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

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