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

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