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

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