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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. var outbuf, errbuf strings.Builder
  223. err := cmd.RunInDirTimeoutEnvPipeline(opts.Env, -1, repoPath, &outbuf, &errbuf)
  224. if err != nil {
  225. if strings.Contains(errbuf.String(), "non-fast-forward") {
  226. return &ErrPushOutOfDate{
  227. StdOut: outbuf.String(),
  228. StdErr: errbuf.String(),
  229. Err: err,
  230. }
  231. } else if strings.Contains(errbuf.String(), "! [remote rejected]") {
  232. err := &ErrPushRejected{
  233. StdOut: outbuf.String(),
  234. StdErr: errbuf.String(),
  235. Err: err,
  236. }
  237. err.GenerateMessage()
  238. return err
  239. }
  240. }
  241. if errbuf.Len() > 0 && err != nil {
  242. return fmt.Errorf("%v - %s", err, errbuf.String())
  243. }
  244. return err
  245. }
  246. // CheckoutOptions options when heck out some branch
  247. type CheckoutOptions struct {
  248. Timeout time.Duration
  249. Branch string
  250. OldBranch string
  251. }
  252. // Checkout checkouts a branch
  253. func Checkout(repoPath string, opts CheckoutOptions) error {
  254. cmd := NewCommand("checkout")
  255. if len(opts.OldBranch) > 0 {
  256. cmd.AddArguments("-b")
  257. }
  258. if opts.Timeout <= 0 {
  259. opts.Timeout = -1
  260. }
  261. cmd.AddArguments(opts.Branch)
  262. if len(opts.OldBranch) > 0 {
  263. cmd.AddArguments(opts.OldBranch)
  264. }
  265. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  266. return err
  267. }
  268. // ResetHEAD resets HEAD to given revision or head of branch.
  269. func ResetHEAD(repoPath string, hard bool, revision string) error {
  270. cmd := NewCommand("reset")
  271. if hard {
  272. cmd.AddArguments("--hard")
  273. }
  274. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  275. return err
  276. }
  277. // MoveFile moves a file to another file or directory.
  278. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  279. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  280. return err
  281. }
  282. // CountObject represents repository count objects report
  283. type CountObject struct {
  284. Count int64
  285. Size int64
  286. InPack int64
  287. Packs int64
  288. SizePack int64
  289. PrunePack int64
  290. Garbage int64
  291. SizeGarbage int64
  292. }
  293. const (
  294. statCount = "count: "
  295. statSize = "size: "
  296. statInpack = "in-pack: "
  297. statPacks = "packs: "
  298. statSizePack = "size-pack: "
  299. statPrunePackage = "prune-package: "
  300. statGarbage = "garbage: "
  301. statSizeGarbage = "size-garbage: "
  302. )
  303. // CountObjects returns the results of git count-objects on the repoPath
  304. func CountObjects(repoPath string) (*CountObject, error) {
  305. cmd := NewCommand("count-objects", "-v")
  306. stdout, err := cmd.RunInDir(repoPath)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return parseSize(stdout), nil
  311. }
  312. // parseSize parses the output from count-objects and return a CountObject
  313. func parseSize(objects string) *CountObject {
  314. repoSize := new(CountObject)
  315. for _, line := range strings.Split(objects, "\n") {
  316. switch {
  317. case strings.HasPrefix(line, statCount):
  318. repoSize.Count = com.StrTo(line[7:]).MustInt64()
  319. case strings.HasPrefix(line, statSize):
  320. repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024
  321. case strings.HasPrefix(line, statInpack):
  322. repoSize.InPack = com.StrTo(line[9:]).MustInt64()
  323. case strings.HasPrefix(line, statPacks):
  324. repoSize.Packs = com.StrTo(line[7:]).MustInt64()
  325. case strings.HasPrefix(line, statSizePack):
  326. repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
  327. case strings.HasPrefix(line, statPrunePackage):
  328. repoSize.PrunePack = com.StrTo(line[16:]).MustInt64()
  329. case strings.HasPrefix(line, statGarbage):
  330. repoSize.Garbage = com.StrTo(line[9:]).MustInt64()
  331. case strings.HasPrefix(line, statSizeGarbage):
  332. repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
  333. }
  334. }
  335. return repoSize
  336. }
  337. // GetLatestCommitTime returns time for latest commit in repository (across all branches)
  338. func GetLatestCommitTime(repoPath string) (time.Time, error) {
  339. cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)")
  340. stdout, err := cmd.RunInDir(repoPath)
  341. if err != nil {
  342. return time.Time{}, err
  343. }
  344. commitTime := strings.TrimSpace(stdout)
  345. return time.Parse(GitTimeLayout, commitTime)
  346. }
  347. // DivergeObject represents commit count diverging commits
  348. type DivergeObject struct {
  349. Ahead int
  350. Behind int
  351. }
  352. func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) {
  353. branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
  354. cmd := NewCommand("rev-list", "--count", branches)
  355. stdout, err := cmd.RunInDir(repoPath)
  356. if err != nil {
  357. return -1, err
  358. }
  359. outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n"))
  360. if errInteger != nil {
  361. return -1, errInteger
  362. }
  363. return outInteger, nil
  364. }
  365. // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
  366. func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) {
  367. // $(git rev-list --count master..feature) commits ahead of master
  368. ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch)
  369. if errorAhead != nil {
  370. return DivergeObject{}, errorAhead
  371. }
  372. // $(git rev-list --count feature..master) commits behind master
  373. behind, errorBehind := checkDivergence(repoPath, targetBranch, baseBranch)
  374. if errorBehind != nil {
  375. return DivergeObject{}, errorBehind
  376. }
  377. return DivergeObject{ahead, behind}, nil
  378. }