editor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. "github.com/gogits/git-module"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/modules/auth"
  14. "github.com/gogits/gogs/modules/base"
  15. "github.com/gogits/gogs/modules/context"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/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.IsLink() {
  160. ctx.Data["Err_TreePath"] = true
  161. ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", part), EDIT_FILE, &form)
  162. return
  163. }
  164. if entry.IsDir() {
  165. ctx.Data["Err_TreePath"] = true
  166. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", part), EDIT_FILE, &form)
  167. return
  168. }
  169. }
  170. }
  171. if !isNewFile {
  172. _, err := ctx.Repo.Commit.GetTreeEntryByPath(oldTreePath)
  173. if err != nil {
  174. if git.IsErrNotExist(err) {
  175. ctx.Data["Err_TreePath"] = true
  176. ctx.RenderWithErr(ctx.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), EDIT_FILE, &form)
  177. } else {
  178. ctx.Handle(500, "GetTreeEntryByPath", err)
  179. }
  180. return
  181. }
  182. if lastCommit != ctx.Repo.CommitID {
  183. files, err := ctx.Repo.Commit.GetFilesChangedSinceCommit(lastCommit)
  184. if err != nil {
  185. ctx.Handle(500, "GetFilesChangedSinceCommit", err)
  186. return
  187. }
  188. for _, file := range files {
  189. if file == form.TreePath {
  190. ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+lastCommit+"..."+ctx.Repo.CommitID), EDIT_FILE, &form)
  191. return
  192. }
  193. }
  194. }
  195. }
  196. if oldTreePath != form.TreePath {
  197. // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber.
  198. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(form.TreePath)
  199. if err != nil {
  200. if !git.IsErrNotExist(err) {
  201. ctx.Handle(500, "GetTreeEntryByPath", err)
  202. return
  203. }
  204. }
  205. if entry != nil {
  206. ctx.Data["Err_TreePath"] = true
  207. ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", form.TreePath), EDIT_FILE, &form)
  208. return
  209. }
  210. }
  211. message := strings.TrimSpace(form.CommitSummary)
  212. if len(message) == 0 {
  213. if isNewFile {
  214. message = ctx.Tr("repo.editor.add", form.TreePath)
  215. } else {
  216. message = ctx.Tr("repo.editor.update", form.TreePath)
  217. }
  218. }
  219. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  220. if len(form.CommitMessage) > 0 {
  221. message += "\n\n" + form.CommitMessage
  222. }
  223. if err := ctx.Repo.Repository.UpdateRepoFile(ctx.User, models.UpdateRepoFileOptions{
  224. LastCommitID: lastCommit,
  225. OldBranch: oldBranchName,
  226. NewBranch: branchName,
  227. OldTreeName: oldTreePath,
  228. NewTreeName: form.TreePath,
  229. Message: message,
  230. Content: strings.Replace(form.Content, "\r", "", -1),
  231. IsNewFile: isNewFile,
  232. }); err != nil {
  233. ctx.Data["Err_TreePath"] = true
  234. ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, err), EDIT_FILE, &form)
  235. return
  236. }
  237. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + template.EscapePound(form.TreePath))
  238. }
  239. func EditFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  240. editFilePost(ctx, form, false)
  241. }
  242. func NewFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  243. editFilePost(ctx, form, true)
  244. }
  245. func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) {
  246. treePath := ctx.Repo.TreePath
  247. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
  248. if err != nil {
  249. ctx.Error(500, "GetTreeEntryByPath: "+err.Error())
  250. return
  251. } else if entry.IsDir() {
  252. ctx.Error(422)
  253. return
  254. }
  255. diff, err := ctx.Repo.Repository.GetDiffPreview(ctx.Repo.BranchName, treePath, form.Content)
  256. if err != nil {
  257. ctx.Error(500, "GetDiffPreview: "+err.Error())
  258. return
  259. }
  260. if diff.NumFiles() == 0 {
  261. ctx.PlainText(200, []byte(ctx.Tr("repo.editor.no_changes_to_show")))
  262. return
  263. }
  264. ctx.Data["File"] = diff.Files[0]
  265. ctx.HTML(200, EDIT_DIFF_PREVIEW)
  266. }
  267. func DeleteFile(ctx *context.Context) {
  268. ctx.Data["PageIsDelete"] = true
  269. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  270. ctx.Data["TreePath"] = ctx.Repo.TreePath
  271. ctx.Data["commit_summary"] = ""
  272. ctx.Data["commit_message"] = ""
  273. ctx.Data["commit_choice"] = "direct"
  274. ctx.Data["new_branch_name"] = ""
  275. ctx.HTML(200, DELETE_FILE)
  276. }
  277. func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
  278. ctx.Data["PageIsDelete"] = true
  279. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  280. ctx.Data["TreePath"] = ctx.Repo.TreePath
  281. oldBranchName := ctx.Repo.BranchName
  282. branchName := oldBranchName
  283. if form.CommitChoice == "commit-to-new-branch" {
  284. branchName = form.NewBranchName
  285. }
  286. ctx.Data["commit_summary"] = form.CommitSummary
  287. ctx.Data["commit_message"] = form.CommitMessage
  288. ctx.Data["commit_choice"] = form.CommitChoice
  289. ctx.Data["new_branch_name"] = branchName
  290. if ctx.HasError() {
  291. ctx.HTML(200, DELETE_FILE)
  292. return
  293. }
  294. if oldBranchName != branchName {
  295. if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
  296. ctx.Data["Err_NewBranchName"] = true
  297. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &form)
  298. return
  299. }
  300. }
  301. message := strings.TrimSpace(form.CommitSummary)
  302. if len(message) == 0 {
  303. message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
  304. }
  305. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  306. if len(form.CommitMessage) > 0 {
  307. message += "\n\n" + form.CommitMessage
  308. }
  309. if err := ctx.Repo.Repository.DeleteRepoFile(ctx.User, models.DeleteRepoFileOptions{
  310. LastCommitID: ctx.Repo.CommitID,
  311. OldBranch: oldBranchName,
  312. NewBranch: branchName,
  313. TreePath: ctx.Repo.TreePath,
  314. Message: message,
  315. }); err != nil {
  316. ctx.Handle(500, "DeleteRepoFile", err)
  317. return
  318. }
  319. ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath))
  320. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName)
  321. }
  322. func renderUploadSettings(ctx *context.Context) {
  323. ctx.Data["RequireDropzone"] = true
  324. ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
  325. ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
  326. ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
  327. }
  328. func UploadFile(ctx *context.Context) {
  329. ctx.Data["PageIsUpload"] = true
  330. renderUploadSettings(ctx)
  331. // We must at least have one element for user to input.
  332. treeNames := []string{""}
  333. if len(ctx.Repo.TreePath) > 0 {
  334. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  335. }
  336. ctx.Data["TreeNames"] = treeNames
  337. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  338. ctx.Data["commit_summary"] = ""
  339. ctx.Data["commit_message"] = ""
  340. ctx.Data["commit_choice"] = "direct"
  341. ctx.Data["new_branch_name"] = ""
  342. ctx.HTML(200, UPLOAD_FILE)
  343. }
  344. func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
  345. ctx.Data["PageIsUpload"] = true
  346. renderUploadSettings(ctx)
  347. oldBranchName := ctx.Repo.BranchName
  348. branchName := oldBranchName
  349. if form.CommitChoice == "commit-to-new-branch" {
  350. branchName = form.NewBranchName
  351. }
  352. form.TreePath = strings.Trim(form.TreePath, " /")
  353. // We must at least have one element for user to input.
  354. treeNames := []string{""}
  355. if len(form.TreePath) > 0 {
  356. treeNames = strings.Split(form.TreePath, "/")
  357. }
  358. ctx.Data["TreePath"] = form.TreePath
  359. ctx.Data["TreeNames"] = treeNames
  360. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName
  361. ctx.Data["commit_summary"] = form.CommitSummary
  362. ctx.Data["commit_message"] = form.CommitMessage
  363. ctx.Data["commit_choice"] = form.CommitChoice
  364. ctx.Data["new_branch_name"] = branchName
  365. if ctx.HasError() {
  366. ctx.HTML(200, UPLOAD_FILE)
  367. return
  368. }
  369. if oldBranchName != branchName {
  370. if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
  371. ctx.Data["Err_NewBranchName"] = true
  372. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &form)
  373. return
  374. }
  375. }
  376. var newTreePath string
  377. for _, part := range treeNames {
  378. newTreePath = path.Join(newTreePath, part)
  379. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath)
  380. if err != nil {
  381. if git.IsErrNotExist(err) {
  382. // Means there is no item with that name, so we're good
  383. break
  384. }
  385. ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err)
  386. return
  387. }
  388. // User can only upload files to a directory.
  389. if !entry.IsDir() {
  390. ctx.Data["Err_TreePath"] = true
  391. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &form)
  392. return
  393. }
  394. }
  395. message := strings.TrimSpace(form.CommitSummary)
  396. if len(message) == 0 {
  397. message = ctx.Tr("repo.editor.upload_files_to_dir", form.TreePath)
  398. }
  399. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  400. if len(form.CommitMessage) > 0 {
  401. message += "\n\n" + form.CommitMessage
  402. }
  403. if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{
  404. LastCommitID: ctx.Repo.CommitID,
  405. OldBranch: oldBranchName,
  406. NewBranch: branchName,
  407. TreePath: form.TreePath,
  408. Message: message,
  409. Files: form.Files,
  410. }); err != nil {
  411. ctx.Data["Err_TreePath"] = true
  412. ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), UPLOAD_FILE, &form)
  413. return
  414. }
  415. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + form.TreePath)
  416. }
  417. func UploadFileToServer(ctx *context.Context) {
  418. file, header, err := ctx.Req.FormFile("file")
  419. if err != nil {
  420. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  421. return
  422. }
  423. defer file.Close()
  424. buf := make([]byte, 1024)
  425. n, _ := file.Read(buf)
  426. if n > 0 {
  427. buf = buf[:n]
  428. }
  429. fileType := http.DetectContentType(buf)
  430. if len(setting.Repository.Upload.AllowedTypes) > 0 {
  431. allowed := false
  432. for _, t := range setting.Repository.Upload.AllowedTypes {
  433. t := strings.Trim(t, " ")
  434. if t == "*/*" || t == fileType {
  435. allowed = true
  436. break
  437. }
  438. }
  439. if !allowed {
  440. ctx.Error(400, ErrFileTypeForbidden.Error())
  441. return
  442. }
  443. }
  444. upload, err := models.NewUpload(header.Filename, buf, file)
  445. if err != nil {
  446. ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
  447. return
  448. }
  449. log.Trace("New file uploaded: %s", upload.UUID)
  450. ctx.JSON(200, map[string]string{
  451. "uuid": upload.UUID,
  452. })
  453. }
  454. func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) {
  455. if len(form.File) == 0 {
  456. ctx.Status(204)
  457. return
  458. }
  459. if err := models.DeleteUploadByUUID(form.File); err != nil {
  460. ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
  461. return
  462. }
  463. log.Trace("Upload file removed: %s", form.File)
  464. ctx.Status(204)
  465. }