editor.go 15 KB

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