repo.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "bytes"
  7. "container/list"
  8. "errors"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/Unknwon/com"
  15. )
  16. // Repository represents a Git repository.
  17. type Repository struct {
  18. Path string
  19. commitCache *objectCache
  20. tagCache *objectCache
  21. }
  22. const _PRETTY_LOG_FORMAT = `--pretty=format:%H`
  23. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) {
  24. l := list.New()
  25. if len(logs) == 0 {
  26. return l, nil
  27. }
  28. parts := bytes.Split(logs, []byte{'\n'})
  29. for _, commitId := range parts {
  30. commit, err := repo.GetCommit(string(commitId))
  31. if err != nil {
  32. return nil, err
  33. }
  34. l.PushBack(commit)
  35. }
  36. return l, nil
  37. }
  38. type NetworkOptions struct {
  39. URL string
  40. Timeout time.Duration
  41. }
  42. // IsRepoURLAccessible checks if given repository URL is accessible.
  43. func IsRepoURLAccessible(opts NetworkOptions) bool {
  44. cmd := NewCommand("ls-remote", "-q", "-h", opts.URL, "HEAD")
  45. if opts.Timeout <= 0 {
  46. opts.Timeout = -1
  47. }
  48. _, err := cmd.RunTimeout(opts.Timeout)
  49. if err != nil {
  50. return false
  51. }
  52. return true
  53. }
  54. // InitRepository initializes a new Git repository.
  55. func InitRepository(repoPath string, bare bool) error {
  56. os.MkdirAll(repoPath, os.ModePerm)
  57. cmd := NewCommand("init")
  58. if bare {
  59. cmd.AddArguments("--bare")
  60. }
  61. _, err := cmd.RunInDir(repoPath)
  62. return err
  63. }
  64. // OpenRepository opens the repository at the given path.
  65. func OpenRepository(repoPath string) (*Repository, error) {
  66. repoPath, err := filepath.Abs(repoPath)
  67. if err != nil {
  68. return nil, err
  69. } else if !isDir(repoPath) {
  70. return nil, errors.New("no such file or directory")
  71. }
  72. return &Repository{
  73. Path: repoPath,
  74. commitCache: newObjectCache(),
  75. tagCache: newObjectCache(),
  76. }, nil
  77. }
  78. type CloneRepoOptions struct {
  79. Mirror bool
  80. Bare bool
  81. Quiet bool
  82. Branch string
  83. Timeout time.Duration
  84. }
  85. // Clone clones original repository to target path.
  86. func Clone(from, to string, opts CloneRepoOptions) (err error) {
  87. toDir := path.Dir(to)
  88. if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
  89. return err
  90. }
  91. cmd := NewCommand("clone")
  92. if opts.Mirror {
  93. cmd.AddArguments("--mirror")
  94. }
  95. if opts.Bare {
  96. cmd.AddArguments("--bare")
  97. }
  98. if opts.Quiet {
  99. cmd.AddArguments("--quiet")
  100. }
  101. if len(opts.Branch) > 0 {
  102. cmd.AddArguments("-b", opts.Branch)
  103. }
  104. cmd.AddArguments(from, to)
  105. if opts.Timeout <= 0 {
  106. opts.Timeout = -1
  107. }
  108. _, err = cmd.RunTimeout(opts.Timeout)
  109. return err
  110. }
  111. type FetchRemoteOptions struct {
  112. Prune bool
  113. Timeout time.Duration
  114. }
  115. // Fetch fetches changes from remotes without merging.
  116. func Fetch(repoPath string, opts FetchRemoteOptions) error {
  117. cmd := NewCommand("fetch")
  118. if opts.Prune {
  119. cmd.AddArguments("--prune")
  120. }
  121. if opts.Timeout <= 0 {
  122. opts.Timeout = -1
  123. }
  124. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  125. return err
  126. }
  127. type PullRemoteOptions struct {
  128. All bool
  129. Rebase bool
  130. Remote string
  131. Branch string
  132. Timeout time.Duration
  133. }
  134. // Pull pulls changes from remotes.
  135. func Pull(repoPath string, opts PullRemoteOptions) error {
  136. cmd := NewCommand("pull")
  137. if opts.Rebase {
  138. cmd.AddArguments("--rebase")
  139. }
  140. if opts.All {
  141. cmd.AddArguments("--all")
  142. } else {
  143. cmd.AddArguments(opts.Remote)
  144. cmd.AddArguments(opts.Branch)
  145. }
  146. if opts.Timeout <= 0 {
  147. opts.Timeout = -1
  148. }
  149. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  150. return err
  151. }
  152. // Push pushs local commits to given remote branch.
  153. func Push(repoPath, remote, branch string) error {
  154. _, err := NewCommand("push", remote, branch).RunInDir(repoPath)
  155. return err
  156. }
  157. type CheckoutOptions struct {
  158. Branch string
  159. OldBranch string
  160. Timeout time.Duration
  161. }
  162. // Checkout checkouts a branch
  163. func Checkout(repoPath string, opts CheckoutOptions) error {
  164. cmd := NewCommand("checkout")
  165. if len(opts.OldBranch) > 0 {
  166. cmd.AddArguments("-b")
  167. }
  168. cmd.AddArguments(opts.Branch)
  169. if len(opts.OldBranch) > 0 {
  170. cmd.AddArguments(opts.OldBranch)
  171. }
  172. if opts.Timeout <= 0 {
  173. opts.Timeout = -1
  174. }
  175. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  176. return err
  177. }
  178. // ResetHEAD resets HEAD to given revision or head of branch.
  179. func ResetHEAD(repoPath string, hard bool, revision string) error {
  180. cmd := NewCommand("reset")
  181. if hard {
  182. cmd.AddArguments("--hard")
  183. }
  184. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  185. return err
  186. }
  187. // MoveFile moves a file to another file or directory.
  188. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  189. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  190. return err
  191. }
  192. // CountObject represents disk usage report of Git repository.
  193. type CountObject struct {
  194. Count int64
  195. Size int64
  196. InPack int64
  197. Packs int64
  198. SizePack int64
  199. PrunePackable int64
  200. Garbage int64
  201. SizeGarbage int64
  202. }
  203. const (
  204. _STAT_COUNT = "count: "
  205. _STAT_SIZE = "size: "
  206. _STAT_IN_PACK = "in-pack: "
  207. _STAT_PACKS = "packs: "
  208. _STAT_SIZE_PACK = "size-pack: "
  209. _STAT_PRUNE_PACKABLE = "prune-packable: "
  210. _STAT_GARBAGE = "garbage: "
  211. _STAT_SIZE_GARBAGE = "size-garbage: "
  212. )
  213. // GetRepoSize returns disk usage report of repository in given path.
  214. func GetRepoSize(repoPath string) (*CountObject, error) {
  215. cmd := NewCommand("count-objects", "-v")
  216. stdout, err := cmd.RunInDir(repoPath)
  217. if err != nil {
  218. return nil, err
  219. }
  220. countObject := new(CountObject)
  221. for _, line := range strings.Split(stdout, "\n") {
  222. switch {
  223. case strings.HasPrefix(line, _STAT_COUNT):
  224. countObject.Count = com.StrTo(line[7:]).MustInt64()
  225. case strings.HasPrefix(line, _STAT_SIZE):
  226. countObject.Size = com.StrTo(line[6:]).MustInt64() * 1024
  227. case strings.HasPrefix(line, _STAT_IN_PACK):
  228. countObject.InPack = com.StrTo(line[9:]).MustInt64()
  229. case strings.HasPrefix(line, _STAT_PACKS):
  230. countObject.Packs = com.StrTo(line[7:]).MustInt64()
  231. case strings.HasPrefix(line, _STAT_SIZE_PACK):
  232. countObject.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
  233. case strings.HasPrefix(line, _STAT_PRUNE_PACKABLE):
  234. countObject.PrunePackable = com.StrTo(line[16:]).MustInt64()
  235. case strings.HasPrefix(line, _STAT_GARBAGE):
  236. countObject.Garbage = com.StrTo(line[9:]).MustInt64()
  237. case strings.HasPrefix(line, _STAT_SIZE_GARBAGE):
  238. countObject.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
  239. }
  240. }
  241. return countObject, nil
  242. }
  243. // GetLatestCommitDate returns the date of latest commit of repository.
  244. // If branch is empty, it returns the latest commit across all branches.
  245. func GetLatestCommitDate(repoPath, branch string) (time.Time, error) {
  246. cmd := NewCommand("for-each-ref", "--count=1", "--sort=-committerdate", "--format=%(committerdate:iso8601)")
  247. if len(branch) > 0 {
  248. cmd.AddArguments("refs/heads/" + branch)
  249. }
  250. stdout, err := cmd.RunInDir(repoPath)
  251. if err != nil {
  252. return time.Time{}, err
  253. }
  254. return time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(stdout))
  255. }