editor.go 15 KB

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