repo_editor.go 15 KB

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