editor.go 15 KB

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