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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/cache"
  13. "code.gitea.io/gitea/modules/charset"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/lfs"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/structs"
  19. stdcharset "golang.org/x/net/html/charset"
  20. "golang.org/x/text/transform"
  21. )
  22. // IdentityOptions for a person's identity like an author or committer
  23. type IdentityOptions struct {
  24. Name string
  25. Email string
  26. }
  27. // UpdateRepoFileOptions holds the repository file update options
  28. type UpdateRepoFileOptions struct {
  29. LastCommitID string
  30. OldBranch string
  31. NewBranch string
  32. TreePath string
  33. FromTreePath string
  34. Message string
  35. Content string
  36. SHA string
  37. IsNewFile bool
  38. Author *IdentityOptions
  39. Committer *IdentityOptions
  40. }
  41. func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string, bool) {
  42. reader, err := entry.Blob().DataAsync()
  43. if err != nil {
  44. // return default
  45. return "UTF-8", false
  46. }
  47. defer reader.Close()
  48. buf := make([]byte, 1024)
  49. n, err := reader.Read(buf)
  50. if err != nil {
  51. // return default
  52. return "UTF-8", false
  53. }
  54. buf = buf[:n]
  55. if setting.LFS.StartServer {
  56. meta := lfs.IsPointerFile(&buf)
  57. if meta != nil {
  58. meta, err = repo.GetLFSMetaObjectByOid(meta.Oid)
  59. if err != nil && err != models.ErrLFSObjectNotExist {
  60. // return default
  61. return "UTF-8", false
  62. }
  63. }
  64. if meta != nil {
  65. dataRc, err := lfs.ReadMetaObject(meta)
  66. if err != nil {
  67. // return default
  68. return "UTF-8", false
  69. }
  70. defer dataRc.Close()
  71. buf = make([]byte, 1024)
  72. n, err = dataRc.Read(buf)
  73. if err != nil {
  74. // return default
  75. return "UTF-8", false
  76. }
  77. buf = buf[:n]
  78. }
  79. }
  80. encoding, err := charset.DetectEncoding(buf)
  81. if err != nil {
  82. // just default to utf-8 and no bom
  83. return "UTF-8", false
  84. }
  85. if encoding == "UTF-8" {
  86. return encoding, bytes.Equal(buf[0:3], charset.UTF8BOM)
  87. }
  88. charsetEncoding, _ := stdcharset.Lookup(encoding)
  89. if charsetEncoding == nil {
  90. return "UTF-8", false
  91. }
  92. result, n, err := transform.String(charsetEncoding.NewDecoder(), string(buf))
  93. if err != nil {
  94. // return default
  95. return "UTF-8", false
  96. }
  97. if n > 2 {
  98. return encoding, bytes.Equal([]byte(result)[0:3], charset.UTF8BOM)
  99. }
  100. return encoding, false
  101. }
  102. // CreateOrUpdateRepoFile adds or updates a file in the given repository
  103. func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) {
  104. // If no branch name is set, assume master
  105. if opts.OldBranch == "" {
  106. opts.OldBranch = repo.DefaultBranch
  107. }
  108. if opts.NewBranch == "" {
  109. opts.NewBranch = opts.OldBranch
  110. }
  111. // oldBranch must exist for this operation
  112. if _, err := repo.GetBranch(opts.OldBranch); err != nil {
  113. return nil, err
  114. }
  115. // A NewBranch can be specified for the file to be created/updated in a new branch.
  116. // Check to make sure the branch does not already exist, otherwise we can't proceed.
  117. // If we aren't branching to a new branch, make sure user can commit to the given branch
  118. if opts.NewBranch != opts.OldBranch {
  119. existingBranch, err := repo.GetBranch(opts.NewBranch)
  120. if existingBranch != nil {
  121. return nil, models.ErrBranchAlreadyExists{
  122. BranchName: opts.NewBranch,
  123. }
  124. }
  125. if err != nil && !git.IsErrBranchNotExist(err) {
  126. return nil, err
  127. }
  128. } else if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
  129. return nil, models.ErrUserCannotCommit{UserName: doer.LowerName}
  130. }
  131. // If FromTreePath is not set, set it to the opts.TreePath
  132. if opts.TreePath != "" && opts.FromTreePath == "" {
  133. opts.FromTreePath = opts.TreePath
  134. }
  135. // Check that the path given in opts.treePath is valid (not a git path)
  136. treePath := CleanUploadFileName(opts.TreePath)
  137. if treePath == "" {
  138. return nil, models.ErrFilenameInvalid{
  139. Path: opts.TreePath,
  140. }
  141. }
  142. // If there is a fromTreePath (we are copying it), also clean it up
  143. fromTreePath := CleanUploadFileName(opts.FromTreePath)
  144. if fromTreePath == "" && opts.FromTreePath != "" {
  145. return nil, models.ErrFilenameInvalid{
  146. Path: opts.FromTreePath,
  147. }
  148. }
  149. message := strings.TrimSpace(opts.Message)
  150. author, committer := GetAuthorAndCommitterUsers(opts.Committer, opts.Author, doer)
  151. t, err := NewTemporaryUploadRepository(repo)
  152. if err != nil {
  153. log.Error("%v", err)
  154. }
  155. defer t.Close()
  156. if err := t.Clone(opts.OldBranch); err != nil {
  157. return nil, err
  158. }
  159. if err := t.SetDefaultIndex(); err != nil {
  160. return nil, err
  161. }
  162. // Get the commit of the original branch
  163. commit, err := t.GetBranchCommit(opts.OldBranch)
  164. if err != nil {
  165. return nil, err // Couldn't get a commit for the branch
  166. }
  167. // Assigned LastCommitID in opts if it hasn't been set
  168. if opts.LastCommitID == "" {
  169. opts.LastCommitID = commit.ID.String()
  170. } else {
  171. lastCommitID, err := t.gitRepo.ConvertToSHA1(opts.LastCommitID)
  172. if err != nil {
  173. return nil, fmt.Errorf("DeleteRepoFile: Invalid last commit ID: %v", err)
  174. }
  175. opts.LastCommitID = lastCommitID.String()
  176. }
  177. encoding := "UTF-8"
  178. bom := false
  179. if !opts.IsNewFile {
  180. fromEntry, err := commit.GetTreeEntryByPath(fromTreePath)
  181. if err != nil {
  182. return nil, err
  183. }
  184. if opts.SHA != "" {
  185. // If a SHA was given and the SHA given doesn't match the SHA of the fromTreePath, throw error
  186. if opts.SHA != fromEntry.ID.String() {
  187. return nil, models.ErrSHADoesNotMatch{
  188. Path: treePath,
  189. GivenSHA: opts.SHA,
  190. CurrentSHA: fromEntry.ID.String(),
  191. }
  192. }
  193. } else if opts.LastCommitID != "" {
  194. // If a lastCommitID was given and it doesn't match the commitID of the head of the branch throw
  195. // an error, but only if we aren't creating a new branch.
  196. if commit.ID.String() != opts.LastCommitID && opts.OldBranch == opts.NewBranch {
  197. if changed, err := commit.FileChangedSinceCommit(treePath, opts.LastCommitID); err != nil {
  198. return nil, err
  199. } else if changed {
  200. return nil, models.ErrCommitIDDoesNotMatch{
  201. GivenCommitID: opts.LastCommitID,
  202. CurrentCommitID: opts.LastCommitID,
  203. }
  204. }
  205. // The file wasn't modified, so we are good to delete it
  206. }
  207. } else {
  208. // When updating a file, a lastCommitID or SHA needs to be given to make sure other commits
  209. // haven't been made. We throw an error if one wasn't provided.
  210. return nil, models.ErrSHAOrCommitIDNotProvided{}
  211. }
  212. encoding, bom = detectEncodingAndBOM(fromEntry, repo)
  213. }
  214. // For the path where this file will be created/updated, we need to make
  215. // sure no parts of the path are existing files or links except for the last
  216. // item in the path which is the file name, and that shouldn't exist IF it is
  217. // a new file OR is being moved to a new path.
  218. treePathParts := strings.Split(treePath, "/")
  219. subTreePath := ""
  220. for index, part := range treePathParts {
  221. subTreePath = path.Join(subTreePath, part)
  222. entry, err := commit.GetTreeEntryByPath(subTreePath)
  223. if err != nil {
  224. if git.IsErrNotExist(err) {
  225. // Means there is no item with that name, so we're good
  226. break
  227. }
  228. return nil, err
  229. }
  230. if index < len(treePathParts)-1 {
  231. if !entry.IsDir() {
  232. return nil, models.ErrFilePathInvalid{
  233. Message: fmt.Sprintf("a file exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  234. Path: subTreePath,
  235. Name: part,
  236. Type: git.EntryModeBlob,
  237. }
  238. }
  239. } else if entry.IsLink() {
  240. return nil, models.ErrFilePathInvalid{
  241. Message: fmt.Sprintf("a symbolic link exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  242. Path: subTreePath,
  243. Name: part,
  244. Type: git.EntryModeSymlink,
  245. }
  246. } else if entry.IsDir() {
  247. return nil, models.ErrFilePathInvalid{
  248. Message: fmt.Sprintf("a directory exists where you’re trying to create a file [path: %s]", subTreePath),
  249. Path: subTreePath,
  250. Name: part,
  251. Type: git.EntryModeTree,
  252. }
  253. } else if fromTreePath != treePath || opts.IsNewFile {
  254. // The entry shouldn't exist if we are creating new file or moving to a new path
  255. return nil, models.ErrRepoFileAlreadyExists{
  256. Path: treePath,
  257. }
  258. }
  259. }
  260. // Get the two paths (might be the same if not moving) from the index if they exist
  261. filesInIndex, err := t.LsFiles(opts.TreePath, opts.FromTreePath)
  262. if err != nil {
  263. return nil, fmt.Errorf("UpdateRepoFile: %v", err)
  264. }
  265. // If is a new file (not updating) then the given path shouldn't exist
  266. if opts.IsNewFile {
  267. for _, file := range filesInIndex {
  268. if file == opts.TreePath {
  269. return nil, models.ErrRepoFileAlreadyExists{
  270. Path: opts.TreePath,
  271. }
  272. }
  273. }
  274. }
  275. // Remove the old path from the tree
  276. if fromTreePath != treePath && len(filesInIndex) > 0 {
  277. for _, file := range filesInIndex {
  278. if file == fromTreePath {
  279. if err := t.RemoveFilesFromIndex(opts.FromTreePath); err != nil {
  280. return nil, err
  281. }
  282. }
  283. }
  284. }
  285. // Check there is no way this can return multiple infos
  286. filename2attribute2info, err := t.CheckAttribute("filter", treePath)
  287. if err != nil {
  288. return nil, err
  289. }
  290. content := opts.Content
  291. if bom {
  292. content = string(charset.UTF8BOM) + content
  293. }
  294. if encoding != "UTF-8" {
  295. charsetEncoding, _ := stdcharset.Lookup(encoding)
  296. if charsetEncoding != nil {
  297. result, _, err := transform.String(charsetEncoding.NewEncoder(), content)
  298. if err != nil {
  299. // Look if we can't encode back in to the original we should just stick with utf-8
  300. log.Error("Error re-encoding %s (%s) as %s - will stay as UTF-8: %v", opts.TreePath, opts.FromTreePath, encoding, err)
  301. result = content
  302. }
  303. content = result
  304. } else {
  305. log.Error("Unknown encoding: %s", encoding)
  306. }
  307. }
  308. // Reset the opts.Content to our adjusted content to ensure that LFS gets the correct content
  309. opts.Content = content
  310. var lfsMetaObject *models.LFSMetaObject
  311. if setting.LFS.StartServer && filename2attribute2info[treePath] != nil && filename2attribute2info[treePath]["filter"] == "lfs" {
  312. // OK so we are supposed to LFS this data!
  313. oid, err := models.GenerateLFSOid(strings.NewReader(opts.Content))
  314. if err != nil {
  315. return nil, err
  316. }
  317. lfsMetaObject = &models.LFSMetaObject{Oid: oid, Size: int64(len(opts.Content)), RepositoryID: repo.ID}
  318. content = lfsMetaObject.Pointer()
  319. }
  320. // Add the object to the database
  321. objectHash, err := t.HashObject(strings.NewReader(content))
  322. if err != nil {
  323. return nil, err
  324. }
  325. // Add the object to the index
  326. if err := t.AddObjectToIndex("100644", objectHash, treePath); err != nil {
  327. return nil, err
  328. }
  329. // Now write the tree
  330. treeHash, err := t.WriteTree()
  331. if err != nil {
  332. return nil, err
  333. }
  334. // Now commit the tree
  335. commitHash, err := t.CommitTree(author, committer, treeHash, message)
  336. if err != nil {
  337. return nil, err
  338. }
  339. if lfsMetaObject != nil {
  340. // We have an LFS object - create it
  341. lfsMetaObject, err = models.NewLFSMetaObject(lfsMetaObject)
  342. if err != nil {
  343. return nil, err
  344. }
  345. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  346. if !contentStore.Exists(lfsMetaObject) {
  347. if err := contentStore.Put(lfsMetaObject, strings.NewReader(opts.Content)); err != nil {
  348. if err2 := repo.RemoveLFSMetaObjectByOid(lfsMetaObject.Oid); err2 != nil {
  349. return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %v)", lfsMetaObject.Oid, err2, err)
  350. }
  351. return nil, err
  352. }
  353. }
  354. }
  355. // Then push this tree to NewBranch
  356. if err := t.Push(doer, commitHash, opts.NewBranch); err != nil {
  357. return nil, err
  358. }
  359. commit, err = t.GetCommit(commitHash)
  360. if err != nil {
  361. return nil, err
  362. }
  363. file, err := GetFileResponseFromCommit(repo, commit, opts.NewBranch, treePath)
  364. if err != nil {
  365. return nil, err
  366. }
  367. return file, nil
  368. }
  369. // PushUpdate must be called for any push actions in order to
  370. // generates necessary push action history feeds and other operations
  371. func PushUpdate(repo *models.Repository, branch string, opts models.PushUpdateOptions) error {
  372. isNewRef := opts.OldCommitID == git.EmptySHA
  373. isDelRef := opts.NewCommitID == git.EmptySHA
  374. if isNewRef && isDelRef {
  375. return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  376. }
  377. repoPath := models.RepoPath(opts.RepoUserName, opts.RepoName)
  378. _, err := git.NewCommand("update-server-info").RunInDir(repoPath)
  379. if err != nil {
  380. return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
  381. }
  382. gitRepo, err := git.OpenRepository(repoPath)
  383. if err != nil {
  384. return fmt.Errorf("OpenRepository: %v", err)
  385. }
  386. if err = repo.UpdateSize(); err != nil {
  387. log.Error("Failed to update size for repository: %v", err)
  388. }
  389. var commits = &models.PushCommits{}
  390. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  391. // If is tag reference
  392. tagName := opts.RefFullName[len(git.TagPrefix):]
  393. if isDelRef {
  394. err = models.PushUpdateDeleteTag(repo, tagName)
  395. if err != nil {
  396. return fmt.Errorf("PushUpdateDeleteTag: %v", err)
  397. }
  398. } else {
  399. // Clear cache for tag commit count
  400. cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
  401. err = models.PushUpdateAddTag(repo, gitRepo, tagName)
  402. if err != nil {
  403. return fmt.Errorf("PushUpdateAddTag: %v", err)
  404. }
  405. }
  406. } else if !isDelRef {
  407. // If is branch reference
  408. // Clear cache for branch commit count
  409. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefFullName[len(git.BranchPrefix):], true))
  410. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  411. if err != nil {
  412. return fmt.Errorf("gitRepo.GetCommit: %v", err)
  413. }
  414. // Push new branch.
  415. var l *list.List
  416. if isNewRef {
  417. l, err = newCommit.CommitsBeforeLimit(10)
  418. if err != nil {
  419. return fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  420. }
  421. } else {
  422. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  423. if err != nil {
  424. return fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  425. }
  426. }
  427. commits = models.ListToPushCommits(l)
  428. }
  429. if err := CommitRepoAction(CommitRepoActionOptions{
  430. PusherName: opts.PusherName,
  431. RepoOwnerID: repo.OwnerID,
  432. RepoName: repo.Name,
  433. RefFullName: opts.RefFullName,
  434. OldCommitID: opts.OldCommitID,
  435. NewCommitID: opts.NewCommitID,
  436. Commits: commits,
  437. }); err != nil {
  438. return fmt.Errorf("CommitRepoAction: %v", err)
  439. }
  440. pusher, err := models.GetUserByID(opts.PusherID)
  441. if err != nil {
  442. return err
  443. }
  444. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  445. go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  446. if opts.RefFullName == git.BranchPrefix+repo.DefaultBranch {
  447. models.UpdateRepoIndexer(repo)
  448. }
  449. return nil
  450. }