repo_editor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. git "github.com/gogits/git-module"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/process"
  20. "github.com/gogits/gogs/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. func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  45. return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
  46. }
  47. // checkoutNewBranch checks out to a new branch from the a branch name.
  48. func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error {
  49. if err := git.Checkout(localPath, git.CheckoutOptions{
  50. Timeout: time.Duration(setting.Git.Timeout.Pull) * time.Second,
  51. Branch: newBranch,
  52. OldBranch: oldBranch,
  53. }); err != nil {
  54. return fmt.Errorf("git checkout -b %s %s: %v", newBranch, oldBranch, err)
  55. }
  56. return nil
  57. }
  58. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  59. return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
  60. }
  61. type UpdateRepoFileOptions struct {
  62. LastCommitID string
  63. OldBranch string
  64. NewBranch string
  65. OldTreeName string
  66. NewTreeName string
  67. Message string
  68. Content string
  69. IsNewFile bool
  70. }
  71. // UpdateRepoFile adds or updates a file in repository.
  72. func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
  73. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  74. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  75. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  76. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  77. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  78. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  79. }
  80. if opts.OldBranch != opts.NewBranch {
  81. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  82. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  83. }
  84. }
  85. localPath := repo.LocalCopyPath()
  86. oldFilePath := path.Join(localPath, opts.OldTreeName)
  87. filePath := path.Join(localPath, opts.NewTreeName)
  88. os.MkdirAll(path.Dir(filePath), os.ModePerm)
  89. // If it's meant to be a new file, make sure it doesn't exist.
  90. if opts.IsNewFile {
  91. if com.IsExist(filePath) {
  92. return ErrRepoFileAlreadyExist{filePath}
  93. }
  94. }
  95. // Ignore move step if it's a new file under a directory.
  96. // Otherwise, move the file when name changed.
  97. if com.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
  98. if err = git.MoveFile(localPath, opts.OldTreeName, opts.NewTreeName); err != nil {
  99. return fmt.Errorf("git mv %s %s: %v", opts.OldTreeName, opts.NewTreeName, err)
  100. }
  101. }
  102. if err = ioutil.WriteFile(filePath, []byte(opts.Content), 0666); err != nil {
  103. return fmt.Errorf("WriteFile: %v", err)
  104. }
  105. if err = git.AddChanges(localPath, true); err != nil {
  106. return fmt.Errorf("git add --all: %v", err)
  107. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  108. Committer: doer.NewGitSig(),
  109. Message: opts.Message,
  110. }); err != nil {
  111. return fmt.Errorf("CommitChanges: %v", err)
  112. } else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil {
  113. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  114. }
  115. gitRepo, err := git.OpenRepository(repo.RepoPath())
  116. if err != nil {
  117. log.Error(4, "OpenRepository: %v", err)
  118. return nil
  119. }
  120. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  121. if err != nil {
  122. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  123. return nil
  124. }
  125. // Simulate push event.
  126. pushCommits := &PushCommits{
  127. Len: 1,
  128. Commits: []*PushCommit{CommitToPushCommit(commit)},
  129. }
  130. oldCommitID := opts.LastCommitID
  131. if opts.NewBranch != opts.OldBranch {
  132. oldCommitID = git.EMPTY_SHA
  133. }
  134. if err := CommitRepoAction(CommitRepoActionOptions{
  135. PusherName: doer.Name,
  136. RepoOwnerID: repo.MustOwner().ID,
  137. RepoName: repo.Name,
  138. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  139. OldCommitID: oldCommitID,
  140. NewCommitID: commit.ID.String(),
  141. Commits: pushCommits,
  142. }); err != nil {
  143. log.Error(4, "CommitRepoAction: %v", err)
  144. return nil
  145. }
  146. return nil
  147. }
  148. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  149. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *Diff, err error) {
  150. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  151. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  152. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  153. return nil, fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", branch, err)
  154. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  155. return nil, fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", branch, err)
  156. }
  157. localPath := repo.LocalCopyPath()
  158. filePath := path.Join(localPath, treePath)
  159. os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
  160. if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
  161. return nil, fmt.Errorf("WriteFile: %v", err)
  162. }
  163. cmd := exec.Command("git", "diff", treePath)
  164. cmd.Dir = localPath
  165. cmd.Stderr = os.Stderr
  166. stdout, err := cmd.StdoutPipe()
  167. if err != nil {
  168. return nil, fmt.Errorf("StdoutPipe: %v", err)
  169. }
  170. if err = cmd.Start(); err != nil {
  171. return nil, fmt.Errorf("Start: %v", err)
  172. }
  173. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  174. defer process.Remove(pid)
  175. diff, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdout)
  176. if err != nil {
  177. return nil, fmt.Errorf("ParsePatch: %v", err)
  178. }
  179. if err = cmd.Wait(); err != nil {
  180. return nil, fmt.Errorf("Wait: %v", err)
  181. }
  182. return diff, nil
  183. }
  184. // ________ .__ __ ___________.__.__
  185. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  186. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  187. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  188. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  189. // \/ \/ \/ \/ \/ \/
  190. //
  191. type DeleteRepoFileOptions struct {
  192. LastCommitID string
  193. OldBranch string
  194. NewBranch string
  195. TreePath string
  196. Message string
  197. }
  198. func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  199. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  200. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  201. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  202. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  203. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  204. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  205. }
  206. if opts.OldBranch != opts.NewBranch {
  207. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  208. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  209. }
  210. }
  211. localPath := repo.LocalCopyPath()
  212. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  213. return fmt.Errorf("Remove: %v", err)
  214. }
  215. if err = git.AddChanges(localPath, true); err != nil {
  216. return fmt.Errorf("git add --all: %v", err)
  217. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  218. Committer: doer.NewGitSig(),
  219. Message: opts.Message,
  220. }); err != nil {
  221. return fmt.Errorf("CommitChanges: %v", err)
  222. } else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil {
  223. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  224. }
  225. gitRepo, err := git.OpenRepository(repo.RepoPath())
  226. if err != nil {
  227. log.Error(4, "OpenRepository: %v", err)
  228. return nil
  229. }
  230. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  231. if err != nil {
  232. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  233. return nil
  234. }
  235. // Simulate push event.
  236. pushCommits := &PushCommits{
  237. Len: 1,
  238. Commits: []*PushCommit{CommitToPushCommit(commit)},
  239. }
  240. if err := CommitRepoAction(CommitRepoActionOptions{
  241. PusherName: doer.Name,
  242. RepoOwnerID: repo.MustOwner().ID,
  243. RepoName: repo.Name,
  244. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  245. OldCommitID: opts.LastCommitID,
  246. NewCommitID: commit.ID.String(),
  247. Commits: pushCommits,
  248. }); err != nil {
  249. log.Error(4, "CommitRepoAction: %v", err)
  250. return nil
  251. }
  252. return nil
  253. }
  254. // ____ ___ .__ .___ ___________.___.__
  255. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  256. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  257. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  258. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  259. // |__| \/ \/ \/ \/ \/
  260. //
  261. // Upload represent a uploaded file to a repo to be deleted when moved
  262. type Upload struct {
  263. ID int64 `xorm:"pk autoincr"`
  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 sessionRelease(sess)
  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. log.Error(4, "OpenRepository: %v", err)
  416. return nil
  417. }
  418. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  419. if err != nil {
  420. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  421. return nil
  422. }
  423. // Simulate push event.
  424. pushCommits := &PushCommits{
  425. Len: 1,
  426. Commits: []*PushCommit{CommitToPushCommit(commit)},
  427. }
  428. if err := CommitRepoAction(CommitRepoActionOptions{
  429. PusherName: doer.Name,
  430. RepoOwnerID: repo.MustOwner().ID,
  431. RepoName: repo.Name,
  432. RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
  433. OldCommitID: opts.LastCommitID,
  434. NewCommitID: commit.ID.String(),
  435. Commits: pushCommits,
  436. }); err != nil {
  437. log.Error(4, "CommitRepoAction: %v", err)
  438. return nil
  439. }
  440. return DeleteUploads(uploads...)
  441. }