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

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