repo_editor.go 15 KB

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