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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. "fmt"
  8. "path"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/charset"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/lfs"
  15. "code.gitea.io/gitea/modules/log"
  16. repo_module "code.gitea.io/gitea/modules/repository"
  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. // CommitDateOptions store dates for GIT_AUTHOR_DATE and GIT_COMMITTER_DATE
  28. type CommitDateOptions struct {
  29. Author time.Time
  30. Committer time.Time
  31. }
  32. // UpdateRepoFileOptions holds the repository file update options
  33. type UpdateRepoFileOptions struct {
  34. LastCommitID string
  35. OldBranch string
  36. NewBranch string
  37. TreePath string
  38. FromTreePath string
  39. Message string
  40. Content string
  41. SHA string
  42. IsNewFile bool
  43. Author *IdentityOptions
  44. Committer *IdentityOptions
  45. Dates *CommitDateOptions
  46. Signoff bool
  47. }
  48. func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string, bool) {
  49. reader, err := entry.Blob().DataAsync()
  50. if err != nil {
  51. // return default
  52. return "UTF-8", false
  53. }
  54. defer reader.Close()
  55. buf := make([]byte, 1024)
  56. n, err := reader.Read(buf)
  57. if err != nil {
  58. // return default
  59. return "UTF-8", false
  60. }
  61. buf = buf[:n]
  62. if setting.LFS.StartServer {
  63. pointer, _ := lfs.ReadPointerFromBuffer(buf)
  64. if pointer.IsValid() {
  65. meta, err := repo.GetLFSMetaObjectByOid(pointer.Oid)
  66. if err != nil && err != models.ErrLFSObjectNotExist {
  67. // return default
  68. return "UTF-8", false
  69. }
  70. if meta != nil {
  71. dataRc, err := lfs.ReadMetaObject(pointer)
  72. if err != nil {
  73. // return default
  74. return "UTF-8", false
  75. }
  76. defer dataRc.Close()
  77. buf = make([]byte, 1024)
  78. n, err = dataRc.Read(buf)
  79. if err != nil {
  80. // return default
  81. return "UTF-8", false
  82. }
  83. buf = buf[:n]
  84. }
  85. }
  86. }
  87. encoding, err := charset.DetectEncoding(buf)
  88. if err != nil {
  89. // just default to utf-8 and no bom
  90. return "UTF-8", false
  91. }
  92. if encoding == "UTF-8" {
  93. return encoding, bytes.Equal(buf[0:3], charset.UTF8BOM)
  94. }
  95. charsetEncoding, _ := stdcharset.Lookup(encoding)
  96. if charsetEncoding == nil {
  97. return "UTF-8", false
  98. }
  99. result, n, err := transform.String(charsetEncoding.NewDecoder(), string(buf))
  100. if err != nil {
  101. // return default
  102. return "UTF-8", false
  103. }
  104. if n > 2 {
  105. return encoding, bytes.Equal([]byte(result)[0:3], charset.UTF8BOM)
  106. }
  107. return encoding, false
  108. }
  109. // CreateOrUpdateRepoFile adds or updates a file in the given repository
  110. func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) {
  111. // If no branch name is set, assume default branch
  112. if opts.OldBranch == "" {
  113. opts.OldBranch = repo.DefaultBranch
  114. }
  115. if opts.NewBranch == "" {
  116. opts.NewBranch = opts.OldBranch
  117. }
  118. // oldBranch must exist for this operation
  119. if _, err := repo_module.GetBranch(repo, opts.OldBranch); err != nil {
  120. return nil, err
  121. }
  122. // A NewBranch can be specified for the file to be created/updated in a new branch.
  123. // Check to make sure the branch does not already exist, otherwise we can't proceed.
  124. // If we aren't branching to a new branch, make sure user can commit to the given branch
  125. if opts.NewBranch != opts.OldBranch {
  126. existingBranch, err := repo_module.GetBranch(repo, opts.NewBranch)
  127. if existingBranch != nil {
  128. return nil, models.ErrBranchAlreadyExists{
  129. BranchName: opts.NewBranch,
  130. }
  131. }
  132. if err != nil && !git.IsErrBranchNotExist(err) {
  133. return nil, err
  134. }
  135. } else if err := VerifyBranchProtection(repo, doer, opts.OldBranch, opts.TreePath); err != nil {
  136. return nil, err
  137. }
  138. // If FromTreePath is not set, set it to the opts.TreePath
  139. if opts.TreePath != "" && opts.FromTreePath == "" {
  140. opts.FromTreePath = opts.TreePath
  141. }
  142. // Check that the path given in opts.treePath is valid (not a git path)
  143. treePath := CleanUploadFileName(opts.TreePath)
  144. if treePath == "" {
  145. return nil, models.ErrFilenameInvalid{
  146. Path: opts.TreePath,
  147. }
  148. }
  149. // If there is a fromTreePath (we are copying it), also clean it up
  150. fromTreePath := CleanUploadFileName(opts.FromTreePath)
  151. if fromTreePath == "" && opts.FromTreePath != "" {
  152. return nil, models.ErrFilenameInvalid{
  153. Path: opts.FromTreePath,
  154. }
  155. }
  156. message := strings.TrimSpace(opts.Message)
  157. author, committer := GetAuthorAndCommitterUsers(opts.Author, opts.Committer, doer)
  158. t, err := NewTemporaryUploadRepository(repo)
  159. if err != nil {
  160. log.Error("%v", err)
  161. }
  162. defer t.Close()
  163. if err := t.Clone(opts.OldBranch); err != nil {
  164. return nil, err
  165. }
  166. if err := t.SetDefaultIndex(); err != nil {
  167. return nil, err
  168. }
  169. // Get the commit of the original branch
  170. commit, err := t.GetBranchCommit(opts.OldBranch)
  171. if err != nil {
  172. return nil, err // Couldn't get a commit for the branch
  173. }
  174. // Assigned LastCommitID in opts if it hasn't been set
  175. if opts.LastCommitID == "" {
  176. opts.LastCommitID = commit.ID.String()
  177. } else {
  178. lastCommitID, err := t.gitRepo.ConvertToSHA1(opts.LastCommitID)
  179. if err != nil {
  180. return nil, fmt.Errorf("DeleteRepoFile: Invalid last commit ID: %v", err)
  181. }
  182. opts.LastCommitID = lastCommitID.String()
  183. }
  184. encoding := "UTF-8"
  185. bom := false
  186. executable := 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. executable = fromEntry.IsExecutable()
  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.gitRepo.CheckAttribute(git.CheckAttributeOpts{
  318. Attributes: []string{"filter"},
  319. Filenames: []string{treePath},
  320. })
  321. if err != nil {
  322. return nil, err
  323. }
  324. if filename2attribute2info[treePath] != nil && filename2attribute2info[treePath]["filter"] == "lfs" {
  325. // OK so we are supposed to LFS this data!
  326. pointer, err := lfs.GeneratePointer(strings.NewReader(opts.Content))
  327. if err != nil {
  328. return nil, err
  329. }
  330. lfsMetaObject = &models.LFSMetaObject{Pointer: pointer, RepositoryID: repo.ID}
  331. content = pointer.StringContent()
  332. }
  333. }
  334. // Add the object to the database
  335. objectHash, err := t.HashObject(strings.NewReader(content))
  336. if err != nil {
  337. return nil, err
  338. }
  339. // Add the object to the index
  340. if executable {
  341. if err := t.AddObjectToIndex("100755", objectHash, treePath); err != nil {
  342. return nil, err
  343. }
  344. } else {
  345. if err := t.AddObjectToIndex("100644", objectHash, treePath); err != nil {
  346. return nil, err
  347. }
  348. }
  349. // Now write the tree
  350. treeHash, err := t.WriteTree()
  351. if err != nil {
  352. return nil, err
  353. }
  354. // Now commit the tree
  355. var commitHash string
  356. if opts.Dates != nil {
  357. commitHash, err = t.CommitTreeWithDate(author, committer, treeHash, message, opts.Signoff, opts.Dates.Author, opts.Dates.Committer)
  358. } else {
  359. commitHash, err = t.CommitTree(author, committer, treeHash, message, opts.Signoff)
  360. }
  361. if err != nil {
  362. return nil, err
  363. }
  364. if lfsMetaObject != nil {
  365. // We have an LFS object - create it
  366. lfsMetaObject, err = models.NewLFSMetaObject(lfsMetaObject)
  367. if err != nil {
  368. return nil, err
  369. }
  370. contentStore := lfs.NewContentStore()
  371. exist, err := contentStore.Exists(lfsMetaObject.Pointer)
  372. if err != nil {
  373. return nil, err
  374. }
  375. if !exist {
  376. if err := contentStore.Put(lfsMetaObject.Pointer, strings.NewReader(opts.Content)); err != nil {
  377. if _, err2 := repo.RemoveLFSMetaObjectByOid(lfsMetaObject.Oid); err2 != nil {
  378. return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %v)", lfsMetaObject.Oid, err2, err)
  379. }
  380. return nil, err
  381. }
  382. }
  383. }
  384. // Then push this tree to NewBranch
  385. if err := t.Push(doer, commitHash, opts.NewBranch); err != nil {
  386. log.Error("%T %v", err, err)
  387. return nil, err
  388. }
  389. commit, err = t.GetCommit(commitHash)
  390. if err != nil {
  391. return nil, err
  392. }
  393. file, err := GetFileResponseFromCommit(repo, commit, opts.NewBranch, treePath)
  394. if err != nil {
  395. return nil, err
  396. }
  397. return file, nil
  398. }
  399. // VerifyBranchProtection verify the branch protection for modifying the given treePath on the given branch
  400. func VerifyBranchProtection(repo *models.Repository, doer *models.User, branchName string, treePath string) error {
  401. protectedBranch, err := repo.GetBranchProtection(branchName)
  402. if err != nil {
  403. return err
  404. }
  405. if protectedBranch != nil {
  406. isUnprotectedFile := false
  407. glob := protectedBranch.GetUnprotectedFilePatterns()
  408. if len(glob) != 0 {
  409. isUnprotectedFile = protectedBranch.IsUnprotectedFile(glob, treePath)
  410. }
  411. if !protectedBranch.CanUserPush(doer.ID) && !isUnprotectedFile {
  412. return models.ErrUserCannotCommit{
  413. UserName: doer.LowerName,
  414. }
  415. }
  416. if protectedBranch.RequireSignedCommits {
  417. _, _, _, err := repo.SignCRUDAction(doer, repo.RepoPath(), branchName)
  418. if err != nil {
  419. if !models.IsErrWontSign(err) {
  420. return err
  421. }
  422. return models.ErrUserCannotCommit{
  423. UserName: doer.LowerName,
  424. }
  425. }
  426. }
  427. patterns := protectedBranch.GetProtectedFilePatterns()
  428. for _, pat := range patterns {
  429. if pat.Match(strings.ToLower(treePath)) {
  430. return models.ErrFilePathProtected{
  431. Path: treePath,
  432. }
  433. }
  434. }
  435. }
  436. return nil
  437. }