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 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "fmt"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. "gopkg.in/src-d/go-billy.v4/osfs"
  19. gogit "gopkg.in/src-d/go-git.v4"
  20. "gopkg.in/src-d/go-git.v4/plumbing/cache"
  21. "gopkg.in/src-d/go-git.v4/storage/filesystem"
  22. )
  23. // Repository represents a Git repository.
  24. type Repository struct {
  25. Path string
  26. tagCache *ObjectCache
  27. gogitRepo *gogit.Repository
  28. gogitStorage *filesystem.Storage
  29. }
  30. const prettyLogFormat = `--pretty=format:%H`
  31. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) {
  32. l := list.New()
  33. if len(logs) == 0 {
  34. return l, nil
  35. }
  36. parts := bytes.Split(logs, []byte{'\n'})
  37. for _, commitID := range parts {
  38. commit, err := repo.GetCommit(string(commitID))
  39. if err != nil {
  40. return nil, err
  41. }
  42. l.PushBack(commit)
  43. }
  44. return l, nil
  45. }
  46. // IsRepoURLAccessible checks if given repository URL is accessible.
  47. func IsRepoURLAccessible(url string) bool {
  48. _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run()
  49. return err == nil
  50. }
  51. // InitRepository initializes a new Git repository.
  52. func InitRepository(repoPath string, bare bool) error {
  53. err := os.MkdirAll(repoPath, os.ModePerm)
  54. if err != nil {
  55. return err
  56. }
  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. fs := osfs.New(repoPath)
  73. _, err = fs.Stat(".git")
  74. if err == nil {
  75. fs, err = fs.Chroot(".git")
  76. if err != nil {
  77. return nil, err
  78. }
  79. }
  80. storage := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{KeepDescriptors: true})
  81. gogitRepo, err := gogit.Open(storage, fs)
  82. if err != nil {
  83. return nil, err
  84. }
  85. return &Repository{
  86. Path: repoPath,
  87. gogitRepo: gogitRepo,
  88. gogitStorage: storage,
  89. tagCache: newObjectCache(),
  90. }, nil
  91. }
  92. // CloneRepoOptions options when clone a repository
  93. type CloneRepoOptions struct {
  94. Timeout time.Duration
  95. Mirror bool
  96. Bare bool
  97. Quiet bool
  98. Branch string
  99. Shared bool
  100. NoCheckout bool
  101. }
  102. // Clone clones original repository to target path.
  103. func Clone(from, to string, opts CloneRepoOptions) (err error) {
  104. toDir := path.Dir(to)
  105. if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
  106. return err
  107. }
  108. cmd := NewCommand("clone")
  109. if opts.Mirror {
  110. cmd.AddArguments("--mirror")
  111. }
  112. if opts.Bare {
  113. cmd.AddArguments("--bare")
  114. }
  115. if opts.Quiet {
  116. cmd.AddArguments("--quiet")
  117. }
  118. if opts.Shared {
  119. cmd.AddArguments("-s")
  120. }
  121. if opts.NoCheckout {
  122. cmd.AddArguments("--no-checkout")
  123. }
  124. if len(opts.Branch) > 0 {
  125. cmd.AddArguments("-b", opts.Branch)
  126. }
  127. cmd.AddArguments("--", from, to)
  128. if opts.Timeout <= 0 {
  129. opts.Timeout = -1
  130. }
  131. _, err = cmd.RunTimeout(opts.Timeout)
  132. return err
  133. }
  134. // PullRemoteOptions options when pull from remote
  135. type PullRemoteOptions struct {
  136. Timeout time.Duration
  137. All bool
  138. Rebase bool
  139. Remote string
  140. Branch string
  141. }
  142. // Pull pulls changes from remotes.
  143. func Pull(repoPath string, opts PullRemoteOptions) error {
  144. cmd := NewCommand("pull")
  145. if opts.Rebase {
  146. cmd.AddArguments("--rebase")
  147. }
  148. if opts.All {
  149. cmd.AddArguments("--all")
  150. } else {
  151. cmd.AddArguments(opts.Remote)
  152. cmd.AddArguments(opts.Branch)
  153. }
  154. if opts.Timeout <= 0 {
  155. opts.Timeout = -1
  156. }
  157. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  158. return err
  159. }
  160. // PushOptions options when push to remote
  161. type PushOptions struct {
  162. Remote string
  163. Branch string
  164. Force bool
  165. Env []string
  166. }
  167. // Push pushs local commits to given remote branch.
  168. func Push(repoPath string, opts PushOptions) error {
  169. cmd := NewCommand("push")
  170. if opts.Force {
  171. cmd.AddArguments("-f")
  172. }
  173. cmd.AddArguments(opts.Remote, opts.Branch)
  174. _, err := cmd.RunInDirWithEnv(repoPath, opts.Env)
  175. return err
  176. }
  177. // CheckoutOptions options when heck out some branch
  178. type CheckoutOptions struct {
  179. Timeout time.Duration
  180. Branch string
  181. OldBranch string
  182. }
  183. // Checkout checkouts a branch
  184. func Checkout(repoPath string, opts CheckoutOptions) error {
  185. cmd := NewCommand("checkout")
  186. if len(opts.OldBranch) > 0 {
  187. cmd.AddArguments("-b")
  188. }
  189. if opts.Timeout <= 0 {
  190. opts.Timeout = -1
  191. }
  192. cmd.AddArguments(opts.Branch)
  193. if len(opts.OldBranch) > 0 {
  194. cmd.AddArguments(opts.OldBranch)
  195. }
  196. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  197. return err
  198. }
  199. // ResetHEAD resets HEAD to given revision or head of branch.
  200. func ResetHEAD(repoPath string, hard bool, revision string) error {
  201. cmd := NewCommand("reset")
  202. if hard {
  203. cmd.AddArguments("--hard")
  204. }
  205. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  206. return err
  207. }
  208. // MoveFile moves a file to another file or directory.
  209. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  210. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  211. return err
  212. }
  213. // CountObject represents repository count objects report
  214. type CountObject struct {
  215. Count int64
  216. Size int64
  217. InPack int64
  218. Packs int64
  219. SizePack int64
  220. PrunePack int64
  221. Garbage int64
  222. SizeGarbage int64
  223. }
  224. const (
  225. statCount = "count: "
  226. statSize = "size: "
  227. statInpack = "in-pack: "
  228. statPacks = "packs: "
  229. statSizePack = "size-pack: "
  230. statPrunePackage = "prune-package: "
  231. statGarbage = "garbage: "
  232. statSizeGarbage = "size-garbage: "
  233. )
  234. // GetRepoSize returns disk consumption for repo in path
  235. func GetRepoSize(repoPath string) (*CountObject, error) {
  236. cmd := NewCommand("count-objects", "-v")
  237. stdout, err := cmd.RunInDir(repoPath)
  238. if err != nil {
  239. return nil, err
  240. }
  241. return parseSize(stdout), nil
  242. }
  243. // parseSize parses the output from count-objects and return a CountObject
  244. func parseSize(objects string) *CountObject {
  245. repoSize := new(CountObject)
  246. for _, line := range strings.Split(objects, "\n") {
  247. switch {
  248. case strings.HasPrefix(line, statCount):
  249. repoSize.Count = com.StrTo(line[7:]).MustInt64()
  250. case strings.HasPrefix(line, statSize):
  251. repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024
  252. case strings.HasPrefix(line, statInpack):
  253. repoSize.InPack = com.StrTo(line[9:]).MustInt64()
  254. case strings.HasPrefix(line, statPacks):
  255. repoSize.Packs = com.StrTo(line[7:]).MustInt64()
  256. case strings.HasPrefix(line, statSizePack):
  257. repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
  258. case strings.HasPrefix(line, statPrunePackage):
  259. repoSize.PrunePack = com.StrTo(line[16:]).MustInt64()
  260. case strings.HasPrefix(line, statGarbage):
  261. repoSize.Garbage = com.StrTo(line[9:]).MustInt64()
  262. case strings.HasPrefix(line, statSizeGarbage):
  263. repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
  264. }
  265. }
  266. return repoSize
  267. }
  268. // GetLatestCommitTime returns time for latest commit in repository (across all branches)
  269. func GetLatestCommitTime(repoPath string) (time.Time, error) {
  270. cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)")
  271. stdout, err := cmd.RunInDir(repoPath)
  272. if err != nil {
  273. return time.Time{}, err
  274. }
  275. commitTime := strings.TrimSpace(stdout)
  276. return time.Parse(GitTimeLayout, commitTime)
  277. }
  278. // DivergeObject represents commit count diverging commits
  279. type DivergeObject struct {
  280. Ahead int
  281. Behind int
  282. }
  283. func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) {
  284. branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
  285. cmd := NewCommand("rev-list", "--count", branches)
  286. stdout, err := cmd.RunInDir(repoPath)
  287. if err != nil {
  288. return -1, err
  289. }
  290. outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n"))
  291. if errInteger != nil {
  292. return -1, errInteger
  293. }
  294. return outInteger, nil
  295. }
  296. // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
  297. func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) {
  298. // $(git rev-list --count master..feature) commits ahead of master
  299. ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch)
  300. if errorAhead != nil {
  301. return DivergeObject{}, errorAhead
  302. }
  303. // $(git rev-list --count feature..master) commits behind master
  304. behind, errorBehind := checkDivergence(repoPath, targetBranch, baseBranch)
  305. if errorBehind != nil {
  306. return DivergeObject{}, errorBehind
  307. }
  308. return DivergeObject{ahead, behind}, nil
  309. }