editor.go 15 KB

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