repo_editor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 db
  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. gouuid "github.com/satori/go.uuid"
  17. "github.com/unknwon/com"
  18. "github.com/gogs/git-module"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/db/errors"
  21. "gogs.io/gogs/internal/gitutil"
  22. "gogs.io/gogs/internal/osutil"
  23. "gogs.io/gogs/internal/process"
  24. "gogs.io/gogs/internal/tool"
  25. )
  26. const (
  27. ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID"
  28. ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME"
  29. ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL"
  30. ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME"
  31. ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5"
  32. ENV_REPO_ID = "GOGS_REPO_ID"
  33. ENV_REPO_NAME = "GOGS_REPO_NAME"
  34. ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_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. ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
  48. ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
  49. ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
  50. ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
  51. ENV_REPO_OWNER_SALT_MD5 + "=" + tool.MD5(opts.OwnerSalt),
  52. ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
  53. ENV_REPO_NAME + "=" + opts.RepoName,
  54. ENV_REPO_CUSTOM_HOOKS_PATH + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
  55. }
  56. return envs
  57. }
  58. // ___________ .___.__ __ ___________.__.__
  59. // \_ _____/ __| _/|__|/ |_ \_ _____/|__| | ____
  60. // | __)_ / __ | | \ __\ | __) | | | _/ __ \
  61. // | \/ /_/ | | || | | \ | | |_\ ___/
  62. // /_______ /\____ | |__||__| \___ / |__|____/\___ >
  63. // \/ \/ \/ \/
  64. // discardLocalRepoBranchChanges discards local commits/changes of
  65. // given branch to make sure it is even to remote branch.
  66. func discardLocalRepoBranchChanges(localPath, branch string) error {
  67. if !com.IsExist(localPath) {
  68. return nil
  69. }
  70. // No need to check if nothing in the repository.
  71. if !git.RepoHasBranch(localPath, branch) {
  72. return nil
  73. }
  74. rev := "origin/" + branch
  75. if err := git.RepoReset(localPath, rev, git.ResetOptions{Hard: true}); err != nil {
  76. return fmt.Errorf("reset [revision: %s]: %v", rev, err)
  77. }
  78. return nil
  79. }
  80. func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  81. return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
  82. }
  83. // CheckoutNewBranch checks out to a new branch from the a branch name.
  84. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  85. if err := git.RepoCheckout(repo.LocalCopyPath(), newBranch, git.CheckoutOptions{
  86. BaseBranch: oldBranch,
  87. Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
  88. }); err != nil {
  89. return fmt.Errorf("checkout [base: %s, new: %s]: %v", oldBranch, newBranch, err)
  90. }
  91. return nil
  92. }
  93. type UpdateRepoFileOptions struct {
  94. LastCommitID string
  95. OldBranch string
  96. NewBranch string
  97. OldTreeName string
  98. NewTreeName string
  99. Message string
  100. Content string
  101. IsNewFile bool
  102. }
  103. // UpdateRepoFile adds or updates a file in repository.
  104. func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
  105. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  106. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  107. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  108. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  109. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  110. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  111. }
  112. repoPath := repo.RepoPath()
  113. localPath := repo.LocalCopyPath()
  114. if opts.OldBranch != opts.NewBranch {
  115. // Directly return error if new branch already exists in the server
  116. if git.RepoHasBranch(repoPath, opts.NewBranch) {
  117. return errors.BranchAlreadyExists{Name: opts.NewBranch}
  118. }
  119. // Otherwise, delete branch from local copy in case out of sync
  120. if git.RepoHasBranch(localPath, opts.NewBranch) {
  121. if err = git.RepoDeleteBranch(localPath, opts.NewBranch, git.DeleteBranchOptions{
  122. Force: true,
  123. }); err != nil {
  124. return fmt.Errorf("delete branch %q: %v", opts.NewBranch, err)
  125. }
  126. }
  127. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  128. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  129. }
  130. }
  131. oldFilePath := path.Join(localPath, opts.OldTreeName)
  132. filePath := path.Join(localPath, opts.NewTreeName)
  133. if err = os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil {
  134. return err
  135. }
  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 osutil.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
  145. if err = git.RepoMove(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.RepoAdd(localPath, git.AddOptions{All: true}); err != nil {
  153. return fmt.Errorf("git add --all: %v", err)
  154. } else if err = git.RepoCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  155. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  156. }
  157. envs := 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. })
  165. if err = git.RepoPush(localPath, "origin", opts.NewBranch, git.PushOptions{Envs: envs}); err != nil {
  166. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  167. }
  168. return nil
  169. }
  170. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  171. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
  172. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  173. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  174. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  175. return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
  176. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  177. return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
  178. }
  179. localPath := repo.LocalCopyPath()
  180. filePath := path.Join(localPath, treePath)
  181. if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
  182. return nil, err
  183. }
  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 = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
  200. if err != nil {
  201. return nil, fmt.Errorf("parse diff: %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.RepoAdd(localPath, git.AddOptions{All: true}); err != nil {
  240. return fmt.Errorf("git add --all: %v", err)
  241. } else if err = git.RepoCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  242. return fmt.Errorf("commit changes to %q: %v", localPath, err)
  243. }
  244. envs := ComposeHookEnvs(ComposeHookEnvsOptions{
  245. AuthUser: doer,
  246. OwnerName: repo.MustOwner().Name,
  247. OwnerSalt: repo.MustOwner().Salt,
  248. RepoID: repo.ID,
  249. RepoName: repo.Name,
  250. RepoPath: repo.RepoPath(),
  251. })
  252. if err = git.RepoPush(localPath, "origin", opts.NewBranch, git.PushOptions{Envs: envs}); err != nil {
  253. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  254. }
  255. return nil
  256. }
  257. // ____ ___ .__ .___ ___________.___.__
  258. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  259. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  260. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  261. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  262. // |__| \/ \/ \/ \/ \/
  263. //
  264. // Upload represent a uploaded file to a repo to be deleted when moved
  265. type Upload struct {
  266. ID int64
  267. UUID string `xorm:"uuid UNIQUE"`
  268. Name string
  269. }
  270. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  271. func UploadLocalPath(uuid string) string {
  272. return path.Join(conf.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  273. }
  274. // LocalPath returns where uploads are temporarily stored in local file system.
  275. func (upload *Upload) LocalPath() string {
  276. return UploadLocalPath(upload.UUID)
  277. }
  278. // NewUpload creates a new upload object.
  279. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  280. if tool.IsMaliciousPath(name) {
  281. return nil, fmt.Errorf("malicious path detected: %s", name)
  282. }
  283. upload := &Upload{
  284. UUID: gouuid.NewV4().String(),
  285. Name: name,
  286. }
  287. localPath := upload.LocalPath()
  288. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  289. return nil, fmt.Errorf("mkdir all: %v", err)
  290. }
  291. fw, err := os.Create(localPath)
  292. if err != nil {
  293. return nil, fmt.Errorf("create: %v", err)
  294. }
  295. defer fw.Close()
  296. if _, err = fw.Write(buf); err != nil {
  297. return nil, fmt.Errorf("write: %v", err)
  298. } else if _, err = io.Copy(fw, file); err != nil {
  299. return nil, fmt.Errorf("copy: %v", err)
  300. }
  301. if _, err := x.Insert(upload); err != nil {
  302. return nil, err
  303. }
  304. return upload, nil
  305. }
  306. func GetUploadByUUID(uuid string) (*Upload, error) {
  307. upload := &Upload{UUID: uuid}
  308. has, err := x.Get(upload)
  309. if err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, ErrUploadNotExist{0, uuid}
  313. }
  314. return upload, nil
  315. }
  316. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  317. if len(uuids) == 0 {
  318. return []*Upload{}, nil
  319. }
  320. // Silently drop invalid uuids.
  321. uploads := make([]*Upload, 0, len(uuids))
  322. return uploads, x.In("uuid", uuids).Find(&uploads)
  323. }
  324. func DeleteUploads(uploads ...*Upload) (err error) {
  325. if len(uploads) == 0 {
  326. return nil
  327. }
  328. sess := x.NewSession()
  329. defer sess.Close()
  330. if err = sess.Begin(); err != nil {
  331. return err
  332. }
  333. ids := make([]int64, len(uploads))
  334. for i := 0; i < len(uploads); i++ {
  335. ids[i] = uploads[i].ID
  336. }
  337. if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
  338. return fmt.Errorf("delete uploads: %v", err)
  339. }
  340. for _, upload := range uploads {
  341. localPath := upload.LocalPath()
  342. if !osutil.IsFile(localPath) {
  343. continue
  344. }
  345. if err := os.Remove(localPath); err != nil {
  346. return fmt.Errorf("remove upload: %v", err)
  347. }
  348. }
  349. return sess.Commit()
  350. }
  351. func DeleteUpload(u *Upload) error {
  352. return DeleteUploads(u)
  353. }
  354. func DeleteUploadByUUID(uuid string) error {
  355. upload, err := GetUploadByUUID(uuid)
  356. if err != nil {
  357. if IsErrUploadNotExist(err) {
  358. return nil
  359. }
  360. return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err)
  361. }
  362. if err := DeleteUpload(upload); err != nil {
  363. return fmt.Errorf("delete upload: %v", err)
  364. }
  365. return nil
  366. }
  367. type UploadRepoFileOptions struct {
  368. LastCommitID string
  369. OldBranch string
  370. NewBranch string
  371. TreePath string
  372. Message string
  373. Files []string // In UUID format
  374. }
  375. // isRepositoryGitPath returns true if given path is or resides inside ".git" path of the repository.
  376. func isRepositoryGitPath(path string) bool {
  377. return strings.HasSuffix(path, ".git") || strings.Contains(path, ".git"+string(os.PathSeparator))
  378. }
  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. if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
  402. return err
  403. }
  404. // Copy uploaded files into repository
  405. for _, upload := range uploads {
  406. tmpPath := upload.LocalPath()
  407. if !osutil.IsFile(tmpPath) {
  408. continue
  409. }
  410. // Prevent copying files into .git directory, see https://gogs.io/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.RepoAdd(localPath, git.AddOptions{All: true}); err != nil {
  420. return fmt.Errorf("git add --all: %v", err)
  421. } else if err = git.RepoCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  422. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  423. }
  424. envs := ComposeHookEnvs(ComposeHookEnvsOptions{
  425. AuthUser: doer,
  426. OwnerName: repo.MustOwner().Name,
  427. OwnerSalt: repo.MustOwner().Salt,
  428. RepoID: repo.ID,
  429. RepoName: repo.Name,
  430. RepoPath: repo.RepoPath(),
  431. })
  432. if err = git.RepoPush(localPath, "origin", opts.NewBranch, git.PushOptions{Envs: envs}); err != nil {
  433. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  434. }
  435. return DeleteUploads(uploads...)
  436. }