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.

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