repo_editor.go 17 KB

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