You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 7.2KB

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