editor.go 15 KB

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