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.

repo_editor.go 16KB

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