You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

editor.go 15KB

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