repo_editor.go 16 KB

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