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 19KB

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