You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_editor.go 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. "code.gitea.io/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/process"
  20. "code.gitea.io/gitea/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. // DiscardLocalRepoBranchChanges discards the local repository branch changes
  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. // CheckoutNewBranch checks out a new branch
  60. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  61. return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
  62. }
  63. // UpdateRepoFileOptions holds the repository file update options
  64. type UpdateRepoFileOptions struct {
  65. LastCommitID string
  66. OldBranch string
  67. NewBranch string
  68. OldTreeName string
  69. NewTreeName string
  70. Message string
  71. Content string
  72. IsNewFile bool
  73. }
  74. // UpdateRepoFile adds or updates a file in repository.
  75. func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
  76. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  77. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  78. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  79. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  80. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  81. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  82. }
  83. if opts.OldBranch != opts.NewBranch {
  84. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  85. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  86. }
  87. }
  88. localPath := repo.LocalCopyPath()
  89. oldFilePath := path.Join(localPath, opts.OldTreeName)
  90. filePath := path.Join(localPath, opts.NewTreeName)
  91. dir := path.Dir(filePath)
  92. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  93. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  94. }
  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, git.PushOptions{
  119. Remote: "origin",
  120. Branch: opts.NewBranch,
  121. }); err != nil {
  122. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  123. }
  124. gitRepo, err := git.OpenRepository(repo.RepoPath())
  125. if err != nil {
  126. log.Error(4, "OpenRepository: %v", err)
  127. return nil
  128. }
  129. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  130. if err != nil {
  131. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  132. return nil
  133. }
  134. // Simulate push event.
  135. oldCommitID := opts.LastCommitID
  136. if opts.NewBranch != opts.OldBranch {
  137. oldCommitID = git.EmptySHA
  138. }
  139. if err = repo.GetOwner(); err != nil {
  140. return fmt.Errorf("GetOwner: %v", err)
  141. }
  142. err = PushUpdate(
  143. opts.NewBranch,
  144. PushUpdateOptions{
  145. PusherID: doer.ID,
  146. PusherName: doer.Name,
  147. RepoUserName: repo.Owner.Name,
  148. RepoName: repo.Name,
  149. RefFullName: git.BranchPrefix + opts.NewBranch,
  150. OldCommitID: oldCommitID,
  151. NewCommitID: commit.ID.String(),
  152. },
  153. )
  154. if err != nil {
  155. return fmt.Errorf("PushUpdate: %v", err)
  156. }
  157. return nil
  158. }
  159. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  160. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *Diff, err error) {
  161. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  162. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  163. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  164. return nil, fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", branch, err)
  165. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  166. return nil, fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", branch, err)
  167. }
  168. localPath := repo.LocalCopyPath()
  169. filePath := path.Join(localPath, treePath)
  170. dir := filepath.Dir(filePath)
  171. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  172. return nil, fmt.Errorf("Failed to create dir %s: %v", dir, err)
  173. }
  174. if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
  175. return nil, fmt.Errorf("WriteFile: %v", err)
  176. }
  177. cmd := exec.Command("git", "diff", treePath)
  178. cmd.Dir = localPath
  179. cmd.Stderr = os.Stderr
  180. stdout, err := cmd.StdoutPipe()
  181. if err != nil {
  182. return nil, fmt.Errorf("StdoutPipe: %v", err)
  183. }
  184. if err = cmd.Start(); err != nil {
  185. return nil, fmt.Errorf("Start: %v", err)
  186. }
  187. pid := process.GetManager().Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  188. defer process.GetManager().Remove(pid)
  189. diff, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdout)
  190. if err != nil {
  191. return nil, fmt.Errorf("ParsePatch: %v", err)
  192. }
  193. if err = cmd.Wait(); err != nil {
  194. return nil, fmt.Errorf("Wait: %v", err)
  195. }
  196. return diff, nil
  197. }
  198. // ________ .__ __ ___________.__.__
  199. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  200. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  201. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  202. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  203. // \/ \/ \/ \/ \/ \/
  204. //
  205. // DeleteRepoFileOptions holds the repository delete file options
  206. type DeleteRepoFileOptions struct {
  207. LastCommitID string
  208. OldBranch string
  209. NewBranch string
  210. TreePath string
  211. Message string
  212. }
  213. // DeleteRepoFile deletes a repository file
  214. func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  215. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  216. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  217. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  218. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  219. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  220. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  221. }
  222. if opts.OldBranch != opts.NewBranch {
  223. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  224. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  225. }
  226. }
  227. localPath := repo.LocalCopyPath()
  228. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  229. return fmt.Errorf("Remove: %v", err)
  230. }
  231. if err = git.AddChanges(localPath, true); err != nil {
  232. return fmt.Errorf("git add --all: %v", err)
  233. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  234. Committer: doer.NewGitSig(),
  235. Message: opts.Message,
  236. }); err != nil {
  237. return fmt.Errorf("CommitChanges: %v", err)
  238. } else if err = git.Push(localPath, git.PushOptions{
  239. Remote: "origin",
  240. Branch: opts.NewBranch,
  241. }); err != nil {
  242. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  243. }
  244. gitRepo, err := git.OpenRepository(repo.RepoPath())
  245. if err != nil {
  246. log.Error(4, "OpenRepository: %v", err)
  247. return nil
  248. }
  249. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  250. if err != nil {
  251. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  252. return nil
  253. }
  254. // Simulate push event.
  255. oldCommitID := opts.LastCommitID
  256. if opts.NewBranch != opts.OldBranch {
  257. oldCommitID = git.EmptySHA
  258. }
  259. if err = repo.GetOwner(); err != nil {
  260. return fmt.Errorf("GetOwner: %v", err)
  261. }
  262. err = PushUpdate(
  263. opts.NewBranch,
  264. PushUpdateOptions{
  265. PusherID: doer.ID,
  266. PusherName: doer.Name,
  267. RepoUserName: repo.Owner.Name,
  268. RepoName: repo.Name,
  269. RefFullName: git.BranchPrefix + opts.NewBranch,
  270. OldCommitID: oldCommitID,
  271. NewCommitID: commit.ID.String(),
  272. },
  273. )
  274. if err != nil {
  275. return fmt.Errorf("PushUpdate: %v", err)
  276. }
  277. return nil
  278. }
  279. // ____ ___ .__ .___ ___________.___.__
  280. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  281. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  282. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  283. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  284. // |__| \/ \/ \/ \/ \/
  285. //
  286. // Upload represent a uploaded file to a repo to be deleted when moved
  287. type Upload struct {
  288. ID int64 `xorm:"pk autoincr"`
  289. UUID string `xorm:"uuid UNIQUE"`
  290. Name string
  291. }
  292. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  293. func UploadLocalPath(uuid string) string {
  294. return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  295. }
  296. // LocalPath returns where uploads are temporarily stored in local file system.
  297. func (upload *Upload) LocalPath() string {
  298. return UploadLocalPath(upload.UUID)
  299. }
  300. // NewUpload creates a new upload object.
  301. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  302. upload := &Upload{
  303. UUID: gouuid.NewV4().String(),
  304. Name: name,
  305. }
  306. localPath := upload.LocalPath()
  307. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  308. return nil, fmt.Errorf("MkdirAll: %v", err)
  309. }
  310. fw, err := os.Create(localPath)
  311. if err != nil {
  312. return nil, fmt.Errorf("Create: %v", err)
  313. }
  314. defer fw.Close()
  315. if _, err = fw.Write(buf); err != nil {
  316. return nil, fmt.Errorf("Write: %v", err)
  317. } else if _, err = io.Copy(fw, file); err != nil {
  318. return nil, fmt.Errorf("Copy: %v", err)
  319. }
  320. if _, err := x.Insert(upload); err != nil {
  321. return nil, err
  322. }
  323. return upload, nil
  324. }
  325. // GetUploadByUUID returns the Upload by UUID
  326. func GetUploadByUUID(uuid string) (*Upload, error) {
  327. upload := &Upload{UUID: uuid}
  328. has, err := x.Get(upload)
  329. if err != nil {
  330. return nil, err
  331. } else if !has {
  332. return nil, ErrUploadNotExist{0, uuid}
  333. }
  334. return upload, nil
  335. }
  336. // GetUploadsByUUIDs returns multiple uploads by UUIDS
  337. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  338. if len(uuids) == 0 {
  339. return []*Upload{}, nil
  340. }
  341. // Silently drop invalid uuids.
  342. uploads := make([]*Upload, 0, len(uuids))
  343. return uploads, x.In("uuid", uuids).Find(&uploads)
  344. }
  345. // DeleteUploads deletes multiple uploads
  346. func DeleteUploads(uploads ...*Upload) (err error) {
  347. if len(uploads) == 0 {
  348. return nil
  349. }
  350. sess := x.NewSession()
  351. defer sess.Close()
  352. if err = sess.Begin(); err != nil {
  353. return err
  354. }
  355. ids := make([]int64, len(uploads))
  356. for i := 0; i < len(uploads); i++ {
  357. ids[i] = uploads[i].ID
  358. }
  359. if _, err = sess.
  360. In("id", ids).
  361. Delete(new(Upload)); err != nil {
  362. return fmt.Errorf("delete uploads: %v", err)
  363. }
  364. for _, upload := range uploads {
  365. localPath := upload.LocalPath()
  366. if !com.IsFile(localPath) {
  367. continue
  368. }
  369. if err := os.Remove(localPath); err != nil {
  370. return fmt.Errorf("remove upload: %v", err)
  371. }
  372. }
  373. return sess.Commit()
  374. }
  375. // DeleteUpload delete a upload
  376. func DeleteUpload(u *Upload) error {
  377. return DeleteUploads(u)
  378. }
  379. // DeleteUploadByUUID deletes a upload by UUID
  380. func DeleteUploadByUUID(uuid string) error {
  381. upload, err := GetUploadByUUID(uuid)
  382. if err != nil {
  383. if IsErrUploadNotExist(err) {
  384. return nil
  385. }
  386. return fmt.Errorf("GetUploadByUUID: %v", err)
  387. }
  388. if err := DeleteUpload(upload); err != nil {
  389. return fmt.Errorf("DeleteUpload: %v", err)
  390. }
  391. return nil
  392. }
  393. // UploadRepoFileOptions contains the uploaded repository file options
  394. type UploadRepoFileOptions struct {
  395. LastCommitID string
  396. OldBranch string
  397. NewBranch string
  398. TreePath string
  399. Message string
  400. Files []string // In UUID format.
  401. }
  402. // UploadRepoFiles uploads files to a repository
  403. func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
  404. if len(opts.Files) == 0 {
  405. return nil
  406. }
  407. uploads, err := GetUploadsByUUIDs(opts.Files)
  408. if err != nil {
  409. return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %v", opts.Files, err)
  410. }
  411. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  412. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  413. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  414. return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
  415. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  416. return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
  417. }
  418. if opts.OldBranch != opts.NewBranch {
  419. if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  420. return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
  421. }
  422. }
  423. localPath := repo.LocalCopyPath()
  424. dirPath := path.Join(localPath, opts.TreePath)
  425. if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
  426. return fmt.Errorf("Failed to create dir %s: %v", dirPath, err)
  427. }
  428. // Copy uploaded files into repository.
  429. for _, upload := range uploads {
  430. tmpPath := upload.LocalPath()
  431. targetPath := path.Join(dirPath, upload.Name)
  432. if !com.IsFile(tmpPath) {
  433. continue
  434. }
  435. if err = com.Copy(tmpPath, targetPath); err != nil {
  436. return fmt.Errorf("Copy: %v", err)
  437. }
  438. }
  439. if err = git.AddChanges(localPath, true); err != nil {
  440. return fmt.Errorf("git add --all: %v", err)
  441. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  442. Committer: doer.NewGitSig(),
  443. Message: opts.Message,
  444. }); err != nil {
  445. return fmt.Errorf("CommitChanges: %v", err)
  446. } else if err = git.Push(localPath, git.PushOptions{
  447. Remote: "origin",
  448. Branch: opts.NewBranch,
  449. }); err != nil {
  450. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  451. }
  452. gitRepo, err := git.OpenRepository(repo.RepoPath())
  453. if err != nil {
  454. log.Error(4, "OpenRepository: %v", err)
  455. return nil
  456. }
  457. commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
  458. if err != nil {
  459. log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
  460. return nil
  461. }
  462. // Simulate push event.
  463. oldCommitID := opts.LastCommitID
  464. if opts.NewBranch != opts.OldBranch {
  465. oldCommitID = git.EmptySHA
  466. }
  467. if err = repo.GetOwner(); err != nil {
  468. return fmt.Errorf("GetOwner: %v", err)
  469. }
  470. err = PushUpdate(
  471. opts.NewBranch,
  472. PushUpdateOptions{
  473. PusherID: doer.ID,
  474. PusherName: doer.Name,
  475. RepoUserName: repo.Owner.Name,
  476. RepoName: repo.Name,
  477. RefFullName: git.BranchPrefix + opts.NewBranch,
  478. OldCommitID: oldCommitID,
  479. NewCommitID: commit.ID.String(),
  480. },
  481. )
  482. if err != nil {
  483. return fmt.Errorf("PushUpdate: %v", err)
  484. }
  485. return DeleteUploads(uploads...)
  486. }