repo_editor.go 14 KB

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