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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/upload"
  21. "code.gitea.io/gitea/modules/util"
  22. "code.gitea.io/gitea/routers/utils"
  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. canCommit, err := ctx.Repo.CanCommitToBranch(ctx.User)
  34. if err != nil {
  35. log.Error("CanCommitToBranch: %v", err)
  36. }
  37. ctx.Data["CanCommitToBranch"] = canCommit
  38. return canCommit
  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) || models.IsErrMergePushOutOfDate(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 if models.IsErrPushRejected(err) {
  240. errPushRej := err.(models.ErrPushRejected)
  241. if len(errPushRej.Message) == 0 {
  242. ctx.RenderWithErr(ctx.Tr("repo.editor.push_rejected_no_message"), tplEditFile, &form)
  243. } else {
  244. ctx.RenderWithErr(ctx.Tr("repo.editor.push_rejected", utils.SanitizeFlashErrorString(errPushRej.Message)), tplEditFile, &form)
  245. }
  246. } else {
  247. ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, utils.SanitizeFlashErrorString(err.Error())), tplEditFile, &form)
  248. }
  249. }
  250. if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) {
  251. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + ctx.Repo.BranchName + "..." + form.NewBranchName)
  252. } else {
  253. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath))
  254. }
  255. }
  256. // EditFilePost response for editing file
  257. func EditFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  258. editFilePost(ctx, form, false)
  259. }
  260. // NewFilePost response for creating file
  261. func NewFilePost(ctx *context.Context, form auth.EditRepoFileForm) {
  262. editFilePost(ctx, form, true)
  263. }
  264. // DiffPreviewPost render preview diff page
  265. func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) {
  266. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  267. if len(treePath) == 0 {
  268. ctx.Error(500, "file name to diff is invalid")
  269. return
  270. }
  271. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
  272. if err != nil {
  273. ctx.Error(500, "GetTreeEntryByPath: "+err.Error())
  274. return
  275. } else if entry.IsDir() {
  276. ctx.Error(422)
  277. return
  278. }
  279. diff, err := repofiles.GetDiffPreview(ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content)
  280. if err != nil {
  281. ctx.Error(500, "GetDiffPreview: "+err.Error())
  282. return
  283. }
  284. if diff.NumFiles() == 0 {
  285. ctx.PlainText(200, []byte(ctx.Tr("repo.editor.no_changes_to_show")))
  286. return
  287. }
  288. ctx.Data["File"] = diff.Files[0]
  289. ctx.HTML(200, tplEditDiffPreview)
  290. }
  291. // DeleteFile render delete file page
  292. func DeleteFile(ctx *context.Context) {
  293. ctx.Data["PageIsDelete"] = true
  294. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  295. treePath := cleanUploadFileName(ctx.Repo.TreePath)
  296. if treePath != ctx.Repo.TreePath {
  297. ctx.Redirect(path.Join(ctx.Repo.RepoLink, "_delete", util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(treePath)))
  298. return
  299. }
  300. ctx.Data["TreePath"] = treePath
  301. canCommit := renderCommitRights(ctx)
  302. ctx.Data["commit_summary"] = ""
  303. ctx.Data["commit_message"] = ""
  304. ctx.Data["last_commit"] = ctx.Repo.CommitID
  305. if canCommit {
  306. ctx.Data["commit_choice"] = frmCommitChoiceDirect
  307. } else {
  308. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  309. }
  310. ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx)
  311. ctx.HTML(200, tplDeleteFile)
  312. }
  313. // DeleteFilePost response for deleting file
  314. func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
  315. canCommit := renderCommitRights(ctx)
  316. branchName := ctx.Repo.BranchName
  317. if form.CommitChoice == frmCommitChoiceNewBranch {
  318. branchName = form.NewBranchName
  319. }
  320. ctx.Data["PageIsDelete"] = true
  321. ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  322. ctx.Data["TreePath"] = ctx.Repo.TreePath
  323. ctx.Data["commit_summary"] = form.CommitSummary
  324. ctx.Data["commit_message"] = form.CommitMessage
  325. ctx.Data["commit_choice"] = form.CommitChoice
  326. ctx.Data["new_branch_name"] = form.NewBranchName
  327. ctx.Data["last_commit"] = ctx.Repo.CommitID
  328. if ctx.HasError() {
  329. ctx.HTML(200, tplDeleteFile)
  330. return
  331. }
  332. if branchName == ctx.Repo.BranchName && !canCommit {
  333. ctx.Data["Err_NewBranchName"] = true
  334. ctx.Data["commit_choice"] = frmCommitChoiceNewBranch
  335. ctx.RenderWithErr(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", branchName), tplDeleteFile, &form)
  336. return
  337. }
  338. message := strings.TrimSpace(form.CommitSummary)
  339. if len(message) == 0 {
  340. message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
  341. }
  342. form.CommitMessage = strings.TrimSpace(form.CommitMessage)
  343. if len(form.CommitMessage) > 0 {
  344. message += "\n\n" + form.CommitMessage
  345. }
  346. if _, err := repofiles.DeleteRepoFile(ctx.Repo.Repository, ctx.User, &repofiles.DeleteRepoFileOptions{
  347. LastCommitID: form.LastCommit,
  348. OldBranch: ctx.Repo.BranchName,
  349. NewBranch: branchName,
  350. TreePath: ctx.Repo.TreePath,
  351. Message: message,
  352. }); err != nil {
  353. // This is where we handle all the errors thrown by repofiles.DeleteRepoFile
  354. if git.IsErrNotExist(err) || models.IsErrRepoFileDoesNotExist(err) {
  355. ctx.RenderWithErr(ctx.Tr("repo.editor.file_deleting_no_longer_exists", ctx.Repo.TreePath), tplDeleteFile, &form)
  356. } else if models.IsErrFilenameInvalid(err) {
  357. ctx.Data["Err_TreePath"] = true
  358. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_invalid", ctx.Repo.TreePath), tplDeleteFile, &form)
  359. } else if models.IsErrFilePathInvalid(err) {
  360. ctx.Data["Err_TreePath"] = true
  361. if fileErr, ok := err.(models.ErrFilePathInvalid); ok {
  362. switch fileErr.Type {
  363. case git.EntryModeSymlink:
  364. ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", fileErr.Path), tplDeleteFile, &form)
  365. case git.EntryModeTree:
  366. ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplDeleteFile, &form)
  367. case git.EntryModeBlob:
  368. ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplDeleteFile, &form)
  369. default:
  370. ctx.ServerError("DeleteRepoFile", err)
  371. }
  372. } else {
  373. ctx.ServerError("DeleteRepoFile", err)
  374. }
  375. } else if git.IsErrBranchNotExist(err) {
  376. // For when a user deletes a file to a branch that no longer exists
  377. if branchErr, ok := err.(git.ErrBranchNotExist); ok {
  378. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplDeleteFile, &form)
  379. } else {
  380. ctx.Error(500, err.Error())
  381. }
  382. } else if models.IsErrBranchAlreadyExists(err) {
  383. // For when a user specifies a new branch that already exists
  384. if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
  385. ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplDeleteFile, &form)
  386. } else {
  387. ctx.Error(500, err.Error())
  388. }
  389. } else if models.IsErrCommitIDDoesNotMatch(err) || models.IsErrMergePushOutOfDate(err) {
  390. ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_deleting", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplDeleteFile, &form)
  391. } else if models.IsErrPushRejected(err) {
  392. errPushRej := err.(models.ErrPushRejected)
  393. if len(errPushRej.Message) == 0 {
  394. ctx.RenderWithErr(ctx.Tr("repo.editor.push_rejected_no_message"), tplDeleteFile, &form)
  395. } else {
  396. ctx.RenderWithErr(ctx.Tr("repo.editor.push_rejected", utils.SanitizeFlashErrorString(errPushRej.Message)), tplDeleteFile, &form)
  397. }
  398. } else {
  399. ctx.ServerError("DeleteRepoFile", err)
  400. }
  401. }
  402. ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath))
  403. if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) {
  404. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + ctx.Repo.BranchName + "..." + form.NewBranchName)
  405. } else {
  406. treePath := filepath.Dir(ctx.Repo.TreePath)
  407. if treePath == "." {
  408. treePath = "" // the file deleted was in the root, so we return the user to the root directory
  409. }
  410. if len(treePath) > 0 {
  411. // Need to get the latest commit since it changed
  412. commit, err := ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.BranchName)
  413. if err == nil && commit != nil {
  414. // We have the comment, now find what directory we can return the user to
  415. // (must have entries)
  416. treePath = GetClosestParentWithFiles(treePath, commit)
  417. } else {
  418. treePath = "" // otherwise return them to the root of the repo
  419. }
  420. }
  421. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(treePath))
  422. }
  423. }
  424. func renderUploadSettings(ctx *context.Context) {
  425. ctx.Data["RequireDropzone"] = true
  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 := ctx.Repo.Repository.GetBranch(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 := ctx.Repo.Repository.GetBranch(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. }