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

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