repo_editor.go 15 KB

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