You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

update.go 20 kB

Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repofiles
  5. import (
  6. "bytes"
  7. "container/list"
  8. "fmt"
  9. "path"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/cache"
  14. "code.gitea.io/gitea/modules/charset"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/lfs"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/structs"
  20. pull_service "code.gitea.io/gitea/services/pull"
  21. stdcharset "golang.org/x/net/html/charset"
  22. "golang.org/x/text/transform"
  23. )
  24. // IdentityOptions for a person's identity like an author or committer
  25. type IdentityOptions struct {
  26. Name string
  27. Email string
  28. }
  29. // CommitDateOptions store dates for GIT_AUTHOR_DATE and GIT_COMMITTER_DATE
  30. type CommitDateOptions struct {
  31. Author time.Time
  32. Committer time.Time
  33. }
  34. // UpdateRepoFileOptions holds the repository file update options
  35. type UpdateRepoFileOptions struct {
  36. LastCommitID string
  37. OldBranch string
  38. NewBranch string
  39. TreePath string
  40. FromTreePath string
  41. Message string
  42. Content string
  43. SHA string
  44. IsNewFile bool
  45. Author *IdentityOptions
  46. Committer *IdentityOptions
  47. Dates *CommitDateOptions
  48. }
  49. func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string, bool) {
  50. reader, err := entry.Blob().DataAsync()
  51. if err != nil {
  52. // return default
  53. return "UTF-8", false
  54. }
  55. defer reader.Close()
  56. buf := make([]byte, 1024)
  57. n, err := reader.Read(buf)
  58. if err != nil {
  59. // return default
  60. return "UTF-8", false
  61. }
  62. buf = buf[:n]
  63. if setting.LFS.StartServer {
  64. meta := lfs.IsPointerFile(&buf)
  65. if meta != nil {
  66. meta, err = repo.GetLFSMetaObjectByOid(meta.Oid)
  67. if err != nil && err != models.ErrLFSObjectNotExist {
  68. // return default
  69. return "UTF-8", false
  70. }
  71. }
  72. if meta != nil {
  73. dataRc, err := lfs.ReadMetaObject(meta)
  74. if err != nil {
  75. // return default
  76. return "UTF-8", false
  77. }
  78. defer dataRc.Close()
  79. buf = make([]byte, 1024)
  80. n, err = dataRc.Read(buf)
  81. if err != nil {
  82. // return default
  83. return "UTF-8", false
  84. }
  85. buf = buf[:n]
  86. }
  87. }
  88. encoding, err := charset.DetectEncoding(buf)
  89. if err != nil {
  90. // just default to utf-8 and no bom
  91. return "UTF-8", false
  92. }
  93. if encoding == "UTF-8" {
  94. return encoding, bytes.Equal(buf[0:3], charset.UTF8BOM)
  95. }
  96. charsetEncoding, _ := stdcharset.Lookup(encoding)
  97. if charsetEncoding == nil {
  98. return "UTF-8", false
  99. }
  100. result, n, err := transform.String(charsetEncoding.NewDecoder(), string(buf))
  101. if err != nil {
  102. // return default
  103. return "UTF-8", false
  104. }
  105. if n > 2 {
  106. return encoding, bytes.Equal([]byte(result)[0:3], charset.UTF8BOM)
  107. }
  108. return encoding, false
  109. }
  110. // CreateOrUpdateRepoFile adds or updates a file in the given repository
  111. func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) {
  112. // If no branch name is set, assume master
  113. if opts.OldBranch == "" {
  114. opts.OldBranch = repo.DefaultBranch
  115. }
  116. if opts.NewBranch == "" {
  117. opts.NewBranch = opts.OldBranch
  118. }
  119. // oldBranch must exist for this operation
  120. if _, err := repo.GetBranch(opts.OldBranch); err != nil {
  121. return nil, err
  122. }
  123. // A NewBranch can be specified for the file to be created/updated in a new branch.
  124. // Check to make sure the branch does not already exist, otherwise we can't proceed.
  125. // If we aren't branching to a new branch, make sure user can commit to the given branch
  126. if opts.NewBranch != opts.OldBranch {
  127. existingBranch, err := repo.GetBranch(opts.NewBranch)
  128. if existingBranch != nil {
  129. return nil, models.ErrBranchAlreadyExists{
  130. BranchName: opts.NewBranch,
  131. }
  132. }
  133. if err != nil && !git.IsErrBranchNotExist(err) {
  134. return nil, err
  135. }
  136. } else if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
  137. return nil, models.ErrUserCannotCommit{UserName: doer.LowerName}
  138. }
  139. // If FromTreePath is not set, set it to the opts.TreePath
  140. if opts.TreePath != "" && opts.FromTreePath == "" {
  141. opts.FromTreePath = opts.TreePath
  142. }
  143. // Check that the path given in opts.treePath is valid (not a git path)
  144. treePath := CleanUploadFileName(opts.TreePath)
  145. if treePath == "" {
  146. return nil, models.ErrFilenameInvalid{
  147. Path: opts.TreePath,
  148. }
  149. }
  150. // If there is a fromTreePath (we are copying it), also clean it up
  151. fromTreePath := CleanUploadFileName(opts.FromTreePath)
  152. if fromTreePath == "" && opts.FromTreePath != "" {
  153. return nil, models.ErrFilenameInvalid{
  154. Path: opts.FromTreePath,
  155. }
  156. }
  157. message := strings.TrimSpace(opts.Message)
  158. author, committer := GetAuthorAndCommitterUsers(opts.Author, opts.Committer, doer)
  159. t, err := NewTemporaryUploadRepository(repo)
  160. if err != nil {
  161. log.Error("%v", err)
  162. }
  163. defer t.Close()
  164. if err := t.Clone(opts.OldBranch); err != nil {
  165. return nil, err
  166. }
  167. if err := t.SetDefaultIndex(); err != nil {
  168. return nil, err
  169. }
  170. // Get the commit of the original branch
  171. commit, err := t.GetBranchCommit(opts.OldBranch)
  172. if err != nil {
  173. return nil, err // Couldn't get a commit for the branch
  174. }
  175. // Assigned LastCommitID in opts if it hasn't been set
  176. if opts.LastCommitID == "" {
  177. opts.LastCommitID = commit.ID.String()
  178. } else {
  179. lastCommitID, err := t.gitRepo.ConvertToSHA1(opts.LastCommitID)
  180. if err != nil {
  181. return nil, fmt.Errorf("DeleteRepoFile: Invalid last commit ID: %v", err)
  182. }
  183. opts.LastCommitID = lastCommitID.String()
  184. }
  185. encoding := "UTF-8"
  186. bom := false
  187. if !opts.IsNewFile {
  188. fromEntry, err := commit.GetTreeEntryByPath(fromTreePath)
  189. if err != nil {
  190. return nil, err
  191. }
  192. if opts.SHA != "" {
  193. // If a SHA was given and the SHA given doesn't match the SHA of the fromTreePath, throw error
  194. if opts.SHA != fromEntry.ID.String() {
  195. return nil, models.ErrSHADoesNotMatch{
  196. Path: treePath,
  197. GivenSHA: opts.SHA,
  198. CurrentSHA: fromEntry.ID.String(),
  199. }
  200. }
  201. } else if opts.LastCommitID != "" {
  202. // If a lastCommitID was given and it doesn't match the commitID of the head of the branch throw
  203. // an error, but only if we aren't creating a new branch.
  204. if commit.ID.String() != opts.LastCommitID && opts.OldBranch == opts.NewBranch {
  205. if changed, err := commit.FileChangedSinceCommit(treePath, opts.LastCommitID); err != nil {
  206. return nil, err
  207. } else if changed {
  208. return nil, models.ErrCommitIDDoesNotMatch{
  209. GivenCommitID: opts.LastCommitID,
  210. CurrentCommitID: opts.LastCommitID,
  211. }
  212. }
  213. // The file wasn't modified, so we are good to delete it
  214. }
  215. } else {
  216. // When updating a file, a lastCommitID or SHA needs to be given to make sure other commits
  217. // haven't been made. We throw an error if one wasn't provided.
  218. return nil, models.ErrSHAOrCommitIDNotProvided{}
  219. }
  220. encoding, bom = detectEncodingAndBOM(fromEntry, repo)
  221. }
  222. // For the path where this file will be created/updated, we need to make
  223. // sure no parts of the path are existing files or links except for the last
  224. // item in the path which is the file name, and that shouldn't exist IF it is
  225. // a new file OR is being moved to a new path.
  226. treePathParts := strings.Split(treePath, "/")
  227. subTreePath := ""
  228. for index, part := range treePathParts {
  229. subTreePath = path.Join(subTreePath, part)
  230. entry, err := commit.GetTreeEntryByPath(subTreePath)
  231. if err != nil {
  232. if git.IsErrNotExist(err) {
  233. // Means there is no item with that name, so we're good
  234. break
  235. }
  236. return nil, err
  237. }
  238. if index < len(treePathParts)-1 {
  239. if !entry.IsDir() {
  240. return nil, models.ErrFilePathInvalid{
  241. Message: fmt.Sprintf("a file exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  242. Path: subTreePath,
  243. Name: part,
  244. Type: git.EntryModeBlob,
  245. }
  246. }
  247. } else if entry.IsLink() {
  248. return nil, models.ErrFilePathInvalid{
  249. Message: fmt.Sprintf("a symbolic link exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  250. Path: subTreePath,
  251. Name: part,
  252. Type: git.EntryModeSymlink,
  253. }
  254. } else if entry.IsDir() {
  255. return nil, models.ErrFilePathInvalid{
  256. Message: fmt.Sprintf("a directory exists where you’re trying to create a file [path: %s]", subTreePath),
  257. Path: subTreePath,
  258. Name: part,
  259. Type: git.EntryModeTree,
  260. }
  261. } else if fromTreePath != treePath || opts.IsNewFile {
  262. // The entry shouldn't exist if we are creating new file or moving to a new path
  263. return nil, models.ErrRepoFileAlreadyExists{
  264. Path: treePath,
  265. }
  266. }
  267. }
  268. // Get the two paths (might be the same if not moving) from the index if they exist
  269. filesInIndex, err := t.LsFiles(opts.TreePath, opts.FromTreePath)
  270. if err != nil {
  271. return nil, fmt.Errorf("UpdateRepoFile: %v", err)
  272. }
  273. // If is a new file (not updating) then the given path shouldn't exist
  274. if opts.IsNewFile {
  275. for _, file := range filesInIndex {
  276. if file == opts.TreePath {
  277. return nil, models.ErrRepoFileAlreadyExists{
  278. Path: opts.TreePath,
  279. }
  280. }
  281. }
  282. }
  283. // Remove the old path from the tree
  284. if fromTreePath != treePath && len(filesInIndex) > 0 {
  285. for _, file := range filesInIndex {
  286. if file == fromTreePath {
  287. if err := t.RemoveFilesFromIndex(opts.FromTreePath); err != nil {
  288. return nil, err
  289. }
  290. }
  291. }
  292. }
  293. content := opts.Content
  294. if bom {
  295. content = string(charset.UTF8BOM) + content
  296. }
  297. if encoding != "UTF-8" {
  298. charsetEncoding, _ := stdcharset.Lookup(encoding)
  299. if charsetEncoding != nil {
  300. result, _, err := transform.String(charsetEncoding.NewEncoder(), content)
  301. if err != nil {
  302. // Look if we can't encode back in to the original we should just stick with utf-8
  303. log.Error("Error re-encoding %s (%s) as %s - will stay as UTF-8: %v", opts.TreePath, opts.FromTreePath, encoding, err)
  304. result = content
  305. }
  306. content = result
  307. } else {
  308. log.Error("Unknown encoding: %s", encoding)
  309. }
  310. }
  311. // Reset the opts.Content to our adjusted content to ensure that LFS gets the correct content
  312. opts.Content = content
  313. var lfsMetaObject *models.LFSMetaObject
  314. if setting.LFS.StartServer {
  315. // Check there is no way this can return multiple infos
  316. filename2attribute2info, err := t.CheckAttribute("filter", treePath)
  317. if err != nil {
  318. return nil, err
  319. }
  320. if filename2attribute2info[treePath] != nil && filename2attribute2info[treePath]["filter"] == "lfs" {
  321. // OK so we are supposed to LFS this data!
  322. oid, err := models.GenerateLFSOid(strings.NewReader(opts.Content))
  323. if err != nil {
  324. return nil, err
  325. }
  326. lfsMetaObject = &models.LFSMetaObject{Oid: oid, Size: int64(len(opts.Content)), RepositoryID: repo.ID}
  327. content = lfsMetaObject.Pointer()
  328. }
  329. }
  330. // Add the object to the database
  331. objectHash, err := t.HashObject(strings.NewReader(content))
  332. if err != nil {
  333. return nil, err
  334. }
  335. // Add the object to the index
  336. if err := t.AddObjectToIndex("100644", objectHash, treePath); err != nil {
  337. return nil, err
  338. }
  339. // Now write the tree
  340. treeHash, err := t.WriteTree()
  341. if err != nil {
  342. return nil, err
  343. }
  344. // Now commit the tree
  345. var commitHash string
  346. if opts.Dates != nil {
  347. commitHash, err = t.CommitTreeWithDate(author, committer, treeHash, message, opts.Dates.Author, opts.Dates.Committer)
  348. } else {
  349. commitHash, err = t.CommitTree(author, committer, treeHash, message)
  350. }
  351. if err != nil {
  352. return nil, err
  353. }
  354. if lfsMetaObject != nil {
  355. // We have an LFS object - create it
  356. lfsMetaObject, err = models.NewLFSMetaObject(lfsMetaObject)
  357. if err != nil {
  358. return nil, err
  359. }
  360. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  361. if !contentStore.Exists(lfsMetaObject) {
  362. if err := contentStore.Put(lfsMetaObject, strings.NewReader(opts.Content)); err != nil {
  363. if _, err2 := repo.RemoveLFSMetaObjectByOid(lfsMetaObject.Oid); err2 != nil {
  364. return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %v)", lfsMetaObject.Oid, err2, err)
  365. }
  366. return nil, err
  367. }
  368. }
  369. }
  370. // Then push this tree to NewBranch
  371. if err := t.Push(doer, commitHash, opts.NewBranch); err != nil {
  372. return nil, err
  373. }
  374. commit, err = t.GetCommit(commitHash)
  375. if err != nil {
  376. return nil, err
  377. }
  378. file, err := GetFileResponseFromCommit(repo, commit, opts.NewBranch, treePath)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return file, nil
  383. }
  384. // PushUpdateOptions defines the push update options
  385. type PushUpdateOptions struct {
  386. PusherID int64
  387. PusherName string
  388. RepoUserName string
  389. RepoName string
  390. RefFullName string
  391. OldCommitID string
  392. NewCommitID string
  393. Branch string
  394. }
  395. // PushUpdate must be called for any push actions in order to
  396. // generates necessary push action history feeds and other operations
  397. func PushUpdate(repo *models.Repository, branch string, opts PushUpdateOptions) error {
  398. isNewRef := opts.OldCommitID == git.EmptySHA
  399. isDelRef := opts.NewCommitID == git.EmptySHA
  400. if isNewRef && isDelRef {
  401. return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  402. }
  403. repoPath := models.RepoPath(opts.RepoUserName, opts.RepoName)
  404. _, err := git.NewCommand("update-server-info").RunInDir(repoPath)
  405. if err != nil {
  406. return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
  407. }
  408. gitRepo, err := git.OpenRepository(repoPath)
  409. if err != nil {
  410. return fmt.Errorf("OpenRepository: %v", err)
  411. }
  412. defer gitRepo.Close()
  413. if err = repo.UpdateSize(); err != nil {
  414. log.Error("Failed to update size for repository: %v", err)
  415. }
  416. commitRepoActionOptions, err := createCommitRepoActionOption(repo, gitRepo, &opts)
  417. if err != nil {
  418. return err
  419. }
  420. if err := CommitRepoAction(commitRepoActionOptions); err != nil {
  421. return fmt.Errorf("CommitRepoAction: %v", err)
  422. }
  423. pusher, err := models.GetUserByID(opts.PusherID)
  424. if err != nil {
  425. return err
  426. }
  427. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  428. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true, opts.OldCommitID, opts.NewCommitID)
  429. if err = models.WatchIfAuto(opts.PusherID, repo.ID, true); err != nil {
  430. log.Warn("Fail to perform auto watch on user %v for repo %v: %v", opts.PusherID, repo.ID, err)
  431. }
  432. return nil
  433. }
  434. // PushUpdates generates push action history feeds for push updating multiple refs
  435. func PushUpdates(repo *models.Repository, optsList []*PushUpdateOptions) error {
  436. repoPath := repo.RepoPath()
  437. _, err := git.NewCommand("update-server-info").RunInDir(repoPath)
  438. if err != nil {
  439. return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
  440. }
  441. gitRepo, err := git.OpenRepository(repoPath)
  442. if err != nil {
  443. return fmt.Errorf("OpenRepository: %v", err)
  444. }
  445. if err = repo.UpdateSize(); err != nil {
  446. log.Error("Failed to update size for repository: %v", err)
  447. }
  448. actions, err := createCommitRepoActions(repo, gitRepo, optsList)
  449. if err != nil {
  450. return err
  451. }
  452. if err := CommitRepoAction(actions...); err != nil {
  453. return fmt.Errorf("CommitRepoAction: %v", err)
  454. }
  455. var pusher *models.User
  456. for _, opts := range optsList {
  457. if pusher == nil || pusher.ID != opts.PusherID {
  458. var err error
  459. pusher, err = models.GetUserByID(opts.PusherID)
  460. if err != nil {
  461. return err
  462. }
  463. }
  464. if opts.NewCommitID != git.EmptySHA {
  465. if err = models.RemoveDeletedBranch(repo.ID, opts.Branch); err != nil {
  466. log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, opts.Branch, err)
  467. }
  468. }
  469. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, opts.Branch, pusher.Name)
  470. go pull_service.AddTestPullRequestTask(pusher, repo.ID, opts.Branch, true, opts.OldCommitID, opts.NewCommitID)
  471. if err = models.WatchIfAuto(opts.PusherID, repo.ID, true); err != nil {
  472. log.Warn("Fail to perform auto watch on user %v for repo %v: %v", opts.PusherID, repo.ID, err)
  473. }
  474. }
  475. return nil
  476. }
  477. func createCommitRepoActions(repo *models.Repository, gitRepo *git.Repository, optsList []*PushUpdateOptions) ([]*CommitRepoActionOptions, error) {
  478. addTags := make([]string, 0, len(optsList))
  479. delTags := make([]string, 0, len(optsList))
  480. actions := make([]*CommitRepoActionOptions, 0, len(optsList))
  481. for _, opts := range optsList {
  482. isNewRef := opts.OldCommitID == git.EmptySHA
  483. isDelRef := opts.NewCommitID == git.EmptySHA
  484. if isNewRef && isDelRef {
  485. return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  486. }
  487. var commits = &models.PushCommits{}
  488. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  489. // If is tag reference
  490. tagName := opts.RefFullName[len(git.TagPrefix):]
  491. if isDelRef {
  492. delTags = append(delTags, tagName)
  493. } else {
  494. cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
  495. addTags = append(addTags, tagName)
  496. }
  497. } else if !isDelRef {
  498. // If is branch reference
  499. // Clear cache for branch commit count
  500. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefFullName[len(git.BranchPrefix):], true))
  501. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  502. if err != nil {
  503. return nil, fmt.Errorf("gitRepo.GetCommit: %v", err)
  504. }
  505. // Push new branch.
  506. var l *list.List
  507. if isNewRef {
  508. l, err = newCommit.CommitsBeforeLimit(10)
  509. if err != nil {
  510. return nil, fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  511. }
  512. } else {
  513. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  514. if err != nil {
  515. return nil, fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  516. }
  517. }
  518. commits = models.ListToPushCommits(l)
  519. }
  520. actions = append(actions, &CommitRepoActionOptions{
  521. PusherName: opts.PusherName,
  522. RepoOwnerID: repo.OwnerID,
  523. RepoName: repo.Name,
  524. RefFullName: opts.RefFullName,
  525. OldCommitID: opts.OldCommitID,
  526. NewCommitID: opts.NewCommitID,
  527. Commits: commits,
  528. })
  529. }
  530. if err := models.PushUpdateAddDeleteTags(repo, gitRepo, addTags, delTags); err != nil {
  531. return nil, fmt.Errorf("PushUpdateAddDeleteTags: %v", err)
  532. }
  533. return actions, nil
  534. }
  535. func createCommitRepoActionOption(repo *models.Repository, gitRepo *git.Repository, opts *PushUpdateOptions) (*CommitRepoActionOptions, error) {
  536. isNewRef := opts.OldCommitID == git.EmptySHA
  537. isDelRef := opts.NewCommitID == git.EmptySHA
  538. if isNewRef && isDelRef {
  539. return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  540. }
  541. var commits = &models.PushCommits{}
  542. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  543. // If is tag reference
  544. tagName := opts.RefFullName[len(git.TagPrefix):]
  545. if isDelRef {
  546. if err := models.PushUpdateDeleteTag(repo, tagName); err != nil {
  547. return nil, fmt.Errorf("PushUpdateDeleteTag: %v", err)
  548. }
  549. } else {
  550. // Clear cache for tag commit count
  551. cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
  552. if err := models.PushUpdateAddTag(repo, gitRepo, tagName); err != nil {
  553. return nil, fmt.Errorf("PushUpdateAddTag: %v", err)
  554. }
  555. }
  556. } else if !isDelRef {
  557. // If is branch reference
  558. // Clear cache for branch commit count
  559. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefFullName[len(git.BranchPrefix):], true))
  560. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  561. if err != nil {
  562. return nil, fmt.Errorf("gitRepo.GetCommit: %v", err)
  563. }
  564. // Push new branch.
  565. var l *list.List
  566. if isNewRef {
  567. l, err = newCommit.CommitsBeforeLimit(10)
  568. if err != nil {
  569. return nil, fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  570. }
  571. } else {
  572. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  573. if err != nil {
  574. return nil, fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  575. }
  576. }
  577. commits = models.ListToPushCommits(l)
  578. }
  579. return &CommitRepoActionOptions{
  580. PusherName: opts.PusherName,
  581. RepoOwnerID: repo.OwnerID,
  582. RepoName: repo.Name,
  583. RefFullName: opts.RefFullName,
  584. OldCommitID: opts.OldCommitID,
  585. NewCommitID: opts.NewCommitID,
  586. Commits: commits,
  587. }, nil
  588. }