editor.go 16 KB

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