repo_editor.go 16 KB

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