editor.go 15 KB

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