repo_editor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. "strings"
  21. "time"
  22. gouuid "github.com/satori/go.uuid"
  23. "gitlab.com/gitote/com"
  24. "gitlab.com/gitote/git-module"
  25. )
  26. const (
  27. EnvAuthUserID = "GITOTE_AUTH_USER_ID"
  28. EnvAuthUsername = "GITOTE_AUTH_USER_NAME"
  29. EnvAuthUserEmail = "GITOTE_AUTH_USER_EMAIL"
  30. EnvRepoOwnerName = "GITOTE_REPO_OWNER_NAME"
  31. EnvRepoOwnerSlatMD5 = "GITOTE_REPO_OWNER_SALT_MD5"
  32. EnvRepoID = "GITOTE_REPO_ID"
  33. EnvRepoName = "GITOTE_REPO_NAME"
  34. EnvRepoCustomHookPath = "GITOTE_REPO_CUSTOM_HOOKS_PATH"
  35. )
  36. type ComposeHookEnvsOptions struct {
  37. AuthUser *User
  38. OwnerName string
  39. OwnerSalt string
  40. RepoID int64
  41. RepoName string
  42. RepoPath string
  43. }
  44. // ComposeHookEnvs returns the envs
  45. func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
  46. envs := []string{
  47. "SSH_ORIGINAL_COMMAND=1",
  48. EnvAuthUserID + "=" + com.ToStr(opts.AuthUser.ID),
  49. EnvAuthUsername + "=" + opts.AuthUser.Name,
  50. EnvAuthUserEmail + "=" + opts.AuthUser.Email,
  51. EnvRepoOwnerName + "=" + opts.OwnerName,
  52. EnvRepoOwnerSlatMD5 + "=" + tool.MD5(opts.OwnerSalt),
  53. EnvRepoID + "=" + com.ToStr(opts.RepoID),
  54. EnvRepoName + "=" + opts.RepoName,
  55. EnvRepoCustomHookPath + "=" + 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("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  108. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  109. return fmt.Errorf("update local copy 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("delete branch[%s]: %v", opts.NewBranch, err)
  124. }
  125. }
  126. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  127. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, 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 %q %q: %v", opts.OldTreeName, opts.NewTreeName, err)
  144. }
  145. }
  146. if err = ioutil.WriteFile(filePath, []byte(opts.Content), 0666); err != nil {
  147. return fmt.Errorf("write file: %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("commit changes on %q: %v", localPath, err)
  156. } else if err = git.PushWithEnvs(localPath, "origin", opts.NewBranch,
  157. ComposeHookEnvs(ComposeHookEnvsOptions{
  158. AuthUser: doer,
  159. OwnerName: repo.MustOwner().Name,
  160. OwnerSalt: repo.MustOwner().Salt,
  161. RepoID: repo.ID,
  162. RepoName: repo.Name,
  163. RepoPath: repo.RepoPath(),
  164. })); err != nil {
  165. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  166. }
  167. return nil
  168. }
  169. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  170. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *Diff, err error) {
  171. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  172. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  173. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  174. return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
  175. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  176. return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
  177. }
  178. localPath := repo.LocalCopyPath()
  179. filePath := path.Join(localPath, treePath)
  180. os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
  181. if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
  182. return nil, fmt.Errorf("write file: %v", err)
  183. }
  184. cmd := exec.Command("git", "diff", treePath)
  185. cmd.Dir = localPath
  186. cmd.Stderr = os.Stderr
  187. stdout, err := cmd.StdoutPipe()
  188. if err != nil {
  189. return nil, fmt.Errorf("get stdout pipe: %v", err)
  190. }
  191. if err = cmd.Start(); err != nil {
  192. return nil, fmt.Errorf("start: %v", err)
  193. }
  194. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  195. defer process.Remove(pid)
  196. diff, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdout)
  197. if err != nil {
  198. return nil, fmt.Errorf("parse path: %v", err)
  199. }
  200. if err = cmd.Wait(); err != nil {
  201. return nil, fmt.Errorf("wait: %v", err)
  202. }
  203. return diff, nil
  204. }
  205. type DeleteRepoFileOptions struct {
  206. LastCommitID string
  207. OldBranch string
  208. NewBranch string
  209. TreePath string
  210. Message string
  211. }
  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("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  217. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  218. return fmt.Errorf("update local copy 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("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  223. }
  224. }
  225. localPath := repo.LocalCopyPath()
  226. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  227. return fmt.Errorf("remove file %q: %v", opts.TreePath, 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("commit changes to %q: %v", localPath, err)
  236. } else if err = git.PushWithEnvs(localPath, "origin", opts.NewBranch,
  237. ComposeHookEnvs(ComposeHookEnvsOptions{
  238. AuthUser: doer,
  239. OwnerName: repo.MustOwner().Name,
  240. OwnerSalt: repo.MustOwner().Salt,
  241. RepoID: repo.ID,
  242. RepoName: repo.Name,
  243. RepoPath: repo.RepoPath(),
  244. })); err != nil {
  245. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  246. }
  247. return nil
  248. }
  249. // Upload represent a uploaded file to a repo to be deleted when moved
  250. type Upload struct {
  251. ID int64
  252. UUID string `xorm:"uuid UNIQUE"`
  253. Name string
  254. }
  255. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  256. func UploadLocalPath(uuid string) string {
  257. return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  258. }
  259. // LocalPath returns where uploads are temporarily stored in local file system.
  260. func (upload *Upload) LocalPath() string {
  261. return UploadLocalPath(upload.UUID)
  262. }
  263. // NewUpload creates a new upload object.
  264. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  265. upload := &Upload{
  266. UUID: gouuid.NewV4().String(),
  267. Name: tool.SanitizePath(name),
  268. }
  269. localPath := upload.LocalPath()
  270. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  271. return nil, fmt.Errorf("mkdir all: %v", err)
  272. }
  273. fw, err := os.Create(localPath)
  274. if err != nil {
  275. return nil, fmt.Errorf("create: %v", err)
  276. }
  277. defer fw.Close()
  278. if _, err = fw.Write(buf); err != nil {
  279. return nil, fmt.Errorf("write: %v", err)
  280. } else if _, err = io.Copy(fw, file); err != nil {
  281. return nil, fmt.Errorf("copy: %v", err)
  282. }
  283. if _, err := x.Insert(upload); err != nil {
  284. return nil, err
  285. }
  286. return upload, nil
  287. }
  288. // GetUploadByUUID returns the Upload by UUID
  289. func GetUploadByUUID(uuid string) (*Upload, error) {
  290. upload := &Upload{UUID: uuid}
  291. has, err := x.Get(upload)
  292. if err != nil {
  293. return nil, err
  294. } else if !has {
  295. return nil, ErrUploadNotExist{0, uuid}
  296. }
  297. return upload, nil
  298. }
  299. // GetUploadsByUUIDs returns multiple uploads by UUIDS
  300. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  301. if len(uuids) == 0 {
  302. return []*Upload{}, nil
  303. }
  304. // Silently drop invalid uuids.
  305. uploads := make([]*Upload, 0, len(uuids))
  306. return uploads, x.In("uuid", uuids).Find(&uploads)
  307. }
  308. // DeleteUploads deletes multiple uploads
  309. func DeleteUploads(uploads ...*Upload) (err error) {
  310. if len(uploads) == 0 {
  311. return nil
  312. }
  313. sess := x.NewSession()
  314. defer sess.Close()
  315. if err = sess.Begin(); err != nil {
  316. return err
  317. }
  318. ids := make([]int64, len(uploads))
  319. for i := 0; i < len(uploads); i++ {
  320. ids[i] = uploads[i].ID
  321. }
  322. if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
  323. return fmt.Errorf("delete uploads: %v", err)
  324. }
  325. for _, upload := range uploads {
  326. localPath := upload.LocalPath()
  327. if !com.IsFile(localPath) {
  328. continue
  329. }
  330. if err := os.Remove(localPath); err != nil {
  331. return fmt.Errorf("remove upload: %v", err)
  332. }
  333. }
  334. return sess.Commit()
  335. }
  336. // DeleteUpload delete a upload
  337. func DeleteUpload(u *Upload) error {
  338. return DeleteUploads(u)
  339. }
  340. // DeleteUploadByUUID deletes a upload by UUID
  341. func DeleteUploadByUUID(uuid string) error {
  342. upload, err := GetUploadByUUID(uuid)
  343. if err != nil {
  344. if IsErrUploadNotExist(err) {
  345. return nil
  346. }
  347. return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err)
  348. }
  349. if err := DeleteUpload(upload); err != nil {
  350. return fmt.Errorf("delete upload: %v", err)
  351. }
  352. return nil
  353. }
  354. type UploadRepoFileOptions struct {
  355. LastCommitID string
  356. OldBranch string
  357. NewBranch string
  358. TreePath string
  359. Message string
  360. Files []string // In UUID format
  361. }
  362. func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
  363. if len(opts.Files) == 0 {
  364. return nil
  365. }
  366. uploads, err := GetUploadsByUUIDs(opts.Files)
  367. if err != nil {
  368. return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
  369. }
  370. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  371. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  372. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  373. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  374. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  375. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  376. }
  377. if opts.OldBranch != opts.NewBranch {
  378. if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  379. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  380. }
  381. }
  382. localPath := repo.LocalCopyPath()
  383. dirPath := path.Join(localPath, opts.TreePath)
  384. os.MkdirAll(dirPath, os.ModePerm)
  385. // Copy uploaded files into repository
  386. for _, upload := range uploads {
  387. tmpPath := upload.LocalPath()
  388. if !com.IsFile(tmpPath) {
  389. continue
  390. }
  391. // Prevent copying files into .git directory
  392. if strings.HasPrefix(upload.Name, ".git/") {
  393. continue
  394. }
  395. targetPath := path.Join(dirPath, upload.Name)
  396. if err = com.Copy(tmpPath, targetPath); err != nil {
  397. return fmt.Errorf("copy: %v", err)
  398. }
  399. }
  400. if err = git.AddChanges(localPath, true); err != nil {
  401. return fmt.Errorf("git add --all: %v", err)
  402. } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
  403. Committer: doer.NewGitSig(),
  404. Message: opts.Message,
  405. }); err != nil {
  406. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  407. } else if err = git.PushWithEnvs(localPath, "origin", opts.NewBranch,
  408. ComposeHookEnvs(ComposeHookEnvsOptions{
  409. AuthUser: doer,
  410. OwnerName: repo.MustOwner().Name,
  411. OwnerSalt: repo.MustOwner().Salt,
  412. RepoID: repo.ID,
  413. RepoName: repo.Name,
  414. RepoPath: repo.RepoPath(),
  415. })); err != nil {
  416. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  417. }
  418. return DeleteUploads(uploads...)
  419. }