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

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