editor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 repo
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "path"
  10. "strings"
  11. log "gopkg.in/clog.v1"
  12. "github.com/gogits/git-module"
  13. "github.com/gogits/gogs/models"
  14. "github.com/gogits/gogs/pkg/context"
  15. "github.com/gogits/gogs/pkg/form"
  16. "github.com/gogits/gogs/pkg/setting"
  17. "github.com/gogits/gogs/pkg/template"
  18. "github.com/gogits/gogs/pkg/tool"
  19. )
  20. const (
  21. EDIT_FILE = "repo/editor/edit"
  22. EDIT_DIFF_PREVIEW = "repo/editor/diff_preview"
  23. DELETE_FILE = "repo/editor/delete"
  24. UPLOAD_FILE = "repo/editor/upload"
  25. )
  26. // getParentTreeFields returns list of parent tree names and corresponding tree paths
  27. // based on given tree path.
  28. func getParentTreeFields(treePath string) (treeNames []string, treePaths []string) {
  29. if len(treePath) == 0 {
  30. return treeNames, treePaths
  31. }
  32. treeNames = strings.Split(treePath, "/")
  33. treePaths = make([]string, len(treeNames))
  34. for i := range treeNames {
  35. treePaths[i] = strings.Join(treeNames[:i+1], "/")
  36. }
  37. return treeNames, treePaths
  38. }
  39. func editFile(c *context.Context, isNewFile bool) {
  40. c.PageIs("Edit")
  41. c.RequireHighlightJS()
  42. c.RequireSimpleMDE()
  43. c.Data["IsNewFile"] = isNewFile
  44. treeNames, treePaths := getParentTreeFields(c.Repo.TreePath)
  45. if !isNewFile {
  46. entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath)
  47. if err != nil {
  48. c.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err)
  49. return
  50. }
  51. // No way to edit a directory online.
  52. if entry.IsDir() {
  53. c.NotFound()
  54. return
  55. }
  56. blob := entry.Blob()
  57. dataRc, err := blob.Data()
  58. if err != nil {
  59. c.ServerError("blob.Data", err)
  60. return
  61. }
  62. c.Data["FileSize"] = blob.Size()
  63. c.Data["FileName"] = blob.Name()
  64. buf := make([]byte, 1024)
  65. n, _ := dataRc.Read(buf)
  66. buf = buf[:n]
  67. // Only text file are editable online.
  68. if !tool.IsTextFile(buf) {
  69. c.NotFound()
  70. return
  71. }
  72. d, _ := ioutil.ReadAll(dataRc)
  73. buf = append(buf, d...)
  74. if err, content := template.ToUTF8WithErr(buf); err != nil {
  75. if err != nil {
  76. log.Error(2, "ToUTF8WithErr: %v", err)
  77. }
  78. c.Data["FileContent"] = string(buf)
  79. } else {
  80. c.Data["FileContent"] = content
  81. }
  82. } else {
  83. treeNames = append(treeNames, "") // Append empty string to allow user name the new file.
  84. }
  85. c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath)
  86. c.Data["TreeNames"] = treeNames
  87. c.Data["TreePaths"] = treePaths
  88. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  89. c.Data["commit_summary"] = ""
  90. c.Data["commit_message"] = ""
  91. c.Data["commit_choice"] = "direct"
  92. c.Data["new_branch_name"] = ""
  93. c.Data["last_commit"] = c.Repo.Commit.ID
  94. c.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
  95. c.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
  96. c.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
  97. c.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", setting.AppSubURL, c.Repo.Repository.FullName())
  98. c.Success(EDIT_FILE)
  99. }
  100. func EditFile(c *context.Context) {
  101. editFile(c, false)
  102. }
  103. func NewFile(c *context.Context) {
  104. editFile(c, true)
  105. }
  106. func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) {
  107. c.PageIs("Edit")
  108. c.RequireHighlightJS()
  109. c.RequireSimpleMDE()
  110. c.Data["IsNewFile"] = isNewFile
  111. oldBranchName := c.Repo.BranchName
  112. branchName := oldBranchName
  113. oldTreePath := c.Repo.TreePath
  114. lastCommit := f.LastCommit
  115. f.LastCommit = c.Repo.Commit.ID.String()
  116. if f.IsNewBrnach() {
  117. branchName = f.NewBranchName
  118. }
  119. f.TreePath = strings.Trim(f.TreePath, " /")
  120. treeNames, treePaths := getParentTreeFields(f.TreePath)
  121. c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath)
  122. c.Data["TreePath"] = f.TreePath
  123. c.Data["TreeNames"] = treeNames
  124. c.Data["TreePaths"] = treePaths
  125. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName
  126. c.Data["FileContent"] = f.Content
  127. c.Data["commit_summary"] = f.CommitSummary
  128. c.Data["commit_message"] = f.CommitMessage
  129. c.Data["commit_choice"] = f.CommitChoice
  130. c.Data["new_branch_name"] = branchName
  131. c.Data["last_commit"] = f.LastCommit
  132. c.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
  133. c.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
  134. c.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
  135. if c.HasError() {
  136. c.Success(EDIT_FILE)
  137. return
  138. }
  139. if len(f.TreePath) == 0 {
  140. c.FormErr("TreePath")
  141. c.RenderWithErr(c.Tr("repo.editor.filename_cannot_be_empty"), EDIT_FILE, &f)
  142. return
  143. }
  144. if oldBranchName != branchName {
  145. if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
  146. c.FormErr("NewBranchName")
  147. c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), EDIT_FILE, &f)
  148. return
  149. }
  150. }
  151. var newTreePath string
  152. for index, part := range treeNames {
  153. newTreePath = path.Join(newTreePath, part)
  154. entry, err := c.Repo.Commit.GetTreeEntryByPath(newTreePath)
  155. if err != nil {
  156. if git.IsErrNotExist(err) {
  157. // Means there is no item with that name, so we're good
  158. break
  159. }
  160. c.ServerError("Repo.Commit.GetTreeEntryByPath", err)
  161. return
  162. }
  163. if index != len(treeNames)-1 {
  164. if !entry.IsDir() {
  165. c.FormErr("TreePath")
  166. c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), EDIT_FILE, &f)
  167. return
  168. }
  169. } else {
  170. if entry.IsLink() {
  171. c.FormErr("TreePath")
  172. c.RenderWithErr(c.Tr("repo.editor.file_is_a_symlink", part), EDIT_FILE, &f)
  173. return
  174. } else if entry.IsDir() {
  175. c.FormErr("TreePath")
  176. c.RenderWithErr(c.Tr("repo.editor.filename_is_a_directory", part), EDIT_FILE, &f)
  177. return
  178. }
  179. }
  180. }
  181. if !isNewFile {
  182. _, err := c.Repo.Commit.GetTreeEntryByPath(oldTreePath)
  183. if err != nil {
  184. if git.IsErrNotExist(err) {
  185. c.FormErr("TreePath")
  186. c.RenderWithErr(c.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), EDIT_FILE, &f)
  187. } else {
  188. c.ServerError("GetTreeEntryByPath", err)
  189. }
  190. return
  191. }
  192. if lastCommit != c.Repo.CommitID {
  193. files, err := c.Repo.Commit.GetFilesChangedSinceCommit(lastCommit)
  194. if err != nil {
  195. c.ServerError("GetFilesChangedSinceCommit", err)
  196. return
  197. }
  198. for _, file := range files {
  199. if file == f.TreePath {
  200. c.RenderWithErr(c.Tr("repo.editor.file_changed_while_editing", c.Repo.RepoLink+"/compare/"+lastCommit+"..."+c.Repo.CommitID), EDIT_FILE, &f)
  201. return
  202. }
  203. }
  204. }
  205. }
  206. if oldTreePath != f.TreePath {
  207. // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber.
  208. entry, err := c.Repo.Commit.GetTreeEntryByPath(f.TreePath)
  209. if err != nil {
  210. if !git.IsErrNotExist(err) {
  211. c.ServerError("GetTreeEntryByPath", err)
  212. return
  213. }
  214. }
  215. if entry != nil {
  216. c.FormErr("TreePath")
  217. c.RenderWithErr(c.Tr("repo.editor.file_already_exists", f.TreePath), EDIT_FILE, &f)
  218. return
  219. }
  220. }
  221. message := strings.TrimSpace(f.CommitSummary)
  222. if len(message) == 0 {
  223. if isNewFile {
  224. message = c.Tr("repo.editor.add", f.TreePath)
  225. } else {
  226. message = c.Tr("repo.editor.update", f.TreePath)
  227. }
  228. }
  229. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  230. if len(f.CommitMessage) > 0 {
  231. message += "\n\n" + f.CommitMessage
  232. }
  233. if err := c.Repo.Repository.UpdateRepoFile(c.User, models.UpdateRepoFileOptions{
  234. LastCommitID: lastCommit,
  235. OldBranch: oldBranchName,
  236. NewBranch: branchName,
  237. OldTreeName: oldTreePath,
  238. NewTreeName: f.TreePath,
  239. Message: message,
  240. Content: strings.Replace(f.Content, "\r", "", -1),
  241. IsNewFile: isNewFile,
  242. }); err != nil {
  243. c.FormErr("TreePath")
  244. c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, err), EDIT_FILE, &f)
  245. return
  246. }
  247. if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
  248. c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  249. } else {
  250. c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + template.EscapePound(f.TreePath))
  251. }
  252. }
  253. func EditFilePost(ctx *context.Context, f form.EditRepoFile) {
  254. editFilePost(ctx, f, false)
  255. }
  256. func NewFilePost(ctx *context.Context, f form.EditRepoFile) {
  257. editFilePost(ctx, f, true)
  258. }
  259. func DiffPreviewPost(ctx *context.Context, f form.EditPreviewDiff) {
  260. treePath := ctx.Repo.TreePath
  261. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
  262. if err != nil {
  263. ctx.Error(500, "GetTreeEntryByPath: "+err.Error())
  264. return
  265. } else if entry.IsDir() {
  266. ctx.Error(422)
  267. return
  268. }
  269. diff, err := ctx.Repo.Repository.GetDiffPreview(ctx.Repo.BranchName, treePath, f.Content)
  270. if err != nil {
  271. ctx.Error(500, "GetDiffPreview: "+err.Error())
  272. return
  273. }
  274. if diff.NumFiles() == 0 {
  275. ctx.PlainText(200, []byte(ctx.Tr("repo.editor.no_changes_to_show")))
  276. return
  277. }
  278. ctx.Data["File"] = diff.Files[0]
  279. ctx.HTML(200, EDIT_DIFF_PREVIEW)
  280. }
  281. func DeleteFile(ctx *context.Context) {
  282. ctx.Data["PageIsDelete"] = true
  283. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  284. ctx.Data["TreePath"] = ctx.Repo.TreePath
  285. ctx.Data["commit_summary"] = ""
  286. ctx.Data["commit_message"] = ""
  287. ctx.Data["commit_choice"] = "direct"
  288. ctx.Data["new_branch_name"] = ""
  289. ctx.HTML(200, DELETE_FILE)
  290. }
  291. func DeleteFilePost(ctx *context.Context, f form.DeleteRepoFile) {
  292. ctx.Data["PageIsDelete"] = true
  293. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  294. ctx.Data["TreePath"] = ctx.Repo.TreePath
  295. oldBranchName := ctx.Repo.BranchName
  296. branchName := oldBranchName
  297. if f.IsNewBrnach() {
  298. branchName = f.NewBranchName
  299. }
  300. ctx.Data["commit_summary"] = f.CommitSummary
  301. ctx.Data["commit_message"] = f.CommitMessage
  302. ctx.Data["commit_choice"] = f.CommitChoice
  303. ctx.Data["new_branch_name"] = branchName
  304. if ctx.HasError() {
  305. ctx.HTML(200, DELETE_FILE)
  306. return
  307. }
  308. if oldBranchName != branchName {
  309. if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
  310. ctx.Data["Err_NewBranchName"] = true
  311. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &f)
  312. return
  313. }
  314. }
  315. message := strings.TrimSpace(f.CommitSummary)
  316. if len(message) == 0 {
  317. message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
  318. }
  319. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  320. if len(f.CommitMessage) > 0 {
  321. message += "\n\n" + f.CommitMessage
  322. }
  323. if err := ctx.Repo.Repository.DeleteRepoFile(ctx.User, models.DeleteRepoFileOptions{
  324. LastCommitID: ctx.Repo.CommitID,
  325. OldBranch: oldBranchName,
  326. NewBranch: branchName,
  327. TreePath: ctx.Repo.TreePath,
  328. Message: message,
  329. }); err != nil {
  330. ctx.Handle(500, "DeleteRepoFile", err)
  331. return
  332. }
  333. if f.IsNewBrnach() && ctx.Repo.PullRequest.Allowed {
  334. ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  335. } else {
  336. ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath))
  337. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName)
  338. }
  339. }
  340. func renderUploadSettings(ctx *context.Context) {
  341. ctx.Data["RequireDropzone"] = true
  342. ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
  343. ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
  344. ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
  345. }
  346. func UploadFile(ctx *context.Context) {
  347. ctx.Data["PageIsUpload"] = true
  348. renderUploadSettings(ctx)
  349. treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath)
  350. if len(treeNames) == 0 {
  351. // We must at least have one element for user to input.
  352. treeNames = []string{""}
  353. }
  354. ctx.Data["TreeNames"] = treeNames
  355. ctx.Data["TreePaths"] = treePaths
  356. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  357. ctx.Data["commit_summary"] = ""
  358. ctx.Data["commit_message"] = ""
  359. ctx.Data["commit_choice"] = "direct"
  360. ctx.Data["new_branch_name"] = ""
  361. ctx.HTML(200, UPLOAD_FILE)
  362. }
  363. func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) {
  364. ctx.Data["PageIsUpload"] = true
  365. renderUploadSettings(ctx)
  366. oldBranchName := ctx.Repo.BranchName
  367. branchName := oldBranchName
  368. if f.IsNewBrnach() {
  369. branchName = f.NewBranchName
  370. }
  371. f.TreePath = strings.Trim(f.TreePath, " /")
  372. treeNames, treePaths := getParentTreeFields(f.TreePath)
  373. if len(treeNames) == 0 {
  374. // We must at least have one element for user to input.
  375. treeNames = []string{""}
  376. }
  377. ctx.Data["TreePath"] = f.TreePath
  378. ctx.Data["TreeNames"] = treeNames
  379. ctx.Data["TreePaths"] = treePaths
  380. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName
  381. ctx.Data["commit_summary"] = f.CommitSummary
  382. ctx.Data["commit_message"] = f.CommitMessage
  383. ctx.Data["commit_choice"] = f.CommitChoice
  384. ctx.Data["new_branch_name"] = branchName
  385. if ctx.HasError() {
  386. ctx.HTML(200, UPLOAD_FILE)
  387. return
  388. }
  389. if oldBranchName != branchName {
  390. if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
  391. ctx.Data["Err_NewBranchName"] = true
  392. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &f)
  393. return
  394. }
  395. }
  396. var newTreePath string
  397. for _, part := range treeNames {
  398. newTreePath = path.Join(newTreePath, part)
  399. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath)
  400. if err != nil {
  401. if git.IsErrNotExist(err) {
  402. // Means there is no item with that name, so we're good
  403. break
  404. }
  405. ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err)
  406. return
  407. }
  408. // User can only upload files to a directory.
  409. if !entry.IsDir() {
  410. ctx.Data["Err_TreePath"] = true
  411. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f)
  412. return
  413. }
  414. }
  415. message := strings.TrimSpace(f.CommitSummary)
  416. if len(message) == 0 {
  417. message = ctx.Tr("repo.editor.upload_files_to_dir", f.TreePath)
  418. }
  419. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  420. if len(f.CommitMessage) > 0 {
  421. message += "\n\n" + f.CommitMessage
  422. }
  423. if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{
  424. LastCommitID: ctx.Repo.CommitID,
  425. OldBranch: oldBranchName,
  426. NewBranch: branchName,
  427. TreePath: f.TreePath,
  428. Message: message,
  429. Files: f.Files,
  430. }); err != nil {
  431. ctx.Data["Err_TreePath"] = true
  432. ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", f.TreePath, err), UPLOAD_FILE, &f)
  433. return
  434. }
  435. if f.IsNewBrnach() && ctx.Repo.PullRequest.Allowed {
  436. ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  437. } else {
  438. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath)
  439. }
  440. }
  441. func UploadFileToServer(ctx *context.Context) {
  442. file, header, err := ctx.Req.FormFile("file")
  443. if err != nil {
  444. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  445. return
  446. }
  447. defer file.Close()
  448. buf := make([]byte, 1024)
  449. n, _ := file.Read(buf)
  450. if n > 0 {
  451. buf = buf[:n]
  452. }
  453. fileType := http.DetectContentType(buf)
  454. if len(setting.Repository.Upload.AllowedTypes) > 0 {
  455. allowed := false
  456. for _, t := range setting.Repository.Upload.AllowedTypes {
  457. t := strings.Trim(t, " ")
  458. if t == "*/*" || t == fileType {
  459. allowed = true
  460. break
  461. }
  462. }
  463. if !allowed {
  464. ctx.Error(400, ErrFileTypeForbidden.Error())
  465. return
  466. }
  467. }
  468. upload, err := models.NewUpload(header.Filename, buf, file)
  469. if err != nil {
  470. ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
  471. return
  472. }
  473. log.Trace("New file uploaded: %s", upload.UUID)
  474. ctx.JSON(200, map[string]string{
  475. "uuid": upload.UUID,
  476. })
  477. }
  478. func RemoveUploadFileFromServer(ctx *context.Context, f form.RemoveUploadFile) {
  479. if len(f.File) == 0 {
  480. ctx.Status(204)
  481. return
  482. }
  483. if err := models.DeleteUploadByUUID(f.File); err != nil {
  484. ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
  485. return
  486. }
  487. log.Trace("Upload file removed: %s", f.File)
  488. ctx.Status(204)
  489. }