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

555 lines
16 KiB

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