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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. "path"
  9. "path/filepath"
  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/charset"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/repofiles"
  19. repo_module "code.gitea.io/gitea/modules/repository"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/upload"
  22. "code.gitea.io/gitea/modules/util"
  23. )
  24. const (
  25. tplEditFile base.TplName = "repo/editor/edit"
  26. tplEditDiffPreview base.TplName = "repo/editor/diff_preview"
  27. tplDeleteFile base.TplName = "repo/editor/delete"
  28. tplUploadFile base.TplName = "repo/editor/upload"
  29. frmCommitChoiceDirect string = "direct"
  30. frmCommitChoiceNewBranch string = "commit-to-new-branch"
  31. )
  32. func renderCommitRights(ctx *context.Context) bool {
  33. canCommitToBranch, err := ctx.Repo.CanCommitToBranch(ctx.User)
  34. if err != nil {
  35. log.Error("CanCommitToBranch: %v", err)
  36. }
  37. ctx.Data["CanCommitToBranch"] = canCommitToBranch
  38. return canCommitToBranch.CanCommitToBranch
  39. }
  40. // getParentTreeFields returns list of parent tree names and corresponding tree paths
  41. // based on given tree path.
  42. func getParentTreeFields(treePath string) (treeNames []string, treePaths []string) {
  43. if len(treePath) == 0 {
  44. return treeNames, treePaths
  45. }
  46. treeNames = strings.Split(treePath, "/")
  47. treePaths = make([]string, len(treeNames))
  48. for i := range treeNames {
  49. treePaths[i] = strings.Join(treeNames[:i+1], "/")
  50. }
  51. return treeNames, treePaths
  52. }
  53. func editFile(ctx *context.Context, isNewFile bool) {
  54. ctx.Data["PageIsEdit"] = true
  55. ctx.Data["IsNewFile"] = isNewFile
  56. ctx.Data["RequireHighlightJS"] = true
  57. ctx.Data["RequireSimpleMDE"] = true
  58. canCommit := renderCommitRights(ctx)
  59. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  60. if treePath != ctx.Repo.TreePath {
  61. if isNewFile {
  62. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_new", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  63. } else {
  64. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_edit", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  65. }
  66. return
  67. }
  68. treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath)
  69. if !isNewFile {
  70. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  71. if err != nil {
  72. ctx.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err)
  73. return
  74. }
  75. // No way to edit a directory online.
  76. if entry.IsDir() {
  77. ctx.NotFound("entry.IsDir", nil)
  78. return
  79. }
  80. blob := entry.Blob()
  81. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  82. ctx.NotFound("blob.Size", err)
  83. return
  84. }
  85. dataRc, err := blob.DataAsync()
  86. if err != nil {
  87. ctx.NotFound("blob.Data", err)
  88. return
  89. }
  90. defer dataRc.Close()
  91. ctx.Data["FileSize"] = blob.Size()
  92. ctx.Data["FileName"] = blob.Name()
  93. buf := make([]byte, 1024)
  94. n, _ := dataRc.Read(buf)
  95. buf = buf[:n]
  96. // Only text file are editable online.
  97. if !base.IsTextFile(buf) {
  98. ctx.NotFound("base.IsTextFile", nil)
  99. return
  100. }
  101. d, _ := ioutil.ReadAll(dataRc)
  102. buf = append(buf, d...)
  103. if content, err := charset.ToUTF8WithErr(buf); err != nil {
  104. log.Error("ToUTF8WithErr: %v", err)
  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"] = GetUniquePatchBranchName(ctx)
  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. case git.EntryModeTree:
  210. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplEditFile, &form)
  211. case git.EntryModeBlob:
  212. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form)
  213. default:
  214. ctx.Error(500, err.Error())
  215. }
  216. } else {
  217. ctx.Error(500, err.Error())
  218. }
  219. } else if models.IsErrRepoFileAlreadyExists(err) {
  220. ctx.Data["Err_TreePath"] = true
  221. ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", form.TreePath), tplEditFile, &form)
  222. } else if git.IsErrBranchNotExist(err) {
  223. // For when a user adds/updates a file to a branch that no longer exists
  224. if branchErr, ok := err.(git.ErrBranchNotExist); ok {
  225. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplEditFile, &form)
  226. } else {
  227. ctx.Error(500, err.Error())
  228. }
  229. } else if models.IsErrBranchAlreadyExists(err) {
  230. // For when a user specifies a new branch that already exists
  231. ctx.Data["Err_NewBranchName"] = true
  232. if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
  233. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplEditFile, &form)
  234. } else {
  235. ctx.Error(500, err.Error())
  236. }
  237. } else if models.IsErrCommitIDDoesNotMatch(err) {
  238. ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplEditFile, &form)
  239. } else {
  240. ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, err), tplEditFile, &form)
  241. }
  242. }
  243. if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) {
  244. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + ctx.Repo.BranchName + "..." + form.NewBranchName)
  245. } else {
  246. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath))
  247. }
  248. }
  249. // EditFilePost response for editing file
  250. func EditFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  251. editFilePost(ctx, form, false)
  252. }
  253. // NewFilePost response for creating file
  254. func NewFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  255. editFilePost(ctx, form, true)
  256. }
  257. // DiffPreviewPost render preview diff page
  258. func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) {
  259. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  260. if len(treePath) == 0 {
  261. ctx.Error(500, "file name to diff is invalid")
  262. return
  263. }
  264. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
  265. if err != nil {
  266. ctx.Error(500, "GetTreeEntryByPath: "+err.Error())
  267. return
  268. } else if entry.IsDir() {
  269. ctx.Error(422)
  270. return
  271. }
  272. diff, err := repofiles.GetDiffPreview(ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content)
  273. if err != nil {
  274. ctx.Error(500, "GetDiffPreview: "+err.Error())
  275. return
  276. }
  277. if diff.NumFiles() == 0 {
  278. ctx.PlainText(200, []byte(ctx.Tr("repo.editor.no_changes_to_show")))
  279. return
  280. }
  281. ctx.Data["File"] = diff.Files[0]
  282. ctx.HTML(200, tplEditDiffPreview)
  283. }
  284. // DeleteFile render delete file page
  285. func DeleteFile(ctx *context.Context) {
  286. ctx.Data["PageIsDelete"] = true
  287. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  288. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  289. if treePath != ctx.Repo.TreePath {
  290. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_delete", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  291. return
  292. }
  293. ctx.Data["TreePath"] = treePath
  294. canCommit := renderCommitRights(ctx)
  295. ctx.Data["commit_summary"] = ""
  296. ctx.Data["commit_message"] = ""
  297. ctx.Data["last_commit"] = ctx.Repo.CommitID
  298. if canCommit {
  299. ctx.Data["commit_choice"] = frmCommitChoiceDirect
  300. } else {
  301. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  302. }
  303. ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx)
  304. ctx.HTML(200, tplDeleteFile)
  305. }
  306. // DeleteFilePost response for deleting file
  307. func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
  308. canCommit := renderCommitRights(ctx)
  309. branchName := ctx.Repo.BranchName
  310. if form.CommitChoice == frmCommitChoiceNewBranch {
  311. branchName = form.NewBranchName
  312. }
  313. ctx.Data["PageIsDelete"] = true
  314. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  315. ctx.Data["TreePath"] = ctx.Repo.TreePath
  316. ctx.Data["commit_summary"] = form.CommitSummary
  317. ctx.Data["commit_message"] = form.CommitMessage
  318. ctx.Data["commit_choice"] = form.CommitChoice
  319. ctx.Data["new_branch_name"] = form.NewBranchName
  320. ctx.Data["last_commit"] = ctx.Repo.CommitID
  321. if ctx.HasError() {
  322. ctx.HTML(200, tplDeleteFile)
  323. return
  324. }
  325. if branchName == ctx.Repo.BranchName && !canCommit {
  326. ctx.Data["Err_NewBranchName"] = true
  327. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  328. ctx.RenderWithErr(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", branchName), tplDeleteFile, &form)
  329. return
  330. }
  331. message := strings.TrimSpace(form.CommitSummary)
  332. if len(message) == 0 {
  333. message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
  334. }
  335. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  336. if len(form.CommitMessage) > 0 {
  337. message += "\n\n" + form.CommitMessage
  338. }
  339. if _, err := repofiles.DeleteRepoFile(ctx.Repo.Repository, ctx.User, &repofiles.DeleteRepoFileOptions{
  340. LastCommitID: form.LastCommit,
  341. OldBranch: ctx.Repo.BranchName,
  342. NewBranch: branchName,
  343. TreePath: ctx.Repo.TreePath,
  344. Message: message,
  345. }); err != nil {
  346. // This is where we handle all the errors thrown by repofiles.DeleteRepoFile
  347. if git.IsErrNotExist(err) || models.IsErrRepoFileDoesNotExist(err) {
  348. ctx.RenderWithErr(ctx.Tr("repo.editor.file_deleting_no_longer_exists", ctx.Repo.TreePath), tplDeleteFile, &form)
  349. } else if models.IsErrFilenameInvalid(err) {
  350. ctx.Data["Err_TreePath"] = true
  351. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_invalid", ctx.Repo.TreePath), tplDeleteFile, &form)
  352. } else if models.IsErrFilePathInvalid(err) {
  353. ctx.Data["Err_TreePath"] = true
  354. if fileErr, ok := err.(models.ErrFilePathInvalid); ok {
  355. switch fileErr.Type {
  356. case git.EntryModeSymlink:
  357. ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", fileErr.Path), tplDeleteFile, &form)
  358. case git.EntryModeTree:
  359. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplDeleteFile, &form)
  360. case git.EntryModeBlob:
  361. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplDeleteFile, &form)
  362. default:
  363. ctx.ServerError("DeleteRepoFile", err)
  364. }
  365. } else {
  366. ctx.ServerError("DeleteRepoFile", err)
  367. }
  368. } else if git.IsErrBranchNotExist(err) {
  369. // For when a user deletes a file to a branch that no longer exists
  370. if branchErr, ok := err.(git.ErrBranchNotExist); ok {
  371. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplDeleteFile, &form)
  372. } else {
  373. ctx.Error(500, err.Error())
  374. }
  375. } else if models.IsErrBranchAlreadyExists(err) {
  376. // For when a user specifies a new branch that already exists
  377. if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
  378. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplDeleteFile, &form)
  379. } else {
  380. ctx.Error(500, err.Error())
  381. }
  382. } else if models.IsErrCommitIDDoesNotMatch(err) {
  383. ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_deleting", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplDeleteFile, &form)
  384. } else {
  385. ctx.ServerError("DeleteRepoFile", err)
  386. }
  387. }
  388. ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath))
  389. if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) {
  390. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + ctx.Repo.BranchName + "..." + form.NewBranchName)
  391. } else {
  392. treePath := filepath.Dir(ctx.Repo.TreePath)
  393. if treePath == "." {
  394. treePath = "" // the file deleted was in the root, so we return the user to the root directory
  395. }
  396. if len(treePath) > 0 {
  397. // Need to get the latest commit since it changed
  398. commit, err := ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.BranchName)
  399. if err == nil && commit != nil {
  400. // We have the comment, now find what directory we can return the user to
  401. // (must have entries)
  402. treePath = GetClosestParentWithFiles(treePath, commit)
  403. } else {
  404. treePath = "" // otherwise return them to the root of the repo
  405. }
  406. }
  407. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(treePath))
  408. }
  409. }
  410. func renderUploadSettings(ctx *context.Context) {
  411. ctx.Data["RequireDropzone"] = true
  412. ctx.Data["RequireTribute"] = true
  413. ctx.Data["RequireSimpleMDE"] = true
  414. ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
  415. ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
  416. ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
  417. }
  418. // UploadFile render upload file page
  419. func UploadFile(ctx *context.Context) {
  420. ctx.Data["PageIsUpload"] = true
  421. renderUploadSettings(ctx)
  422. canCommit := renderCommitRights(ctx)
  423. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  424. if treePath != ctx.Repo.TreePath {
  425. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_upload", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  426. return
  427. }
  428. ctx.Repo.TreePath = treePath
  429. treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath)
  430. if len(treeNames) == 0 {
  431. // We must at least have one element for user to input.
  432. treeNames = []string{""}
  433. }
  434. ctx.Data["TreeNames"] = treeNames
  435. ctx.Data["TreePaths"] = treePaths
  436. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  437. ctx.Data["commit_summary"] = ""
  438. ctx.Data["commit_message"] = ""
  439. if canCommit {
  440. ctx.Data["commit_choice"] = frmCommitChoiceDirect
  441. } else {
  442. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  443. }
  444. ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx)
  445. ctx.HTML(200, tplUploadFile)
  446. }
  447. // UploadFilePost response for uploading file
  448. func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
  449. ctx.Data["PageIsUpload"] = true
  450. renderUploadSettings(ctx)
  451. canCommit := renderCommitRights(ctx)
  452. oldBranchName := ctx.Repo.BranchName
  453. branchName := oldBranchName
  454. if form.CommitChoice == frmCommitChoiceNewBranch {
  455. branchName = form.NewBranchName
  456. }
  457. form.TreePath = cleanUploadFileName(form.TreePath)
  458. treeNames, treePaths := getParentTreeFields(form.TreePath)
  459. if len(treeNames) == 0 {
  460. // We must at least have one element for user to input.
  461. treeNames = []string{""}
  462. }
  463. ctx.Data["TreePath"] = form.TreePath
  464. ctx.Data["TreeNames"] = treeNames
  465. ctx.Data["TreePaths"] = treePaths
  466. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/branch/" + branchName
  467. ctx.Data["commit_summary"] = form.CommitSummary
  468. ctx.Data["commit_message"] = form.CommitMessage
  469. ctx.Data["commit_choice"] = form.CommitChoice
  470. ctx.Data["new_branch_name"] = branchName
  471. if ctx.HasError() {
  472. ctx.HTML(200, tplUploadFile)
  473. return
  474. }
  475. if oldBranchName != branchName {
  476. if _, err := repo_module.GetBranch(ctx.Repo.Repository, branchName); err == nil {
  477. ctx.Data["Err_NewBranchName"] = true
  478. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplUploadFile, &form)
  479. return
  480. }
  481. } else if !canCommit {
  482. ctx.Data["Err_NewBranchName"] = true
  483. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  484. ctx.RenderWithErr(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", branchName), tplUploadFile, &form)
  485. return
  486. }
  487. var newTreePath string
  488. for _, part := range treeNames {
  489. newTreePath = path.Join(newTreePath, part)
  490. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath)
  491. if err != nil {
  492. if git.IsErrNotExist(err) {
  493. // Means there is no item with that name, so we're good
  494. break
  495. }
  496. ctx.ServerError("Repo.Commit.GetTreeEntryByPath", err)
  497. return
  498. }
  499. // User can only upload files to a directory.
  500. if !entry.IsDir() {
  501. ctx.Data["Err_TreePath"] = true
  502. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), tplUploadFile, &form)
  503. return
  504. }
  505. }
  506. message := strings.TrimSpace(form.CommitSummary)
  507. if len(message) == 0 {
  508. message = ctx.Tr("repo.editor.upload_files_to_dir", form.TreePath)
  509. }
  510. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  511. if len(form.CommitMessage) > 0 {
  512. message += "\n\n" + form.CommitMessage
  513. }
  514. if err := repofiles.UploadRepoFiles(ctx.Repo.Repository, ctx.User, &repofiles.UploadRepoFileOptions{
  515. LastCommitID: ctx.Repo.CommitID,
  516. OldBranch: oldBranchName,
  517. NewBranch: branchName,
  518. TreePath: form.TreePath,
  519. Message: message,
  520. Files: form.Files,
  521. }); err != nil {
  522. ctx.Data["Err_TreePath"] = true
  523. if models.IsErrLFSFileLocked(err) {
  524. ctx.RenderWithErr(ctx.Tr("repo.editor.upload_file_is_locked", err.(models.ErrLFSFileLocked).Path, err.(models.ErrLFSFileLocked).UserName), tplUploadFile, &form)
  525. } else {
  526. ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), tplUploadFile, &form)
  527. }
  528. return
  529. }
  530. if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) {
  531. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + ctx.Repo.BranchName + "..." + form.NewBranchName)
  532. } else {
  533. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath))
  534. }
  535. }
  536. func cleanUploadFileName(name string) string {
  537. // Rebase the filename
  538. name = strings.Trim(path.Clean("/"+name), " /")
  539. // Git disallows any filenames to have a .git directory in them.
  540. for _, part := range strings.Split(name, "/") {
  541. if strings.ToLower(part) == ".git" {
  542. return ""
  543. }
  544. }
  545. return name
  546. }
  547. // UploadFileToServer upload file to server file dir not git
  548. func UploadFileToServer(ctx *context.Context) {
  549. file, header, err := ctx.Req.FormFile("file")
  550. if err != nil {
  551. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  552. return
  553. }
  554. defer file.Close()
  555. buf := make([]byte, 1024)
  556. n, _ := file.Read(buf)
  557. if n > 0 {
  558. buf = buf[:n]
  559. }
  560. if len(setting.Repository.Upload.AllowedTypes) > 0 {
  561. err = upload.VerifyAllowedContentType(buf, setting.Repository.Upload.AllowedTypes)
  562. if err != nil {
  563. ctx.Error(400, err.Error())
  564. return
  565. }
  566. }
  567. name := cleanUploadFileName(header.Filename)
  568. if len(name) == 0 {
  569. ctx.Error(500, "Upload file name is invalid")
  570. return
  571. }
  572. upload, err := models.NewUpload(name, buf, file)
  573. if err != nil {
  574. ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
  575. return
  576. }
  577. log.Trace("New file uploaded: %s", upload.UUID)
  578. ctx.JSON(200, map[string]string{
  579. "uuid": upload.UUID,
  580. })
  581. }
  582. // RemoveUploadFileFromServer remove file from server file dir
  583. func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) {
  584. if len(form.File) == 0 {
  585. ctx.Status(204)
  586. return
  587. }
  588. if err := models.DeleteUploadByUUID(form.File); err != nil {
  589. ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
  590. return
  591. }
  592. log.Trace("Upload file removed: %s", form.File)
  593. ctx.Status(204)
  594. }
  595. // GetUniquePatchBranchName Gets a unique branch name for a new patch branch
  596. // It will be in the form of <username>-patch-<num> where <num> is the first branch of this format
  597. // that doesn't already exist. If we exceed 1000 tries or an error is thrown, we just return "" so the user has to
  598. // type in the branch name themselves (will be an empty field)
  599. func GetUniquePatchBranchName(ctx *context.Context) string {
  600. prefix := ctx.User.LowerName + "-patch-"
  601. for i := 1; i <= 1000; i++ {
  602. branchName := fmt.Sprintf("%s%d", prefix, i)
  603. if _, err := repo_module.GetBranch(ctx.Repo.Repository, branchName); err != nil {
  604. if git.IsErrBranchNotExist(err) {
  605. return branchName
  606. }
  607. log.Error("GetUniquePatchBranchName: %v", err)
  608. return ""
  609. }
  610. }
  611. return ""
  612. }
  613. // GetClosestParentWithFiles Recursively gets the path of parent in a tree that has files (used when file in a tree is
  614. // deleted). Returns "" for the root if no parents other than the root have files. If the given treePath isn't a
  615. // SubTree or it has no entries, we go up one dir and see if we can return the user to that listing.
  616. func GetClosestParentWithFiles(treePath string, commit *git.Commit) string {
  617. if len(treePath) == 0 || treePath == "." {
  618. return ""
  619. }
  620. // see if the tree has entries
  621. if tree, err := commit.SubTree(treePath); err != nil {
  622. // failed to get tree, going up a dir
  623. return GetClosestParentWithFiles(filepath.Dir(treePath), commit)
  624. } else if entries, err := tree.ListEntries(); err != nil || len(entries) == 0 {
  625. // no files in this dir, going up a dir
  626. return GetClosestParentWithFiles(filepath.Dir(treePath), commit)
  627. }
  628. return treePath
  629. }