repo_editor.go 15 KB

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