You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

editor.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/repofiles"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/templates"
  20. "code.gitea.io/gitea/modules/util"
  21. )
  22. const (
  23. tplEditFile base.TplName = "repo/editor/edit"
  24. tplEditDiffPreview base.TplName = "repo/editor/diff_preview"
  25. tplDeleteFile base.TplName = "repo/editor/delete"
  26. tplUploadFile base.TplName = "repo/editor/upload"
  27. frmCommitChoiceDirect string = "direct"
  28. frmCommitChoiceNewBranch string = "commit-to-new-branch"
  29. )
  30. func renderCommitRights(ctx *context.Context) bool {
  31. canCommit, err := ctx.Repo.CanCommitToBranch(ctx.User)
  32. if err != nil {
  33. log.Error("CanCommitToBranch: %v", err)
  34. }
  35. ctx.Data["CanCommitToBranch"] = canCommit
  36. return canCommit
  37. }
  38. // getParentTreeFields returns list of parent tree names and corresponding tree paths
  39. // based on given tree path.
  40. func getParentTreeFields(treePath string) (treeNames []string, treePaths []string) {
  41. if len(treePath) == 0 {
  42. return treeNames, treePaths
  43. }
  44. treeNames = strings.Split(treePath, "/")
  45. treePaths = make([]string, len(treeNames))
  46. for i := range treeNames {
  47. treePaths[i] = strings.Join(treeNames[:i+1], "/")
  48. }
  49. return treeNames, treePaths
  50. }
  51. func editFile(ctx *context.Context, isNewFile bool) {
  52. ctx.Data["PageIsEdit"] = true
  53. ctx.Data["IsNewFile"] = isNewFile
  54. ctx.Data["RequireHighlightJS"] = true
  55. ctx.Data["RequireSimpleMDE"] = true
  56. canCommit := renderCommitRights(ctx)
  57. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  58. if treePath != ctx.Repo.TreePath {
  59. if isNewFile {
  60. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_new", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  61. } else {
  62. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_edit", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  63. }
  64. return
  65. }
  66. treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath)
  67. if !isNewFile {
  68. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  69. if err != nil {
  70. ctx.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err)
  71. return
  72. }
  73. // No way to edit a directory online.
  74. if entry.IsDir() {
  75. ctx.NotFound("entry.IsDir", nil)
  76. return
  77. }
  78. blob := entry.Blob()
  79. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  80. ctx.NotFound("blob.Size", err)
  81. return
  82. }
  83. dataRc, err := blob.DataAsync()
  84. if err != nil {
  85. ctx.NotFound("blob.Data", err)
  86. return
  87. }
  88. defer dataRc.Close()
  89. ctx.Data["FileSize"] = blob.Size()
  90. ctx.Data["FileName"] = blob.Name()
  91. buf := make([]byte, 1024)
  92. n, _ := dataRc.Read(buf)
  93. buf = buf[:n]
  94. // Only text file are editable online.
  95. if !base.IsTextFile(buf) {
  96. ctx.NotFound("base.IsTextFile", nil)
  97. return
  98. }
  99. d, _ := ioutil.ReadAll(dataRc)
  100. buf = append(buf, d...)
  101. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  102. if err != nil {
  103. log.Error("ToUTF8WithErr: %v", err)
  104. }
  105. ctx.Data["FileContent"] = string(buf)
  106. } else {
  107. ctx.Data["FileContent"] = content
  108. }
  109. } else {
  110. treeNames = append(treeNames, "") // Append empty string to allow user name the new file.
  111. }
  112. ctx.Data["TreeNames"] = treeNames
  113. ctx.Data["TreePaths"] = treePaths
  114. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  115. ctx.Data["commit_summary"] = ""
  116. ctx.Data["commit_message"] = ""
  117. if canCommit {
  118. ctx.Data["commit_choice"] = frmCommitChoiceDirect
  119. } else {
  120. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  121. }
  122. ctx.Data["new_branch_name"] = ""
  123. ctx.Data["last_commit"] = ctx.Repo.CommitID
  124. ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
  125. ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
  126. ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
  127. ctx.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", setting.AppSubURL, ctx.Repo.Repository.FullName())
  128. ctx.HTML(200, tplEditFile)
  129. }
  130. // EditFile render edit file page
  131. func EditFile(ctx *context.Context) {
  132. editFile(ctx, false)
  133. }
  134. // NewFile render create file page
  135. func NewFile(ctx *context.Context) {
  136. editFile(ctx, true)
  137. }
  138. func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bool) {
  139. canCommit := renderCommitRights(ctx)
  140. treeNames, treePaths := getParentTreeFields(form.TreePath)
  141. branchName := ctx.Repo.BranchName
  142. if form.CommitChoice == frmCommitChoiceNewBranch {
  143. branchName = form.NewBranchName
  144. }
  145. ctx.Data["PageIsEdit"] = true
  146. ctx.Data["IsNewFile"] = isNewFile
  147. ctx.Data["RequireHighlightJS"] = true
  148. ctx.Data["RequireSimpleMDE"] = true
  149. ctx.Data["TreePath"] = form.TreePath
  150. ctx.Data["TreeNames"] = treeNames
  151. ctx.Data["TreePaths"] = treePaths
  152. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/branch/" + ctx.Repo.BranchName
  153. ctx.Data["FileContent"] = form.Content
  154. ctx.Data["commit_summary"] = form.CommitSummary
  155. ctx.Data["commit_message"] = form.CommitMessage
  156. ctx.Data["commit_choice"] = form.CommitChoice
  157. ctx.Data["new_branch_name"] = form.NewBranchName
  158. ctx.Data["last_commit"] = ctx.Repo.CommitID
  159. ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
  160. ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
  161. ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
  162. if ctx.HasError() {
  163. ctx.HTML(200, tplEditFile)
  164. return
  165. }
  166. // Cannot commit to a an existing branch if user doesn't have rights
  167. if branchName == ctx.Repo.BranchName && !canCommit {
  168. ctx.Data["Err_NewBranchName"] = true
  169. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  170. ctx.RenderWithErr(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", branchName), tplEditFile, &form)
  171. return
  172. }
  173. // CommitSummary is optional in the web form, if empty, give it a default message based on add or update
  174. // `message` will be both the summary and message combined
  175. message := strings.TrimSpace(form.CommitSummary)
  176. if len(message) == 0 {
  177. if isNewFile {
  178. message = ctx.Tr("repo.editor.add", form.TreePath)
  179. } else {
  180. message = ctx.Tr("repo.editor.update", form.TreePath)
  181. }
  182. }
  183. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  184. if len(form.CommitMessage) > 0 {
  185. message += "\n\n" + form.CommitMessage
  186. }
  187. if _, err := repofiles.CreateOrUpdateRepoFile(ctx.Repo.Repository, ctx.User, &repofiles.UpdateRepoFileOptions{
  188. LastCommitID: form.LastCommit,
  189. OldBranch: ctx.Repo.BranchName,
  190. NewBranch: branchName,
  191. FromTreePath: ctx.Repo.TreePath,
  192. TreePath: form.TreePath,
  193. Message: message,
  194. Content: strings.Replace(form.Content, "\r", "", -1),
  195. IsNewFile: isNewFile,
  196. }); err != nil {
  197. // This is where we handle all the errors thrown by repofiles.CreateOrUpdateRepoFile
  198. if git.IsErrNotExist(err) {
  199. ctx.RenderWithErr(ctx.Tr("repo.editor.file_editing_no_longer_exists", ctx.Repo.TreePath), tplEditFile, &form)
  200. } else if models.IsErrFilenameInvalid(err) {
  201. ctx.Data["Err_TreePath"] = true
  202. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_invalid", form.TreePath), tplEditFile, &form)
  203. } else if models.IsErrFilePathInvalid(err) {
  204. ctx.Data["Err_TreePath"] = true
  205. if fileErr, ok := err.(models.ErrFilePathInvalid); ok {
  206. switch fileErr.Type {
  207. case git.EntryModeSymlink:
  208. ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", fileErr.Path), tplEditFile, &form)
  209. break
  210. case git.EntryModeTree:
  211. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplEditFile, &form)
  212. break
  213. case git.EntryModeBlob:
  214. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form)
  215. break
  216. default:
  217. ctx.Error(500, err.Error())
  218. break
  219. }
  220. } else {
  221. ctx.Error(500, err.Error())
  222. }
  223. } else if models.IsErrRepoFileAlreadyExists(err) {
  224. ctx.Data["Err_TreePath"] = true
  225. ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", form.TreePath), tplEditFile, &form)
  226. } else if git.IsErrBranchNotExist(err) {
  227. // For when a user adds/updates a file to a branch that no longer exists
  228. if branchErr, ok := err.(git.ErrBranchNotExist); ok {
  229. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplEditFile, &form)
  230. } else {
  231. ctx.Error(500, err.Error())
  232. }
  233. } else if models.IsErrBranchAlreadyExists(err) {
  234. // For when a user specifies a new branch that already exists
  235. ctx.Data["Err_NewBranchName"] = true
  236. if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
  237. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplEditFile, &form)
  238. } else {
  239. ctx.Error(500, err.Error())
  240. }
  241. } else if models.IsErrCommitIDDoesNotMatch(err) {
  242. ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplEditFile, &form)
  243. } else {
  244. ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, err), tplEditFile, &form)
  245. }
  246. } else {
  247. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + branchName + "/" + strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(cleanUploadFileName(form.TreePath)))
  248. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath))
  249. }
  250. }
  251. // EditFilePost response for editing file
  252. func EditFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  253. editFilePost(ctx, form, false)
  254. }
  255. // NewFilePost response for creating file
  256. func NewFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  257. editFilePost(ctx, form, true)
  258. }
  259. // DiffPreviewPost render preview diff page
  260. func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) {
  261. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  262. if len(treePath) == 0 {
  263. ctx.Error(500, "file name to diff is invalid")
  264. return
  265. }
  266. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
  267. if err != nil {
  268. ctx.Error(500, "GetTreeEntryByPath: "+err.Error())
  269. return
  270. } else if entry.IsDir() {
  271. ctx.Error(422)
  272. return
  273. }
  274. diff, err := repofiles.GetDiffPreview(ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content)
  275. if err != nil {
  276. ctx.Error(500, "GetDiffPreview: "+err.Error())
  277. return
  278. }
  279. if diff.NumFiles() == 0 {
  280. ctx.PlainText(200, []byte(ctx.Tr("repo.editor.no_changes_to_show")))
  281. return
  282. }
  283. ctx.Data["File"] = diff.Files[0]
  284. ctx.HTML(200, tplEditDiffPreview)
  285. }
  286. // DeleteFile render delete file page
  287. func DeleteFile(ctx *context.Context) {
  288. ctx.Data["PageIsDelete"] = true
  289. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  290. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  291. if treePath != ctx.Repo.TreePath {
  292. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_delete", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  293. return
  294. }
  295. ctx.Data["TreePath"] = treePath
  296. canCommit := renderCommitRights(ctx)
  297. ctx.Data["commit_summary"] = ""
  298. ctx.Data["commit_message"] = ""
  299. ctx.Data["last_commit"] = ctx.Repo.CommitID
  300. if canCommit {
  301. ctx.Data["commit_choice"] = frmCommitChoiceDirect
  302. } else {
  303. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  304. }
  305. ctx.Data["new_branch_name"] = ""
  306. ctx.HTML(200, tplDeleteFile)
  307. }
  308. // DeleteFilePost response for deleting file
  309. func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
  310. canCommit := renderCommitRights(ctx)
  311. branchName := ctx.Repo.BranchName
  312. if form.CommitChoice == frmCommitChoiceNewBranch {
  313. branchName = form.NewBranchName
  314. }
  315. ctx.Data["PageIsDelete"] = true
  316. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  317. ctx.Data["TreePath"] = ctx.Repo.TreePath
  318. ctx.Data["commit_summary"] = form.CommitSummary
  319. ctx.Data["commit_message"] = form.CommitMessage
  320. ctx.Data["commit_choice"] = form.CommitChoice
  321. ctx.Data["new_branch_name"] = form.NewBranchName
  322. ctx.Data["last_commit"] = ctx.Repo.CommitID
  323. if ctx.HasError() {
  324. ctx.HTML(200, tplDeleteFile)
  325. return
  326. }
  327. if branchName != ctx.Repo.BranchName && !canCommit {
  328. ctx.Data["Err_NewBranchName"] = true
  329. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  330. ctx.RenderWithErr(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", branchName), tplDeleteFile, &form)
  331. return
  332. }
  333. message := strings.TrimSpace(form.CommitSummary)
  334. if len(message) == 0 {
  335. message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
  336. }
  337. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  338. if len(form.CommitMessage) > 0 {
  339. message += "\n\n" + form.CommitMessage
  340. }
  341. if _, err := repofiles.DeleteRepoFile(ctx.Repo.Repository, ctx.User, &repofiles.DeleteRepoFileOptions{
  342. LastCommitID: form.LastCommit,
  343. OldBranch: ctx.Repo.BranchName,
  344. NewBranch: branchName,
  345. TreePath: ctx.Repo.TreePath,
  346. Message: message,
  347. }); err != nil {
  348. // This is where we handle all the errors thrown by repofiles.DeleteRepoFile
  349. if git.IsErrNotExist(err) || models.IsErrRepoFileDoesNotExist(err) {
  350. ctx.RenderWithErr(ctx.Tr("repo.editor.file_deleting_no_longer_exists", ctx.Repo.TreePath), tplEditFile, &form)
  351. } else if models.IsErrFilenameInvalid(err) {
  352. ctx.Data["Err_TreePath"] = true
  353. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_invalid", ctx.Repo.TreePath), tplEditFile, &form)
  354. } else if models.IsErrFilePathInvalid(err) {
  355. ctx.Data["Err_TreePath"] = true
  356. if fileErr, ok := err.(models.ErrFilePathInvalid); ok {
  357. switch fileErr.Type {
  358. case git.EntryModeSymlink:
  359. ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", fileErr.Path), tplEditFile, &form)
  360. break
  361. case git.EntryModeTree:
  362. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplEditFile, &form)
  363. break
  364. case git.EntryModeBlob:
  365. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form)
  366. break
  367. default:
  368. ctx.ServerError("DeleteRepoFile", err)
  369. break
  370. }
  371. } else {
  372. ctx.ServerError("DeleteRepoFile", err)
  373. }
  374. } else if git.IsErrBranchNotExist(err) {
  375. // For when a user deletes a file to a branch that no longer exists
  376. if branchErr, ok := err.(git.ErrBranchNotExist); ok {
  377. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplEditFile, &form)
  378. } else {
  379. ctx.Error(500, err.Error())
  380. }
  381. } else if models.IsErrBranchAlreadyExists(err) {
  382. // For when a user specifies a new branch that already exists
  383. if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
  384. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplEditFile, &form)
  385. } else {
  386. ctx.Error(500, err.Error())
  387. }
  388. } else if models.IsErrCommitIDDoesNotMatch(err) {
  389. ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplEditFile, &form)
  390. } else {
  391. ctx.ServerError("DeleteRepoFile", err)
  392. }
  393. } else {
  394. ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath))
  395. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName))
  396. }
  397. }
  398. func renderUploadSettings(ctx *context.Context) {
  399. ctx.Data["RequireDropzone"] = true
  400. ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
  401. ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
  402. ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
  403. }
  404. // UploadFile render upload file page
  405. func UploadFile(ctx *context.Context) {
  406. ctx.Data["PageIsUpload"] = true
  407. renderUploadSettings(ctx)
  408. canCommit := renderCommitRights(ctx)
  409. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  410. if treePath != ctx.Repo.TreePath {
  411. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_upload", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  412. return
  413. }
  414. ctx.Repo.TreePath = treePath
  415. treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath)
  416. if len(treeNames) == 0 {
  417. // We must at least have one element for user to input.
  418. treeNames = []string{""}
  419. }
  420. ctx.Data["TreeNames"] = treeNames
  421. ctx.Data["TreePaths"] = treePaths
  422. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  423. ctx.Data["commit_summary"] = ""
  424. ctx.Data["commit_message"] = ""
  425. if canCommit {
  426. ctx.Data["commit_choice"] = frmCommitChoiceDirect
  427. } else {
  428. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  429. }
  430. ctx.Data["new_branch_name"] = ""
  431. ctx.HTML(200, tplUploadFile)
  432. }
  433. // UploadFilePost response for uploading file
  434. func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
  435. ctx.Data["PageIsUpload"] = true
  436. renderUploadSettings(ctx)
  437. canCommit := renderCommitRights(ctx)
  438. oldBranchName := ctx.Repo.BranchName
  439. branchName := oldBranchName
  440. if form.CommitChoice == frmCommitChoiceNewBranch {
  441. branchName = form.NewBranchName
  442. }
  443. form.TreePath = cleanUploadFileName(form.TreePath)
  444. treeNames, treePaths := getParentTreeFields(form.TreePath)
  445. if len(treeNames) == 0 {
  446. // We must at least have one element for user to input.
  447. treeNames = []string{""}
  448. }
  449. ctx.Data["TreePath"] = form.TreePath
  450. ctx.Data["TreeNames"] = treeNames
  451. ctx.Data["TreePaths"] = treePaths
  452. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/branch/" + branchName
  453. ctx.Data["commit_summary"] = form.CommitSummary
  454. ctx.Data["commit_message"] = form.CommitMessage
  455. ctx.Data["commit_choice"] = form.CommitChoice
  456. ctx.Data["new_branch_name"] = branchName
  457. if ctx.HasError() {
  458. ctx.HTML(200, tplUploadFile)
  459. return
  460. }
  461. if oldBranchName != branchName {
  462. if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
  463. ctx.Data["Err_NewBranchName"] = true
  464. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplUploadFile, &form)
  465. return
  466. }
  467. } else if !canCommit {
  468. ctx.Data["Err_NewBranchName"] = true
  469. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  470. ctx.RenderWithErr(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", branchName), tplUploadFile, &form)
  471. return
  472. }
  473. var newTreePath string
  474. for _, part := range treeNames {
  475. newTreePath = path.Join(newTreePath, part)
  476. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath)
  477. if err != nil {
  478. if git.IsErrNotExist(err) {
  479. // Means there is no item with that name, so we're good
  480. break
  481. }
  482. ctx.ServerError("Repo.Commit.GetTreeEntryByPath", err)
  483. return
  484. }
  485. // User can only upload files to a directory.
  486. if !entry.IsDir() {
  487. ctx.Data["Err_TreePath"] = true
  488. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), tplUploadFile, &form)
  489. return
  490. }
  491. }
  492. message := strings.TrimSpace(form.CommitSummary)
  493. if len(message) == 0 {
  494. message = ctx.Tr("repo.editor.upload_files_to_dir", form.TreePath)
  495. }
  496. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  497. if len(form.CommitMessage) > 0 {
  498. message += "\n\n" + form.CommitMessage
  499. }
  500. if err := repofiles.UploadRepoFiles(ctx.Repo.Repository, ctx.User, &repofiles.UploadRepoFileOptions{
  501. LastCommitID: ctx.Repo.CommitID,
  502. OldBranch: oldBranchName,
  503. NewBranch: branchName,
  504. TreePath: form.TreePath,
  505. Message: message,
  506. Files: form.Files,
  507. }); err != nil {
  508. ctx.Data["Err_TreePath"] = true
  509. ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), tplUploadFile, &form)
  510. return
  511. }
  512. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath))
  513. }
  514. func cleanUploadFileName(name string) string {
  515. // Rebase the filename
  516. name = strings.Trim(path.Clean("/"+name), " /")
  517. // Git disallows any filenames to have a .git directory in them.
  518. for _, part := range strings.Split(name, "/") {
  519. if strings.ToLower(part) == ".git" {
  520. return ""
  521. }
  522. }
  523. return name
  524. }
  525. // UploadFileToServer upload file to server file dir not git
  526. func UploadFileToServer(ctx *context.Context) {
  527. file, header, err := ctx.Req.FormFile("file")
  528. if err != nil {
  529. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  530. return
  531. }
  532. defer file.Close()
  533. buf := make([]byte, 1024)
  534. n, _ := file.Read(buf)
  535. if n > 0 {
  536. buf = buf[:n]
  537. }
  538. fileType := http.DetectContentType(buf)
  539. if len(setting.Repository.Upload.AllowedTypes) > 0 {
  540. allowed := false
  541. for _, t := range setting.Repository.Upload.AllowedTypes {
  542. t := strings.Trim(t, " ")
  543. if t == "*/*" || t == fileType {
  544. allowed = true
  545. break
  546. }
  547. }
  548. if !allowed {
  549. ctx.Error(400, ErrFileTypeForbidden.Error())
  550. return
  551. }
  552. }
  553. name := cleanUploadFileName(header.Filename)
  554. if len(name) == 0 {
  555. ctx.Error(500, "Upload file name is invalid")
  556. return
  557. }
  558. upload, err := models.NewUpload(name, buf, file)
  559. if err != nil {
  560. ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
  561. return
  562. }
  563. log.Trace("New file uploaded: %s", upload.UUID)
  564. ctx.JSON(200, map[string]string{
  565. "uuid": upload.UUID,
  566. })
  567. }
  568. // RemoveUploadFileFromServer remove file from server file dir
  569. func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) {
  570. if len(form.File) == 0 {
  571. ctx.Status(204)
  572. return
  573. }
  574. if err := models.DeleteUploadByUUID(form.File); err != nil {
  575. ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
  576. return
  577. }
  578. log.Trace("Upload file removed: %s", form.File)
  579. ctx.Status(204)
  580. }