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

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