repo_editor.go 14 KB

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