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.

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