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.

repo_editor.go 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. // Copyright 2016 The Gogs 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 models
  5. import (
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "mime/multipart"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "time"
  15. "github.com/Unknwon/com"
  16. gouuid "github.com/satori/go.uuid"
  17. "code.gitea.io/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/process"
  20. "code.gitea.io/gitea/modules/setting"
  21. )
  22. // ___________ .___.__ __ ___________.__.__
  23. // \_ _____/ __| _/|__|/ |_ \_ _____/|__| | ____
  24. // | __)_ / __ | | \ __\ | __) | | | _/ __ \
  25. // | \/ /_/ | | || | | \ | | |_\ ___/
  26. // /_______ /\____ | |__||__| \___ / |__|____/\___ >
  27. // \/ \/ \/ \/
  28. // discardLocalRepoBranchChanges discards local commits/changes of
  29. // given branch to make sure it is even to remote branch.
  30. func discardLocalRepoBranchChanges(localPath, branch string) error {
  31. if !com.IsExist(localPath) {
  32. return nil
  33. }
  34. // No need to check if nothing in the repository.
  35. if !git.IsBranchExist(localPath, branch) {
  36. return nil
  37. }
  38. refName := "origin/" + branch
  39. if err := git.ResetHEAD(localPath, true, refName); err != nil {
  40. return fmt.Errorf("git reset --hard %s: %v", refName, err)
  41. }
  42. return nil
  43. }
  44. // DiscardLocalRepoBranchChanges discards the local repository branch changes
  45. func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  46. return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
  47. }
  48. // checkoutNewBranch checks out to a new branch from the a branch name.
  49. func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error {
  50. if err := git.Checkout(localPath, git.CheckoutOptions{
  51. Timeout: time.Duration(setting.Git.Timeout.Pull) * time.Second,
  52. Branch: newBranch,
  53. OldBranch: oldBranch,
  54. }); err != nil {
  55. return fmt.Errorf("git checkout -b %s %s: %v", newBranch, oldBranch, err)
  56. }
  57. return nil
  58. }
  59. // CheckoutNewBranch checks out a new branch
  60. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  61. return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
  62. }
  63. // UpdateRepoFileOptions holds the repository file update options
  64. type UpdateRepoFileOptions struct {
  65. LastCommitID string
  66. OldBranch string
  67. NewBranch string
  68. OldTreeName string
  69. NewTreeName string
  70. Message string
  71. Content string
  72. IsNewFile bool
  73. }
  74. // UpdateRepoFile adds or updates a file in repository.
  75. func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
  76. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  77. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  78. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  79. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  80. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  81. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  82. }
  83. if opts.OldBranch != opts.NewBranch {
  84. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  85. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  86. }
  87. }
  88. localPath := repo.LocalCopyPath()
  89. oldFilePath := path.Join(localPath, opts.OldTreeName)
  90. filePath := path.Join(localPath, opts.NewTreeName)
  91. os.MkdirAll(path.Dir(filePath), os.ModePerm)
  92. // If it's meant to be a new file, make sure it doesn't exist.
  93. if opts.IsNewFile {
  94. if com.IsExist(filePath) {
  95. return ErrRepoFileAlreadyExist{filePath}
  96. }
  97. }
  98. // Ignore move step if it's a new file under a directory.
  99. // Otherwise, move the file when name changed.
  100. if com.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
  101. if err = git.MoveFile(localPath, opts.OldTreeName, opts.NewTreeName); err != nil {
  102. return fmt.Errorf("git mv %s %s: %v", opts.OldTreeName, opts.NewTreeName, err)
  103. }
  104. }
  105. if err = ioutil.WriteFile(filePath, []byte(opts.Content), 0666); err != nil {
  106. return fmt.Errorf("WriteFile: %v", err)
  107. }
  108. if err = git.AddChanges(localPath, true); err != nil {
  109. return fmt.Errorf("git add --all: %v", err)
  110. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  111. Committer: doer.NewGitSig(),
  112. Message: opts.Message,
  113. }); err != nil {
  114. return fmt.Errorf("CommitChanges: %v", err)
  115. } else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil {
  116. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  117. }
  118. gitRepo, err := git.OpenRepository(repo.RepoPath())
  119. if err != nil {
  120. log.Error(4, "OpenRepository: %v", err)
  121. return nil
  122. }
  123. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  124. if err != nil {
  125. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  126. return nil
  127. }
  128. // Simulate push event.
  129. pushCommits := &PushCommits{
  130. Len: 1,
  131. Commits: []*PushCommit{CommitToPushCommit(commit)},
  132. }
  133. oldCommitID := opts.LastCommitID
  134. if opts.NewBranch != opts.OldBranch {
  135. oldCommitID = git.EMPTY_SHA
  136. }
  137. if err := CommitRepoAction(CommitRepoActionOptions{
  138. PusherName: doer.Name,
  139. RepoOwnerID: repo.MustOwner().ID,
  140. RepoName: repo.Name,
  141. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  142. OldCommitID: oldCommitID,
  143. NewCommitID: commit.ID.String(),
  144. Commits: pushCommits,
  145. }); err != nil {
  146. log.Error(4, "CommitRepoAction: %v", err)
  147. return nil
  148. }
  149. return nil
  150. }
  151. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  152. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *Diff, err error) {
  153. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  154. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  155. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  156. return nil, fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", branch, err)
  157. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  158. return nil, fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", branch, err)
  159. }
  160. localPath := repo.LocalCopyPath()
  161. filePath := path.Join(localPath, treePath)
  162. os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
  163. if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
  164. return nil, fmt.Errorf("WriteFile: %v", err)
  165. }
  166. cmd := exec.Command("git", "diff", treePath)
  167. cmd.Dir = localPath
  168. cmd.Stderr = os.Stderr
  169. stdout, err := cmd.StdoutPipe()
  170. if err != nil {
  171. return nil, fmt.Errorf("StdoutPipe: %v", err)
  172. }
  173. if err = cmd.Start(); err != nil {
  174. return nil, fmt.Errorf("Start: %v", err)
  175. }
  176. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  177. defer process.Remove(pid)
  178. diff, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdout)
  179. if err != nil {
  180. return nil, fmt.Errorf("ParsePatch: %v", err)
  181. }
  182. if err = cmd.Wait(); err != nil {
  183. return nil, fmt.Errorf("Wait: %v", err)
  184. }
  185. return diff, nil
  186. }
  187. // ________ .__ __ ___________.__.__
  188. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  189. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  190. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  191. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  192. // \/ \/ \/ \/ \/ \/
  193. //
  194. // DeleteRepoFileOptions holds the repository delete file options
  195. type DeleteRepoFileOptions struct {
  196. LastCommitID string
  197. OldBranch string
  198. NewBranch string
  199. TreePath string
  200. Message string
  201. }
  202. // DeleteRepoFile deletes a repository file
  203. func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  204. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  205. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  206. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  207. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  208. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  209. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  210. }
  211. if opts.OldBranch != opts.NewBranch {
  212. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  213. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  214. }
  215. }
  216. localPath := repo.LocalCopyPath()
  217. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  218. return fmt.Errorf("Remove: %v", err)
  219. }
  220. if err = git.AddChanges(localPath, true); err != nil {
  221. return fmt.Errorf("git add --all: %v", err)
  222. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  223. Committer: doer.NewGitSig(),
  224. Message: opts.Message,
  225. }); err != nil {
  226. return fmt.Errorf("CommitChanges: %v", err)
  227. } else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil {
  228. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  229. }
  230. gitRepo, err := git.OpenRepository(repo.RepoPath())
  231. if err != nil {
  232. log.Error(4, "OpenRepository: %v", err)
  233. return nil
  234. }
  235. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  236. if err != nil {
  237. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  238. return nil
  239. }
  240. // Simulate push event.
  241. pushCommits := &PushCommits{
  242. Len: 1,
  243. Commits: []*PushCommit{CommitToPushCommit(commit)},
  244. }
  245. if err := CommitRepoAction(CommitRepoActionOptions{
  246. PusherName: doer.Name,
  247. RepoOwnerID: repo.MustOwner().ID,
  248. RepoName: repo.Name,
  249. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  250. OldCommitID: opts.LastCommitID,
  251. NewCommitID: commit.ID.String(),
  252. Commits: pushCommits,
  253. }); err != nil {
  254. log.Error(4, "CommitRepoAction: %v", err)
  255. return nil
  256. }
  257. return nil
  258. }
  259. // ____ ___ .__ .___ ___________.___.__
  260. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  261. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  262. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  263. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  264. // |__| \/ \/ \/ \/ \/
  265. //
  266. // Upload represent a uploaded file to a repo to be deleted when moved
  267. type Upload struct {
  268. ID int64 `xorm:"pk autoincr"`
  269. UUID string `xorm:"uuid UNIQUE"`
  270. Name string
  271. }
  272. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  273. func UploadLocalPath(uuid string) string {
  274. return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  275. }
  276. // LocalPath returns where uploads are temporarily stored in local file system.
  277. func (upload *Upload) LocalPath() string {
  278. return UploadLocalPath(upload.UUID)
  279. }
  280. // NewUpload creates a new upload object.
  281. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  282. upload := &Upload{
  283. UUID: gouuid.NewV4().String(),
  284. Name: name,
  285. }
  286. localPath := upload.LocalPath()
  287. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  288. return nil, fmt.Errorf("MkdirAll: %v", err)
  289. }
  290. fw, err := os.Create(localPath)
  291. if err != nil {
  292. return nil, fmt.Errorf("Create: %v", err)
  293. }
  294. defer fw.Close()
  295. if _, err = fw.Write(buf); err != nil {
  296. return nil, fmt.Errorf("Write: %v", err)
  297. } else if _, err = io.Copy(fw, file); err != nil {
  298. return nil, fmt.Errorf("Copy: %v", err)
  299. }
  300. if _, err := x.Insert(upload); err != nil {
  301. return nil, err
  302. }
  303. return upload, nil
  304. }
  305. // GetUploadByUUID returns the Upload by UUID
  306. func GetUploadByUUID(uuid string) (*Upload, error) {
  307. upload := &Upload{UUID: uuid}
  308. has, err := x.Get(upload)
  309. if err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, ErrUploadNotExist{0, uuid}
  313. }
  314. return upload, nil
  315. }
  316. // GetUploadsByUUIDs returns multiple uploads by UUIDS
  317. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  318. if len(uuids) == 0 {
  319. return []*Upload{}, nil
  320. }
  321. // Silently drop invalid uuids.
  322. uploads := make([]*Upload, 0, len(uuids))
  323. return uploads, x.In("uuid", uuids).Find(&uploads)
  324. }
  325. // DeleteUploads deletes multiple uploads
  326. func DeleteUploads(uploads ...*Upload) (err error) {
  327. if len(uploads) == 0 {
  328. return nil
  329. }
  330. sess := x.NewSession()
  331. defer sessionRelease(sess)
  332. if err = sess.Begin(); err != nil {
  333. return err
  334. }
  335. ids := make([]int64, len(uploads))
  336. for i := 0; i < len(uploads); i++ {
  337. ids[i] = uploads[i].ID
  338. }
  339. if _, err = sess.
  340. In("id", ids).
  341. Delete(new(Upload)); err != nil {
  342. return fmt.Errorf("delete uploads: %v", err)
  343. }
  344. for _, upload := range uploads {
  345. localPath := upload.LocalPath()
  346. if !com.IsFile(localPath) {
  347. continue
  348. }
  349. if err := os.Remove(localPath); err != nil {
  350. return fmt.Errorf("remove upload: %v", err)
  351. }
  352. }
  353. return sess.Commit()
  354. }
  355. // DeleteUpload delete a upload
  356. func DeleteUpload(u *Upload) error {
  357. return DeleteUploads(u)
  358. }
  359. // DeleteUploadByUUID deletes a upload by UUID
  360. func DeleteUploadByUUID(uuid string) error {
  361. upload, err := GetUploadByUUID(uuid)
  362. if err != nil {
  363. if IsErrUploadNotExist(err) {
  364. return nil
  365. }
  366. return fmt.Errorf("GetUploadByUUID: %v", err)
  367. }
  368. if err := DeleteUpload(upload); err != nil {
  369. return fmt.Errorf("DeleteUpload: %v", err)
  370. }
  371. return nil
  372. }
  373. // UploadRepoFileOptions contains the uploaded repository file options
  374. type UploadRepoFileOptions struct {
  375. LastCommitID string
  376. OldBranch string
  377. NewBranch string
  378. TreePath string
  379. Message string
  380. Files []string // In UUID format.
  381. }
  382. // UploadRepoFiles uploads files to a repository
  383. func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
  384. if len(opts.Files) == 0 {
  385. return nil
  386. }
  387. uploads, err := GetUploadsByUUIDs(opts.Files)
  388. if err != nil {
  389. return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %v", opts.Files, err)
  390. }
  391. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  392. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  393. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  394. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  395. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  396. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  397. }
  398. if opts.OldBranch != opts.NewBranch {
  399. if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  400. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  401. }
  402. }
  403. localPath := repo.LocalCopyPath()
  404. dirPath := path.Join(localPath, opts.TreePath)
  405. os.MkdirAll(dirPath, os.ModePerm)
  406. // Copy uploaded files into repository.
  407. for _, upload := range uploads {
  408. tmpPath := upload.LocalPath()
  409. targetPath := path.Join(dirPath, upload.Name)
  410. if !com.IsFile(tmpPath) {
  411. continue
  412. }
  413. if err = com.Copy(tmpPath, targetPath); err != nil {
  414. return fmt.Errorf("Copy: %v", err)
  415. }
  416. }
  417. if err = git.AddChanges(localPath, true); err != nil {
  418. return fmt.Errorf("git add --all: %v", err)
  419. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  420. Committer: doer.NewGitSig(),
  421. Message: opts.Message,
  422. }); err != nil {
  423. return fmt.Errorf("CommitChanges: %v", err)
  424. } else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil {
  425. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  426. }
  427. gitRepo, err := git.OpenRepository(repo.RepoPath())
  428. if err != nil {
  429. log.Error(4, "OpenRepository: %v", err)
  430. return nil
  431. }
  432. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  433. if err != nil {
  434. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  435. return nil
  436. }
  437. // Simulate push event.
  438. pushCommits := &PushCommits{
  439. Len: 1,
  440. Commits: []*PushCommit{CommitToPushCommit(commit)},
  441. }
  442. if err := CommitRepoAction(CommitRepoActionOptions{
  443. PusherName: doer.Name,
  444. RepoOwnerID: repo.MustOwner().ID,
  445. RepoName: repo.Name,
  446. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  447. OldCommitID: opts.LastCommitID,
  448. NewCommitID: commit.ID.String(),
  449. Commits: pushCommits,
  450. }); err != nil {
  451. log.Error(4, "CommitRepoAction: %v", err)
  452. return nil
  453. }
  454. return DeleteUploads(uploads...)
  455. }