repo_editor.go 15 KB

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