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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. }
  394. // PushUpdate must be called for any push actions in order to
  395. // generates necessary push action history feeds and other operations
  396. func PushUpdate(repo *models.Repository, branch string, opts PushUpdateOptions) error {
  397. isNewRef := opts.OldCommitID == git.EmptySHA
  398. isDelRef := opts.NewCommitID == git.EmptySHA
  399. if isNewRef && isDelRef {
  400. return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  401. }
  402. repoPath := models.RepoPath(opts.RepoUserName, opts.RepoName)
  403. _, err := git.NewCommand("update-server-info").RunInDir(repoPath)
  404. if err != nil {
  405. return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
  406. }
  407. gitRepo, err := git.OpenRepository(repoPath)
  408. if err != nil {
  409. return fmt.Errorf("OpenRepository: %v", err)
  410. }
  411. defer gitRepo.Close()
  412. if err = repo.UpdateSize(); err != nil {
  413. log.Error("Failed to update size for repository: %v", err)
  414. }
  415. var commits = &models.PushCommits{}
  416. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  417. // If is tag reference
  418. tagName := opts.RefFullName[len(git.TagPrefix):]
  419. if isDelRef {
  420. err = models.PushUpdateDeleteTag(repo, tagName)
  421. if err != nil {
  422. return fmt.Errorf("PushUpdateDeleteTag: %v", err)
  423. }
  424. } else {
  425. // Clear cache for tag commit count
  426. cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
  427. err = models.PushUpdateAddTag(repo, gitRepo, tagName)
  428. if err != nil {
  429. return fmt.Errorf("PushUpdateAddTag: %v", err)
  430. }
  431. }
  432. } else if !isDelRef {
  433. // If is branch reference
  434. // Clear cache for branch commit count
  435. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefFullName[len(git.BranchPrefix):], true))
  436. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  437. if err != nil {
  438. return fmt.Errorf("gitRepo.GetCommit: %v", err)
  439. }
  440. // Push new branch.
  441. var l *list.List
  442. if isNewRef {
  443. l, err = newCommit.CommitsBeforeLimit(10)
  444. if err != nil {
  445. return fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  446. }
  447. } else {
  448. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  449. if err != nil {
  450. return fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  451. }
  452. }
  453. commits = models.ListToPushCommits(l)
  454. }
  455. if err := CommitRepoAction(CommitRepoActionOptions{
  456. PusherName: opts.PusherName,
  457. RepoOwnerID: repo.OwnerID,
  458. RepoName: repo.Name,
  459. RefFullName: opts.RefFullName,
  460. OldCommitID: opts.OldCommitID,
  461. NewCommitID: opts.NewCommitID,
  462. Commits: commits,
  463. }); err != nil {
  464. return fmt.Errorf("CommitRepoAction: %v", err)
  465. }
  466. pusher, err := models.GetUserByID(opts.PusherID)
  467. if err != nil {
  468. return err
  469. }
  470. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  471. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  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. return nil
  476. }