You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

update.go 13 kB

Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 n > 2 {
  92. return encoding, bytes.Equal([]byte(result)[0:3], base.UTF8BOM)
  93. }
  94. return encoding, false
  95. }
  96. // CreateOrUpdateRepoFile adds or updates a file in the given repository
  97. func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) {
  98. // If no branch name is set, assume master
  99. if opts.OldBranch == "" {
  100. opts.OldBranch = repo.DefaultBranch
  101. }
  102. if opts.NewBranch == "" {
  103. opts.NewBranch = opts.OldBranch
  104. }
  105. // oldBranch must exist for this operation
  106. if _, err := repo.GetBranch(opts.OldBranch); err != nil {
  107. return nil, err
  108. }
  109. // A NewBranch can be specified for the file to be created/updated in a new branch.
  110. // Check to make sure the branch does not already exist, otherwise we can't proceed.
  111. // If we aren't branching to a new branch, make sure user can commit to the given branch
  112. if opts.NewBranch != opts.OldBranch {
  113. existingBranch, err := repo.GetBranch(opts.NewBranch)
  114. if existingBranch != nil {
  115. return nil, models.ErrBranchAlreadyExists{
  116. BranchName: opts.NewBranch,
  117. }
  118. }
  119. if err != nil && !git.IsErrBranchNotExist(err) {
  120. return nil, err
  121. }
  122. } else {
  123. if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
  124. return nil, models.ErrUserCannotCommit{UserName: doer.LowerName}
  125. }
  126. }
  127. // If FromTreePath is not set, set it to the opts.TreePath
  128. if opts.TreePath != "" && opts.FromTreePath == "" {
  129. opts.FromTreePath = opts.TreePath
  130. }
  131. // Check that the path given in opts.treePath is valid (not a git path)
  132. treePath := CleanUploadFileName(opts.TreePath)
  133. if treePath == "" {
  134. return nil, models.ErrFilenameInvalid{
  135. Path: opts.TreePath,
  136. }
  137. }
  138. // If there is a fromTreePath (we are copying it), also clean it up
  139. fromTreePath := CleanUploadFileName(opts.FromTreePath)
  140. if fromTreePath == "" && opts.FromTreePath != "" {
  141. return nil, models.ErrFilenameInvalid{
  142. Path: opts.FromTreePath,
  143. }
  144. }
  145. message := strings.TrimSpace(opts.Message)
  146. author, committer := GetAuthorAndCommitterUsers(opts.Committer, opts.Author, doer)
  147. t, err := NewTemporaryUploadRepository(repo)
  148. defer t.Close()
  149. if err != nil {
  150. return nil, err
  151. }
  152. if err := t.Clone(opts.OldBranch); err != nil {
  153. return nil, err
  154. }
  155. if err := t.SetDefaultIndex(); err != nil {
  156. return nil, err
  157. }
  158. // Get the commit of the original branch
  159. commit, err := t.GetBranchCommit(opts.OldBranch)
  160. if err != nil {
  161. return nil, err // Couldn't get a commit for the branch
  162. }
  163. // Assigned LastCommitID in opts if it hasn't been set
  164. if opts.LastCommitID == "" {
  165. opts.LastCommitID = commit.ID.String()
  166. }
  167. encoding := "UTF-8"
  168. bom := false
  169. if !opts.IsNewFile {
  170. fromEntry, err := commit.GetTreeEntryByPath(fromTreePath)
  171. if err != nil {
  172. return nil, err
  173. }
  174. if opts.SHA != "" {
  175. // If a SHA was given and the SHA given doesn't match the SHA of the fromTreePath, throw error
  176. if opts.SHA != fromEntry.ID.String() {
  177. return nil, models.ErrSHADoesNotMatch{
  178. Path: treePath,
  179. GivenSHA: opts.SHA,
  180. CurrentSHA: fromEntry.ID.String(),
  181. }
  182. }
  183. } else if opts.LastCommitID != "" {
  184. // If a lastCommitID was given and it doesn't match the commitID of the head of the branch throw
  185. // an error, but only if we aren't creating a new branch.
  186. if commit.ID.String() != opts.LastCommitID && opts.OldBranch == opts.NewBranch {
  187. if changed, err := commit.FileChangedSinceCommit(treePath, opts.LastCommitID); err != nil {
  188. return nil, err
  189. } else if changed {
  190. return nil, models.ErrCommitIDDoesNotMatch{
  191. GivenCommitID: opts.LastCommitID,
  192. CurrentCommitID: opts.LastCommitID,
  193. }
  194. }
  195. // The file wasn't modified, so we are good to delete it
  196. }
  197. } else {
  198. // When updating a file, a lastCommitID or SHA needs to be given to make sure other commits
  199. // haven't been made. We throw an error if one wasn't provided.
  200. return nil, models.ErrSHAOrCommitIDNotProvided{}
  201. }
  202. encoding, bom = detectEncodingAndBOM(fromEntry, repo)
  203. }
  204. // For the path where this file will be created/updated, we need to make
  205. // sure no parts of the path are existing files or links except for the last
  206. // item in the path which is the file name, and that shouldn't exist IF it is
  207. // a new file OR is being moved to a new path.
  208. treePathParts := strings.Split(treePath, "/")
  209. subTreePath := ""
  210. for index, part := range treePathParts {
  211. subTreePath = path.Join(subTreePath, part)
  212. entry, err := commit.GetTreeEntryByPath(subTreePath)
  213. if err != nil {
  214. if git.IsErrNotExist(err) {
  215. // Means there is no item with that name, so we're good
  216. break
  217. }
  218. return nil, err
  219. }
  220. if index < len(treePathParts)-1 {
  221. if !entry.IsDir() {
  222. return nil, models.ErrFilePathInvalid{
  223. Message: fmt.Sprintf("a file exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  224. Path: subTreePath,
  225. Name: part,
  226. Type: git.EntryModeBlob,
  227. }
  228. }
  229. } else if entry.IsLink() {
  230. return nil, models.ErrFilePathInvalid{
  231. Message: fmt.Sprintf("a symbolic link exists where you’re trying to create a subdirectory [path: %s]", subTreePath),
  232. Path: subTreePath,
  233. Name: part,
  234. Type: git.EntryModeSymlink,
  235. }
  236. } else if entry.IsDir() {
  237. return nil, models.ErrFilePathInvalid{
  238. Message: fmt.Sprintf("a directory exists where you’re trying to create a file [path: %s]", subTreePath),
  239. Path: subTreePath,
  240. Name: part,
  241. Type: git.EntryModeTree,
  242. }
  243. } else if fromTreePath != treePath || opts.IsNewFile {
  244. // The entry shouldn't exist if we are creating new file or moving to a new path
  245. return nil, models.ErrRepoFileAlreadyExists{
  246. Path: treePath,
  247. }
  248. }
  249. }
  250. // Get the two paths (might be the same if not moving) from the index if they exist
  251. filesInIndex, err := t.LsFiles(opts.TreePath, opts.FromTreePath)
  252. if err != nil {
  253. return nil, fmt.Errorf("UpdateRepoFile: %v", err)
  254. }
  255. // If is a new file (not updating) then the given path shouldn't exist
  256. if opts.IsNewFile {
  257. for _, file := range filesInIndex {
  258. if file == opts.TreePath {
  259. return nil, models.ErrRepoFileAlreadyExists{
  260. Path: opts.TreePath,
  261. }
  262. }
  263. }
  264. }
  265. // Remove the old path from the tree
  266. if fromTreePath != treePath && len(filesInIndex) > 0 {
  267. for _, file := range filesInIndex {
  268. if file == fromTreePath {
  269. if err := t.RemoveFilesFromIndex(opts.FromTreePath); err != nil {
  270. return nil, err
  271. }
  272. }
  273. }
  274. }
  275. // Check there is no way this can return multiple infos
  276. filename2attribute2info, err := t.CheckAttribute("filter", treePath)
  277. if err != nil {
  278. return nil, err
  279. }
  280. content := opts.Content
  281. if bom {
  282. content = string(base.UTF8BOM) + content
  283. }
  284. if encoding != "UTF-8" {
  285. charsetEncoding, _ := charset.Lookup(encoding)
  286. if charsetEncoding != nil {
  287. result, _, err := transform.String(charsetEncoding.NewEncoder(), string(content))
  288. if err != nil {
  289. // Look if we can't encode back in to the original we should just stick with utf-8
  290. log.Error("Error re-encoding %s (%s) as %s - will stay as UTF-8: %v", opts.TreePath, opts.FromTreePath, encoding, err)
  291. result = content
  292. }
  293. content = result
  294. } else {
  295. log.Error("Unknown encoding: %s", encoding)
  296. }
  297. }
  298. // Reset the opts.Content to our adjusted content to ensure that LFS gets the correct content
  299. opts.Content = content
  300. var lfsMetaObject *models.LFSMetaObject
  301. if setting.LFS.StartServer && filename2attribute2info[treePath] != nil && filename2attribute2info[treePath]["filter"] == "lfs" {
  302. // OK so we are supposed to LFS this data!
  303. oid, err := models.GenerateLFSOid(strings.NewReader(opts.Content))
  304. if err != nil {
  305. return nil, err
  306. }
  307. lfsMetaObject = &models.LFSMetaObject{Oid: oid, Size: int64(len(opts.Content)), RepositoryID: repo.ID}
  308. content = lfsMetaObject.Pointer()
  309. }
  310. // Add the object to the database
  311. objectHash, err := t.HashObject(strings.NewReader(content))
  312. if err != nil {
  313. return nil, err
  314. }
  315. // Add the object to the index
  316. if err := t.AddObjectToIndex("100644", objectHash, treePath); err != nil {
  317. return nil, err
  318. }
  319. // Now write the tree
  320. treeHash, err := t.WriteTree()
  321. if err != nil {
  322. return nil, err
  323. }
  324. // Now commit the tree
  325. commitHash, err := t.CommitTree(author, committer, treeHash, message)
  326. if err != nil {
  327. return nil, err
  328. }
  329. if lfsMetaObject != nil {
  330. // We have an LFS object - create it
  331. lfsMetaObject, err = models.NewLFSMetaObject(lfsMetaObject)
  332. if err != nil {
  333. return nil, err
  334. }
  335. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  336. if !contentStore.Exists(lfsMetaObject) {
  337. if err := contentStore.Put(lfsMetaObject, strings.NewReader(opts.Content)); err != nil {
  338. if err2 := repo.RemoveLFSMetaObjectByOid(lfsMetaObject.Oid); err2 != nil {
  339. return nil, fmt.Errorf("Error whilst removing failed inserted LFS object %s: %v (Prev Error: %v)", lfsMetaObject.Oid, err2, err)
  340. }
  341. return nil, err
  342. }
  343. }
  344. }
  345. // Then push this tree to NewBranch
  346. if err := t.Push(doer, commitHash, opts.NewBranch); err != nil {
  347. return nil, err
  348. }
  349. // Simulate push event.
  350. oldCommitID := opts.LastCommitID
  351. if opts.NewBranch != opts.OldBranch || oldCommitID == "" {
  352. oldCommitID = git.EmptySHA
  353. }
  354. if err = repo.GetOwner(); err != nil {
  355. return nil, fmt.Errorf("GetOwner: %v", err)
  356. }
  357. err = PushUpdate(
  358. repo,
  359. opts.NewBranch,
  360. models.PushUpdateOptions{
  361. PusherID: doer.ID,
  362. PusherName: doer.Name,
  363. RepoUserName: repo.Owner.Name,
  364. RepoName: repo.Name,
  365. RefFullName: git.BranchPrefix + opts.NewBranch,
  366. OldCommitID: oldCommitID,
  367. NewCommitID: commitHash,
  368. },
  369. )
  370. if err != nil {
  371. return nil, fmt.Errorf("PushUpdate: %v", err)
  372. }
  373. commit, err = t.GetCommit(commitHash)
  374. if err != nil {
  375. return nil, err
  376. }
  377. file, err := GetFileResponseFromCommit(repo, commit, opts.NewBranch, treePath)
  378. if err != nil {
  379. return nil, err
  380. }
  381. return file, nil
  382. }
  383. // PushUpdate must be called for any push actions in order to
  384. // generates necessary push action history feeds and other operations
  385. func PushUpdate(repo *models.Repository, branch string, opts models.PushUpdateOptions) error {
  386. err := models.PushUpdate(branch, opts)
  387. if err != nil {
  388. return fmt.Errorf("PushUpdate: %v", err)
  389. }
  390. if opts.RefFullName == git.BranchPrefix+repo.DefaultBranch {
  391. models.UpdateRepoIndexer(repo)
  392. }
  393. return nil
  394. }