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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. "golang.org/x/net/html/charset"
  11. "golang.org/x/text/transform"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/base"
  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. )
  20. // IdentityOptions for a person's identity like an author or committer
  21. type IdentityOptions struct {
  22. Name string
  23. Email string
  24. }
  25. // UpdateRepoFileOptions holds the repository file update options
  26. type UpdateRepoFileOptions struct {
  27. LastCommitID string
  28. OldBranch string
  29. NewBranch string
  30. TreePath string
  31. FromTreePath string
  32. Message string
  33. Content string
  34. SHA string
  35. IsNewFile bool
  36. Author *IdentityOptions
  37. Committer *IdentityOptions
  38. }
  39. func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string, bool) {
  40. reader, err := entry.Blob().DataAsync()
  41. if err != nil {
  42. // return default
  43. return "UTF-8", false
  44. }
  45. defer reader.Close()
  46. buf := make([]byte, 1024)
  47. n, err := reader.Read(buf)
  48. if err != nil {
  49. // return default
  50. return "UTF-8", false
  51. }
  52. buf = buf[:n]
  53. if setting.LFS.StartServer {
  54. meta := lfs.IsPointerFile(&buf)
  55. if meta != nil {
  56. meta, err = repo.GetLFSMetaObjectByOid(meta.Oid)
  57. if err != nil && err != models.ErrLFSObjectNotExist {
  58. // return default
  59. return "UTF-8", false
  60. }
  61. }
  62. if meta != nil {
  63. dataRc, err := lfs.ReadMetaObject(meta)
  64. if err != nil {
  65. // return default
  66. return "UTF-8", false
  67. }
  68. defer dataRc.Close()
  69. buf = make([]byte, 1024)
  70. n, err = dataRc.Read(buf)
  71. if err != nil {
  72. // return default
  73. return "UTF-8", false
  74. }
  75. buf = buf[:n]
  76. }
  77. }
  78. encoding, err := base.DetectEncoding(buf)
  79. if err != nil {
  80. // just default to utf-8 and no bom
  81. return "UTF-8", false
  82. }
  83. if encoding == "UTF-8" {
  84. return encoding, bytes.Equal(buf[0:3], base.UTF8BOM)
  85. }
  86. charsetEncoding, _ := charset.Lookup(encoding)
  87. if charsetEncoding == nil {
  88. return "UTF-8", false
  89. }
  90. result, n, err := transform.String(charsetEncoding.NewDecoder(), string(buf))
  91. if err != nil {
  92. // return default
  93. return "UTF-8", false
  94. }
  95. if n > 2 {
  96. return encoding, bytes.Equal([]byte(result)[0:3], base.UTF8BOM)
  97. }
  98. return encoding, false
  99. }
  100. // CreateOrUpdateRepoFile adds or updates a file in the given repository
  101. func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) {
  102. // If no branch name is set, assume master
  103. if opts.OldBranch == "" {
  104. opts.OldBranch = repo.DefaultBranch
  105. }
  106. if opts.NewBranch == "" {
  107. opts.NewBranch = opts.OldBranch
  108. }
  109. // oldBranch must exist for this operation
  110. if _, err := repo.GetBranch(opts.OldBranch); err != nil {
  111. return nil, err
  112. }
  113. // A NewBranch can be specified for the file to be created/updated in a new branch.
  114. // Check to make sure the branch does not already exist, otherwise we can't proceed.
  115. // If we aren't branching to a new branch, make sure user can commit to the given branch
  116. if opts.NewBranch != opts.OldBranch {
  117. existingBranch, err := repo.GetBranch(opts.NewBranch)
  118. if existingBranch != nil {
  119. return nil, models.ErrBranchAlreadyExists{
  120. BranchName: opts.NewBranch,
  121. }
  122. }
  123. if err != nil && !git.IsErrBranchNotExist(err) {
  124. return nil, err
  125. }
  126. } else if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
  127. return nil, models.ErrUserCannotCommit{UserName: doer.LowerName}
  128. }
  129. // If FromTreePath is not set, set it to the opts.TreePath
  130. if opts.TreePath != "" && opts.FromTreePath == "" {
  131. opts.FromTreePath = opts.TreePath
  132. }
  133. // Check that the path given in opts.treePath is valid (not a git path)
  134. treePath := CleanUploadFileName(opts.TreePath)
  135. if treePath == "" {
  136. return nil, models.ErrFilenameInvalid{
  137. Path: opts.TreePath,
  138. }
  139. }
  140. // If there is a fromTreePath (we are copying it), also clean it up
  141. fromTreePath := CleanUploadFileName(opts.FromTreePath)
  142. if fromTreePath == "" && opts.FromTreePath != "" {
  143. return nil, models.ErrFilenameInvalid{
  144. Path: opts.FromTreePath,
  145. }
  146. }
  147. message := strings.TrimSpace(opts.Message)
  148. author, committer := GetAuthorAndCommitterUsers(opts.Committer, opts.Author, doer)
  149. t, err := NewTemporaryUploadRepository(repo)
  150. if err != nil {
  151. log.Error("%v", err)
  152. }
  153. defer t.Close()
  154. if err := t.Clone(opts.OldBranch); err != nil {
  155. return nil, err
  156. }
  157. if err := t.SetDefaultIndex(); err != nil {
  158. return nil, err
  159. }
  160. // Get the commit of the original branch
  161. commit, err := t.GetBranchCommit(opts.OldBranch)
  162. if err != nil {
  163. return nil, err // Couldn't get a commit for the branch
  164. }
  165. // Assigned LastCommitID in opts if it hasn't been set
  166. if opts.LastCommitID == "" {
  167. opts.LastCommitID = commit.ID.String()
  168. } else {
  169. lastCommitID, err := t.gitRepo.ConvertToSHA1(opts.LastCommitID)
  170. if err != nil {
  171. return nil, fmt.Errorf("DeleteRepoFile: Invalid last commit ID: %v", err)
  172. }
  173. opts.LastCommitID = lastCommitID.String()
  174. }
  175. encoding := "UTF-8"
  176. bom := false
  177. if !opts.IsNewFile {
  178. fromEntry, err := commit.GetTreeEntryByPath(fromTreePath)
  179. if err != nil {
  180. return nil, err
  181. }
  182. if opts.SHA != "" {
  183. // If a SHA was given and the SHA given doesn't match the SHA of the fromTreePath, throw error
  184. if opts.SHA != fromEntry.ID.String() {
  185. return nil, models.ErrSHADoesNotMatch{
  186. Path: treePath,
  187. GivenSHA: opts.SHA,
  188. CurrentSHA: fromEntry.ID.String(),
  189. }
  190. }
  191. } else if opts.LastCommitID != "" {
  192. // If a lastCommitID was given and it doesn't match the commitID of the head of the branch throw
  193. // an error, but only if we aren't creating a new branch.
  194. if commit.ID.String() != opts.LastCommitID && opts.OldBranch == opts.NewBranch {
  195. if changed, err := commit.FileChangedSinceCommit(treePath, opts.LastCommitID); err != nil {
  196. return nil, err
  197. } else if changed {
  198. return nil, models.ErrCommitIDDoesNotMatch{
  199. GivenCommitID: opts.LastCommitID,
  200. CurrentCommitID: opts.LastCommitID,
  201. }
  202. }
  203. // The file wasn't modified, so we are good to delete it
  204. }
  205. } else {
  206. // When updating a file, a lastCommitID or SHA needs to be given to make sure other commits
  207. // haven't been made. We throw an error if one wasn't provided.
  208. return nil, models.ErrSHAOrCommitIDNotProvided{}
  209. }
  210. encoding, bom = detectEncodingAndBOM(fromEntry, repo)
  211. }
  212. // For the path where this file will be created/updated, we need to make
  213. // sure no parts of the path are existing files or links except for the last
  214. // item in the path which is the file name, and that shouldn't exist IF it is
  215. // a new file OR is being moved to a new path.
  216. treePathParts := strings.Split(treePath, "/")
  217. subTreePath := ""
  218. for index, part := range treePathParts {
  219. subTreePath = path.Join(subTreePath, part)
  220. entry, err := commit.GetTreeEntryByPath(subTreePath)
  221. if err != nil {
  222. if git.IsErrNotExist(err) {
  223. // Means there is no item with that name, so we're good
  224. break
  225. }
  226. return nil, err
  227. }
  228. if index < len(treePathParts)-1 {
  229. if !entry.IsDir() {
  230. return nil, models.ErrFilePathInvalid{
  231. Message: fmt.Sprintf("a file exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  232. Path: subTreePath,
  233. Name: part,
  234. Type: git.EntryModeBlob,
  235. }
  236. }
  237. } else if entry.IsLink() {
  238. return nil, models.ErrFilePathInvalid{
  239. Message: fmt.Sprintf("a symbolic link exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  240. Path: subTreePath,
  241. Name: part,
  242. Type: git.EntryModeSymlink,
  243. }
  244. } else if entry.IsDir() {
  245. return nil, models.ErrFilePathInvalid{
  246. Message: fmt.Sprintf("a directory exists where you’re trying to create a file [path: %s]", subTreePath),
  247. Path: subTreePath,
  248. Name: part,
  249. Type: git.EntryModeTree,
  250. }
  251. } else if fromTreePath != treePath || opts.IsNewFile {
  252. // The entry shouldn't exist if we are creating new file or moving to a new path
  253. return nil, models.ErrRepoFileAlreadyExists{
  254. Path: treePath,
  255. }
  256. }
  257. }
  258. // Get the two paths (might be the same if not moving) from the index if they exist
  259. filesInIndex, err := t.LsFiles(opts.TreePath, opts.FromTreePath)
  260. if err != nil {
  261. return nil, fmt.Errorf("UpdateRepoFile: %v", err)
  262. }
  263. // If is a new file (not updating) then the given path shouldn't exist
  264. if opts.IsNewFile {
  265. for _, file := range filesInIndex {
  266. if file == opts.TreePath {
  267. return nil, models.ErrRepoFileAlreadyExists{
  268. Path: opts.TreePath,
  269. }
  270. }
  271. }
  272. }
  273. // Remove the old path from the tree
  274. if fromTreePath != treePath && len(filesInIndex) > 0 {
  275. for _, file := range filesInIndex {
  276. if file == fromTreePath {
  277. if err := t.RemoveFilesFromIndex(opts.FromTreePath); err != nil {
  278. return nil, err
  279. }
  280. }
  281. }
  282. }
  283. content := opts.Content
  284. if bom {
  285. content = string(base.UTF8BOM) + content
  286. }
  287. if encoding != "UTF-8" {
  288. charsetEncoding, _ := charset.Lookup(encoding)
  289. if charsetEncoding != nil {
  290. result, _, err := transform.String(charsetEncoding.NewEncoder(), string(content))
  291. if err != nil {
  292. // Look if we can't encode back in to the original we should just stick with utf-8
  293. log.Error("Error re-encoding %s (%s) as %s - will stay as UTF-8: %v", opts.TreePath, opts.FromTreePath, encoding, err)
  294. result = content
  295. }
  296. content = result
  297. } else {
  298. log.Error("Unknown encoding: %s", encoding)
  299. }
  300. }
  301. // Reset the opts.Content to our adjusted content to ensure that LFS gets the correct content
  302. opts.Content = content
  303. var lfsMetaObject *models.LFSMetaObject
  304. if setting.LFS.StartServer {
  305. // Check there is no way this can return multiple infos
  306. filename2attribute2info, err := t.CheckAttribute("filter", treePath)
  307. if err != nil {
  308. return nil, err
  309. }
  310. if filename2attribute2info[treePath] != nil && filename2attribute2info[treePath]["filter"] == "lfs" {
  311. // OK so we are supposed to LFS this data!
  312. oid, err := models.GenerateLFSOid(strings.NewReader(opts.Content))
  313. if err != nil {
  314. return nil, err
  315. }
  316. lfsMetaObject = &models.LFSMetaObject{Oid: oid, Size: int64(len(opts.Content)), RepositoryID: repo.ID}
  317. content = lfsMetaObject.Pointer()
  318. }
  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. err := models.PushUpdate(branch, opts)
  373. if err != nil {
  374. return fmt.Errorf("PushUpdate: %v", err)
  375. }
  376. if opts.RefFullName == git.BranchPrefix+repo.DefaultBranch {
  377. models.UpdateRepoIndexer(repo)
  378. }
  379. return nil
  380. }