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.

update.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. executable := false
  188. if !opts.IsNewFile {
  189. fromEntry, err := commit.GetTreeEntryByPath(fromTreePath)
  190. if err != nil {
  191. return nil, err
  192. }
  193. if opts.SHA != "" {
  194. // If a SHA was given and the SHA given doesn't match the SHA of the fromTreePath, throw error
  195. if opts.SHA != fromEntry.ID.String() {
  196. return nil, models.ErrSHADoesNotMatch{
  197. Path: treePath,
  198. GivenSHA: opts.SHA,
  199. CurrentSHA: fromEntry.ID.String(),
  200. }
  201. }
  202. } else if opts.LastCommitID != "" {
  203. // If a lastCommitID was given and it doesn't match the commitID of the head of the branch throw
  204. // an error, but only if we aren't creating a new branch.
  205. if commit.ID.String() != opts.LastCommitID && opts.OldBranch == opts.NewBranch {
  206. if changed, err := commit.FileChangedSinceCommit(treePath, opts.LastCommitID); err != nil {
  207. return nil, err
  208. } else if changed {
  209. return nil, models.ErrCommitIDDoesNotMatch{
  210. GivenCommitID: opts.LastCommitID,
  211. CurrentCommitID: opts.LastCommitID,
  212. }
  213. }
  214. // The file wasn't modified, so we are good to delete it
  215. }
  216. } else {
  217. // When updating a file, a lastCommitID or SHA needs to be given to make sure other commits
  218. // haven't been made. We throw an error if one wasn't provided.
  219. return nil, models.ErrSHAOrCommitIDNotProvided{}
  220. }
  221. encoding, bom = detectEncodingAndBOM(fromEntry, repo)
  222. executable = fromEntry.IsExecutable()
  223. }
  224. // For the path where this file will be created/updated, we need to make
  225. // sure no parts of the path are existing files or links except for the last
  226. // item in the path which is the file name, and that shouldn't exist IF it is
  227. // a new file OR is being moved to a new path.
  228. treePathParts := strings.Split(treePath, "/")
  229. subTreePath := ""
  230. for index, part := range treePathParts {
  231. subTreePath = path.Join(subTreePath, part)
  232. entry, err := commit.GetTreeEntryByPath(subTreePath)
  233. if err != nil {
  234. if git.IsErrNotExist(err) {
  235. // Means there is no item with that name, so we're good
  236. break
  237. }
  238. return nil, err
  239. }
  240. if index < len(treePathParts)-1 {
  241. if !entry.IsDir() {
  242. return nil, models.ErrFilePathInvalid{
  243. Message: fmt.Sprintf("a file exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  244. Path: subTreePath,
  245. Name: part,
  246. Type: git.EntryModeBlob,
  247. }
  248. }
  249. } else if entry.IsLink() {
  250. return nil, models.ErrFilePathInvalid{
  251. Message: fmt.Sprintf("a symbolic link exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  252. Path: subTreePath,
  253. Name: part,
  254. Type: git.EntryModeSymlink,
  255. }
  256. } else if entry.IsDir() {
  257. return nil, models.ErrFilePathInvalid{
  258. Message: fmt.Sprintf("a directory exists where you’re trying to create a file [path: %s]", subTreePath),
  259. Path: subTreePath,
  260. Name: part,
  261. Type: git.EntryModeTree,
  262. }
  263. } else if fromTreePath != treePath || opts.IsNewFile {
  264. // The entry shouldn't exist if we are creating new file or moving to a new path
  265. return nil, models.ErrRepoFileAlreadyExists{
  266. Path: treePath,
  267. }
  268. }
  269. }
  270. // Get the two paths (might be the same if not moving) from the index if they exist
  271. filesInIndex, err := t.LsFiles(opts.TreePath, opts.FromTreePath)
  272. if err != nil {
  273. return nil, fmt.Errorf("UpdateRepoFile: %v", err)
  274. }
  275. // If is a new file (not updating) then the given path shouldn't exist
  276. if opts.IsNewFile {
  277. for _, file := range filesInIndex {
  278. if file == opts.TreePath {
  279. return nil, models.ErrRepoFileAlreadyExists{
  280. Path: opts.TreePath,
  281. }
  282. }
  283. }
  284. }
  285. // Remove the old path from the tree
  286. if fromTreePath != treePath && len(filesInIndex) > 0 {
  287. for _, file := range filesInIndex {
  288. if file == fromTreePath {
  289. if err := t.RemoveFilesFromIndex(opts.FromTreePath); err != nil {
  290. return nil, err
  291. }
  292. }
  293. }
  294. }
  295. content := opts.Content
  296. if bom {
  297. content = string(charset.UTF8BOM) + content
  298. }
  299. if encoding != "UTF-8" {
  300. charsetEncoding, _ := stdcharset.Lookup(encoding)
  301. if charsetEncoding != nil {
  302. result, _, err := transform.String(charsetEncoding.NewEncoder(), content)
  303. if err != nil {
  304. // Look if we can't encode back in to the original we should just stick with utf-8
  305. log.Error("Error re-encoding %s (%s) as %s - will stay as UTF-8: %v", opts.TreePath, opts.FromTreePath, encoding, err)
  306. result = content
  307. }
  308. content = result
  309. } else {
  310. log.Error("Unknown encoding: %s", encoding)
  311. }
  312. }
  313. // Reset the opts.Content to our adjusted content to ensure that LFS gets the correct content
  314. opts.Content = content
  315. var lfsMetaObject *models.LFSMetaObject
  316. if setting.LFS.StartServer {
  317. // Check there is no way this can return multiple infos
  318. filename2attribute2info, err := t.CheckAttribute("filter", treePath)
  319. if err != nil {
  320. return nil, err
  321. }
  322. if filename2attribute2info[treePath] != nil && filename2attribute2info[treePath]["filter"] == "lfs" {
  323. // OK so we are supposed to LFS this data!
  324. oid, err := models.GenerateLFSOid(strings.NewReader(opts.Content))
  325. if err != nil {
  326. return nil, err
  327. }
  328. lfsMetaObject = &models.LFSMetaObject{Oid: oid, Size: int64(len(opts.Content)), RepositoryID: repo.ID}
  329. content = lfsMetaObject.Pointer()
  330. }
  331. }
  332. // Add the object to the database
  333. objectHash, err := t.HashObject(strings.NewReader(content))
  334. if err != nil {
  335. return nil, err
  336. }
  337. // Add the object to the index
  338. if executable {
  339. if err := t.AddObjectToIndex("100755", objectHash, treePath); err != nil {
  340. return nil, err
  341. }
  342. } else {
  343. if err := t.AddObjectToIndex("100644", objectHash, treePath); err != nil {
  344. return nil, err
  345. }
  346. }
  347. // Now write the tree
  348. treeHash, err := t.WriteTree()
  349. if err != nil {
  350. return nil, err
  351. }
  352. // Now commit the tree
  353. var commitHash string
  354. if opts.Dates != nil {
  355. commitHash, err = t.CommitTreeWithDate(author, committer, treeHash, message, opts.Dates.Author, opts.Dates.Committer)
  356. } else {
  357. commitHash, err = t.CommitTree(author, committer, treeHash, message)
  358. }
  359. if err != nil {
  360. return nil, err
  361. }
  362. if lfsMetaObject != nil {
  363. // We have an LFS object - create it
  364. lfsMetaObject, err = models.NewLFSMetaObject(lfsMetaObject)
  365. if err != nil {
  366. return nil, err
  367. }
  368. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  369. if !contentStore.Exists(lfsMetaObject) {
  370. if err := contentStore.Put(lfsMetaObject, strings.NewReader(opts.Content)); err != nil {
  371. if _, err2 := repo.RemoveLFSMetaObjectByOid(lfsMetaObject.Oid); err2 != nil {
  372. return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %v)", lfsMetaObject.Oid, err2, err)
  373. }
  374. return nil, err
  375. }
  376. }
  377. }
  378. // Then push this tree to NewBranch
  379. if err := t.Push(doer, commitHash, opts.NewBranch); err != nil {
  380. return nil, err
  381. }
  382. commit, err = t.GetCommit(commitHash)
  383. if err != nil {
  384. return nil, err
  385. }
  386. file, err := GetFileResponseFromCommit(repo, commit, opts.NewBranch, treePath)
  387. if err != nil {
  388. return nil, err
  389. }
  390. return file, nil
  391. }
  392. // PushUpdateOptions defines the push update options
  393. type PushUpdateOptions struct {
  394. PusherID int64
  395. PusherName string
  396. RepoUserName string
  397. RepoName string
  398. RefFullName string
  399. OldCommitID string
  400. NewCommitID string
  401. Branch string
  402. }
  403. // PushUpdate must be called for any push actions in order to
  404. // generates necessary push action history feeds and other operations
  405. func PushUpdate(repo *models.Repository, branch string, opts PushUpdateOptions) error {
  406. isNewRef := opts.OldCommitID == git.EmptySHA
  407. isDelRef := opts.NewCommitID == git.EmptySHA
  408. if isNewRef && isDelRef {
  409. return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  410. }
  411. repoPath := models.RepoPath(opts.RepoUserName, opts.RepoName)
  412. _, err := git.NewCommand("update-server-info").RunInDir(repoPath)
  413. if err != nil {
  414. return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
  415. }
  416. gitRepo, err := git.OpenRepository(repoPath)
  417. if err != nil {
  418. return fmt.Errorf("OpenRepository: %v", err)
  419. }
  420. defer gitRepo.Close()
  421. if err = repo.UpdateSize(); err != nil {
  422. log.Error("Failed to update size for repository: %v", err)
  423. }
  424. commitRepoActionOptions, err := createCommitRepoActionOption(repo, gitRepo, &opts)
  425. if err != nil {
  426. return err
  427. }
  428. if err := CommitRepoAction(commitRepoActionOptions); err != nil {
  429. return fmt.Errorf("CommitRepoAction: %v", err)
  430. }
  431. pusher, err := models.GetUserByID(opts.PusherID)
  432. if err != nil {
  433. return err
  434. }
  435. if !isDelRef {
  436. if err = models.RemoveDeletedBranch(repo.ID, opts.Branch); err != nil {
  437. log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, opts.Branch, err)
  438. }
  439. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  440. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  441. // close all related pulls
  442. } else if err = pull_service.CloseBranchPulls(pusher, repo.ID, branch); err != nil {
  443. log.Error("close related pull request failed: %v", err)
  444. }
  445. if err = models.WatchIfAuto(opts.PusherID, repo.ID, true); err != nil {
  446. log.Warn("Fail to perform auto watch on user %v for repo %v: %v", opts.PusherID, repo.ID, err)
  447. }
  448. return nil
  449. }
  450. // PushUpdates generates push action history feeds for push updating multiple refs
  451. func PushUpdates(repo *models.Repository, optsList []*PushUpdateOptions) error {
  452. repoPath := repo.RepoPath()
  453. _, err := git.NewCommand("update-server-info").RunInDir(repoPath)
  454. if err != nil {
  455. return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
  456. }
  457. gitRepo, err := git.OpenRepository(repoPath)
  458. if err != nil {
  459. return fmt.Errorf("OpenRepository: %v", err)
  460. }
  461. if err = repo.UpdateSize(); err != nil {
  462. log.Error("Failed to update size for repository: %v", err)
  463. }
  464. actions, err := createCommitRepoActions(repo, gitRepo, optsList)
  465. if err != nil {
  466. return err
  467. }
  468. if err := CommitRepoAction(actions...); err != nil {
  469. return fmt.Errorf("CommitRepoAction: %v", err)
  470. }
  471. var pusher *models.User
  472. for _, opts := range optsList {
  473. if pusher == nil || pusher.ID != opts.PusherID {
  474. var err error
  475. pusher, err = models.GetUserByID(opts.PusherID)
  476. if err != nil {
  477. return err
  478. }
  479. }
  480. if opts.NewCommitID != git.EmptySHA {
  481. if err = models.RemoveDeletedBranch(repo.ID, opts.Branch); err != nil {
  482. log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, opts.Branch, err)
  483. }
  484. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, opts.Branch, pusher.Name)
  485. go pull_service.AddTestPullRequestTask(pusher, repo.ID, opts.Branch, true)
  486. // close all related pulls
  487. } else if err = pull_service.CloseBranchPulls(pusher, repo.ID, opts.Branch); err != nil {
  488. log.Error("close related pull request failed: %v", err)
  489. }
  490. if err = models.WatchIfAuto(opts.PusherID, repo.ID, true); err != nil {
  491. log.Warn("Fail to perform auto watch on user %v for repo %v: %v", opts.PusherID, repo.ID, err)
  492. }
  493. }
  494. return nil
  495. }
  496. func createCommitRepoActions(repo *models.Repository, gitRepo *git.Repository, optsList []*PushUpdateOptions) ([]*CommitRepoActionOptions, error) {
  497. addTags := make([]string, 0, len(optsList))
  498. delTags := make([]string, 0, len(optsList))
  499. actions := make([]*CommitRepoActionOptions, 0, len(optsList))
  500. for _, opts := range optsList {
  501. isNewRef := opts.OldCommitID == git.EmptySHA
  502. isDelRef := opts.NewCommitID == git.EmptySHA
  503. if isNewRef && isDelRef {
  504. return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  505. }
  506. var commits = &models.PushCommits{}
  507. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  508. // If is tag reference
  509. tagName := opts.RefFullName[len(git.TagPrefix):]
  510. if isDelRef {
  511. delTags = append(delTags, tagName)
  512. } else {
  513. cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
  514. addTags = append(addTags, tagName)
  515. }
  516. } else if !isDelRef {
  517. // If is branch reference
  518. // Clear cache for branch commit count
  519. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefFullName[len(git.BranchPrefix):], true))
  520. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  521. if err != nil {
  522. return nil, fmt.Errorf("gitRepo.GetCommit: %v", err)
  523. }
  524. // Push new branch.
  525. var l *list.List
  526. if isNewRef {
  527. l, err = newCommit.CommitsBeforeLimit(10)
  528. if err != nil {
  529. return nil, fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  530. }
  531. } else {
  532. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  533. if err != nil {
  534. return nil, fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  535. }
  536. }
  537. commits = models.ListToPushCommits(l)
  538. }
  539. actions = append(actions, &CommitRepoActionOptions{
  540. PusherName: opts.PusherName,
  541. RepoOwnerID: repo.OwnerID,
  542. RepoName: repo.Name,
  543. RefFullName: opts.RefFullName,
  544. OldCommitID: opts.OldCommitID,
  545. NewCommitID: opts.NewCommitID,
  546. Commits: commits,
  547. })
  548. }
  549. if err := models.PushUpdateAddDeleteTags(repo, gitRepo, addTags, delTags); err != nil {
  550. return nil, fmt.Errorf("PushUpdateAddDeleteTags: %v", err)
  551. }
  552. return actions, nil
  553. }
  554. func createCommitRepoActionOption(repo *models.Repository, gitRepo *git.Repository, opts *PushUpdateOptions) (*CommitRepoActionOptions, error) {
  555. isNewRef := opts.OldCommitID == git.EmptySHA
  556. isDelRef := opts.NewCommitID == git.EmptySHA
  557. if isNewRef && isDelRef {
  558. return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  559. }
  560. var commits = &models.PushCommits{}
  561. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  562. // If is tag reference
  563. tagName := opts.RefFullName[len(git.TagPrefix):]
  564. if isDelRef {
  565. if err := models.PushUpdateDeleteTag(repo, tagName); err != nil {
  566. return nil, fmt.Errorf("PushUpdateDeleteTag: %v", err)
  567. }
  568. } else {
  569. // Clear cache for tag commit count
  570. cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
  571. if err := models.PushUpdateAddTag(repo, gitRepo, tagName); err != nil {
  572. return nil, fmt.Errorf("PushUpdateAddTag: %v", err)
  573. }
  574. }
  575. } else if !isDelRef {
  576. // If is branch reference
  577. // Clear cache for branch commit count
  578. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefFullName[len(git.BranchPrefix):], true))
  579. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  580. if err != nil {
  581. return nil, fmt.Errorf("gitRepo.GetCommit: %v", err)
  582. }
  583. // Push new branch.
  584. var l *list.List
  585. if isNewRef {
  586. l, err = newCommit.CommitsBeforeLimit(10)
  587. if err != nil {
  588. return nil, fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  589. }
  590. } else {
  591. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  592. if err != nil {
  593. return nil, fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  594. }
  595. }
  596. commits = models.ListToPushCommits(l)
  597. }
  598. return &CommitRepoActionOptions{
  599. PusherName: opts.PusherName,
  600. RepoOwnerID: repo.OwnerID,
  601. RepoName: repo.Name,
  602. RefFullName: opts.RefFullName,
  603. OldCommitID: opts.OldCommitID,
  604. NewCommitID: opts.NewCommitID,
  605. Commits: commits,
  606. }, nil
  607. }