repo_editor.go 16 KB

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