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

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