gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package repo
  5. import (
  6. "errors"
  7. "fmt"
  8. "html/template"
  9. "net/http"
  10. "path"
  11. "strings"
  12. asymkey_model "code.gitea.io/gitea/models/asymkey"
  13. "code.gitea.io/gitea/models/db"
  14. git_model "code.gitea.io/gitea/models/git"
  15. issues_model "code.gitea.io/gitea/models/issues"
  16. "code.gitea.io/gitea/models/renderhelper"
  17. repo_model "code.gitea.io/gitea/models/repo"
  18. unit_model "code.gitea.io/gitea/models/unit"
  19. user_model "code.gitea.io/gitea/models/user"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/charset"
  22. "code.gitea.io/gitea/modules/fileicon"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/gitrepo"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/markup"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/modules/templates"
  29. "code.gitea.io/gitea/modules/util"
  30. asymkey_service "code.gitea.io/gitea/services/asymkey"
  31. "code.gitea.io/gitea/services/context"
  32. git_service "code.gitea.io/gitea/services/git"
  33. "code.gitea.io/gitea/services/gitdiff"
  34. repo_service "code.gitea.io/gitea/services/repository"
  35. "code.gitea.io/gitea/services/repository/gitgraph"
  36. )
  37. const (
  38. tplCommits templates.TplName = "repo/commits"
  39. tplGraph templates.TplName = "repo/graph"
  40. tplGraphDiv templates.TplName = "repo/graph/div"
  41. tplCommitPage templates.TplName = "repo/commit_page"
  42. )
  43. // RefCommits render commits page
  44. func RefCommits(ctx *context.Context) {
  45. switch {
  46. case len(ctx.Repo.TreePath) == 0:
  47. Commits(ctx)
  48. case ctx.Repo.TreePath == "search":
  49. SearchCommits(ctx)
  50. default:
  51. FileHistory(ctx)
  52. }
  53. }
  54. // Commits render branch's commits
  55. func Commits(ctx *context.Context) {
  56. ctx.Data["PageIsCommits"] = true
  57. if ctx.Repo.Commit == nil {
  58. ctx.NotFound(nil)
  59. return
  60. }
  61. ctx.Data["PageIsViewCode"] = true
  62. commitsCount := ctx.Repo.CommitsCount
  63. page := max(ctx.FormInt("page"), 1)
  64. pageSize := ctx.FormInt("limit")
  65. if pageSize <= 0 {
  66. pageSize = setting.Git.CommitsRangeSize
  67. }
  68. // Both `git log branchName` and `git log commitId` work.
  69. commits, err := ctx.Repo.Commit.CommitsByRange(page, pageSize, "", "", "")
  70. if err != nil {
  71. ctx.ServerError("CommitsByRange", err)
  72. return
  73. }
  74. ctx.Data["Commits"], err = processGitCommits(ctx, commits)
  75. if err != nil {
  76. ctx.ServerError("processGitCommits", err)
  77. return
  78. }
  79. commitIDs := make([]string, 0, len(commits))
  80. for _, c := range commits {
  81. commitIDs = append(commitIDs, c.ID.String())
  82. }
  83. commitsTagsMap, err := repo_model.FindTagsByCommitIDs(ctx, ctx.Repo.Repository.ID, commitIDs...)
  84. if err != nil {
  85. log.Error("FindTagsByCommitIDs: %v", err)
  86. ctx.Flash.Error(ctx.Tr("internal_error_skipped", "FindTagsByCommitIDs"))
  87. } else {
  88. ctx.Data["CommitsTagsMap"] = commitsTagsMap
  89. }
  90. ctx.Data["Username"] = ctx.Repo.Owner.Name
  91. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  92. ctx.Data["CommitCount"] = commitsCount
  93. pager := context.NewPagination(int(commitsCount), pageSize, page, 5)
  94. pager.AddParamFromRequest(ctx.Req)
  95. ctx.Data["Page"] = pager
  96. ctx.HTML(http.StatusOK, tplCommits)
  97. }
  98. // Graph render commit graph - show commits from all branches.
  99. func Graph(ctx *context.Context) {
  100. ctx.Data["Title"] = ctx.Tr("repo.commit_graph")
  101. ctx.Data["PageIsCommits"] = true
  102. ctx.Data["PageIsViewCode"] = true
  103. mode := strings.ToLower(ctx.FormTrim("mode"))
  104. if mode != "monochrome" {
  105. mode = "color"
  106. }
  107. ctx.Data["Mode"] = mode
  108. hidePRRefs := ctx.FormBool("hide-pr-refs")
  109. ctx.Data["HidePRRefs"] = hidePRRefs
  110. branches := ctx.FormStrings("branch")
  111. realBranches := make([]string, len(branches))
  112. copy(realBranches, branches)
  113. for i, branch := range realBranches {
  114. if strings.HasPrefix(branch, "--") {
  115. realBranches[i] = git.BranchPrefix + branch
  116. }
  117. }
  118. ctx.Data["SelectedBranches"] = realBranches
  119. files := ctx.FormStrings("file")
  120. graphCommitsCount, err := ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files)
  121. if err != nil {
  122. log.Warn("GetCommitGraphsCount error for generate graph exclude prs: %t branches: %s in %-v, Will Ignore branches and try again. Underlying Error: %v", hidePRRefs, branches, ctx.Repo.Repository, err)
  123. realBranches = []string{}
  124. graphCommitsCount, err = ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files)
  125. if err != nil {
  126. ctx.ServerError("GetCommitGraphsCount", err)
  127. return
  128. }
  129. }
  130. page := ctx.FormInt("page")
  131. graph, err := gitgraph.GetCommitGraph(ctx.Repo.GitRepo, page, 0, hidePRRefs, realBranches, files)
  132. if err != nil {
  133. ctx.ServerError("GetCommitGraph", err)
  134. return
  135. }
  136. if err := graph.LoadAndProcessCommits(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil {
  137. ctx.ServerError("LoadAndProcessCommits", err)
  138. return
  139. }
  140. ctx.Data["Graph"] = graph
  141. gitRefs, err := ctx.Repo.GitRepo.GetRefs()
  142. if err != nil {
  143. ctx.ServerError("GitRepo.GetRefs", err)
  144. return
  145. }
  146. ctx.Data["AllRefs"] = gitRefs
  147. ctx.Data["Username"] = ctx.Repo.Owner.Name
  148. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  149. divOnly := ctx.FormBool("div-only")
  150. queryParams := ctx.Req.URL.Query()
  151. queryParams.Del("div-only")
  152. paginator := context.NewPagination(int(graphCommitsCount), setting.UI.GraphMaxCommitNum, page, 5)
  153. paginator.AddParamFromQuery(queryParams)
  154. ctx.Data["Page"] = paginator
  155. if divOnly {
  156. ctx.HTML(http.StatusOK, tplGraphDiv)
  157. return
  158. }
  159. ctx.HTML(http.StatusOK, tplGraph)
  160. }
  161. // SearchCommits render commits filtered by keyword
  162. func SearchCommits(ctx *context.Context) {
  163. ctx.Data["PageIsCommits"] = true
  164. ctx.Data["PageIsViewCode"] = true
  165. query := ctx.FormTrim("q")
  166. if len(query) == 0 {
  167. ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.RefTypeNameSubURL())
  168. return
  169. }
  170. all := ctx.FormBool("all")
  171. opts := git.NewSearchCommitsOptions(query, all)
  172. commits, err := ctx.Repo.Commit.SearchCommits(opts)
  173. if err != nil {
  174. ctx.ServerError("SearchCommits", err)
  175. return
  176. }
  177. ctx.Data["CommitCount"] = len(commits)
  178. ctx.Data["Commits"], err = processGitCommits(ctx, commits)
  179. if err != nil {
  180. ctx.ServerError("processGitCommits", err)
  181. return
  182. }
  183. ctx.Data["Keyword"] = query
  184. if all {
  185. ctx.Data["All"] = true
  186. }
  187. ctx.Data["Username"] = ctx.Repo.Owner.Name
  188. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  189. ctx.HTML(http.StatusOK, tplCommits)
  190. }
  191. // FileHistory show a file's reversions
  192. func FileHistory(ctx *context.Context) {
  193. if ctx.Repo.TreePath == "" {
  194. Commits(ctx)
  195. return
  196. }
  197. commitsCount, err := ctx.Repo.GitRepo.FileCommitsCount(ctx.Repo.RefFullName.ShortName(), ctx.Repo.TreePath)
  198. if err != nil {
  199. ctx.ServerError("FileCommitsCount", err)
  200. return
  201. } else if commitsCount == 0 {
  202. ctx.NotFound(nil)
  203. return
  204. }
  205. page := max(ctx.FormInt("page"), 1)
  206. commits, err := ctx.Repo.GitRepo.CommitsByFileAndRange(
  207. git.CommitsByFileAndRangeOptions{
  208. Revision: ctx.Repo.RefFullName.ShortName(), // FIXME: legacy code used ShortName
  209. File: ctx.Repo.TreePath,
  210. Page: page,
  211. })
  212. if err != nil {
  213. ctx.ServerError("CommitsByFileAndRange", err)
  214. return
  215. }
  216. ctx.Data["Commits"], err = processGitCommits(ctx, commits)
  217. if err != nil {
  218. ctx.ServerError("processGitCommits", err)
  219. return
  220. }
  221. ctx.Data["Username"] = ctx.Repo.Owner.Name
  222. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  223. ctx.Data["FileTreePath"] = ctx.Repo.TreePath
  224. ctx.Data["CommitCount"] = commitsCount
  225. pager := context.NewPagination(int(commitsCount), setting.Git.CommitsRangeSize, page, 5)
  226. pager.AddParamFromRequest(ctx.Req)
  227. ctx.Data["Page"] = pager
  228. ctx.HTML(http.StatusOK, tplCommits)
  229. }
  230. func LoadBranchesAndTags(ctx *context.Context) {
  231. response, err := repo_service.LoadBranchesAndTags(ctx, ctx.Repo, ctx.PathParam("sha"))
  232. if err == nil {
  233. ctx.JSON(http.StatusOK, response)
  234. return
  235. }
  236. ctx.NotFoundOrServerError(fmt.Sprintf("could not load branches and tags the commit %s belongs to", ctx.PathParam("sha")), git.IsErrNotExist, err)
  237. }
  238. // Diff show different from current commit to previous commit
  239. func Diff(ctx *context.Context) {
  240. ctx.Data["PageIsDiff"] = true
  241. userName := ctx.Repo.Owner.Name
  242. repoName := ctx.Repo.Repository.Name
  243. commitID := ctx.PathParam("sha")
  244. var (
  245. gitRepo *git.Repository
  246. err error
  247. )
  248. if ctx.Data["PageIsWiki"] != nil {
  249. gitRepo, err = gitrepo.OpenRepository(ctx, ctx.Repo.Repository.WikiStorageRepo())
  250. if err != nil {
  251. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  252. return
  253. }
  254. defer gitRepo.Close()
  255. } else {
  256. gitRepo = ctx.Repo.GitRepo
  257. }
  258. commit, err := gitRepo.GetCommit(commitID)
  259. if err != nil {
  260. if git.IsErrNotExist(err) {
  261. ctx.NotFound(err)
  262. } else {
  263. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  264. }
  265. return
  266. }
  267. if len(commitID) != commit.ID.Type().FullLength() {
  268. commitID = commit.ID.String()
  269. }
  270. fileOnly := ctx.FormBool("file-only")
  271. maxLines, maxFiles := setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffFiles
  272. files := ctx.FormStrings("files")
  273. if fileOnly && (len(files) == 2 || len(files) == 1) {
  274. maxLines, maxFiles = -1, -1
  275. }
  276. diff, err := gitdiff.GetDiffForRender(ctx, ctx.Repo.RepoLink, gitRepo, &gitdiff.DiffOptions{
  277. AfterCommitID: commitID,
  278. SkipTo: ctx.FormString("skip-to"),
  279. MaxLines: maxLines,
  280. MaxLineCharacters: setting.Git.MaxGitDiffLineCharacters,
  281. MaxFiles: maxFiles,
  282. WhitespaceBehavior: gitdiff.GetWhitespaceFlag(ctx.Data["WhitespaceBehavior"].(string)),
  283. }, files...)
  284. if err != nil {
  285. ctx.NotFound(err)
  286. return
  287. }
  288. diffShortStat, err := gitdiff.GetDiffShortStat(gitRepo, "", commitID)
  289. if err != nil {
  290. ctx.ServerError("GetDiffShortStat", err)
  291. return
  292. }
  293. ctx.Data["DiffShortStat"] = diffShortStat
  294. parents := make([]string, commit.ParentCount())
  295. for i := 0; i < commit.ParentCount(); i++ {
  296. sha, err := commit.ParentID(i)
  297. if err != nil {
  298. ctx.NotFound(err)
  299. return
  300. }
  301. parents[i] = sha.String()
  302. }
  303. ctx.Data["CommitID"] = commitID
  304. ctx.Data["AfterCommitID"] = commitID
  305. ctx.Data["Username"] = userName
  306. ctx.Data["Reponame"] = repoName
  307. var parentCommit *git.Commit
  308. var parentCommitID string
  309. if commit.ParentCount() > 0 {
  310. parentCommit, err = gitRepo.GetCommit(parents[0])
  311. if err != nil {
  312. ctx.NotFound(err)
  313. return
  314. }
  315. parentCommitID = parentCommit.ID.String()
  316. }
  317. setCompareContext(ctx, parentCommit, commit, userName, repoName)
  318. ctx.Data["Title"] = commit.Summary() + " · " + base.ShortSha(commitID)
  319. ctx.Data["Commit"] = commit
  320. ctx.Data["Diff"] = diff
  321. if !fileOnly {
  322. diffTree, err := gitdiff.GetDiffTree(ctx, gitRepo, false, parentCommitID, commitID)
  323. if err != nil {
  324. ctx.ServerError("GetDiffTree", err)
  325. return
  326. }
  327. renderedIconPool := fileicon.NewRenderedIconPool()
  328. ctx.PageData["DiffFileTree"] = transformDiffTreeForWeb(renderedIconPool, diffTree, nil)
  329. ctx.PageData["FolderIcon"] = fileicon.RenderEntryIconHTML(renderedIconPool, fileicon.EntryInfoFolder())
  330. ctx.PageData["FolderOpenIcon"] = fileicon.RenderEntryIconHTML(renderedIconPool, fileicon.EntryInfoFolderOpen())
  331. ctx.Data["FileIconPoolHTML"] = renderedIconPool.RenderToHTML()
  332. }
  333. statuses, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, commitID, db.ListOptionsAll)
  334. if err != nil {
  335. log.Error("GetLatestCommitStatus: %v", err)
  336. }
  337. if !ctx.Repo.CanRead(unit_model.TypeActions) {
  338. git_model.CommitStatusesHideActionsURL(ctx, statuses)
  339. }
  340. ctx.Data["CommitStatus"] = git_model.CalcCommitStatus(statuses)
  341. ctx.Data["CommitStatuses"] = statuses
  342. verification := asymkey_service.ParseCommitWithSignature(ctx, commit)
  343. ctx.Data["Verification"] = verification
  344. ctx.Data["Author"] = user_model.ValidateCommitWithEmail(ctx, commit)
  345. ctx.Data["Parents"] = parents
  346. ctx.Data["DiffNotAvailable"] = diffShortStat.NumFiles == 0
  347. if err := asymkey_model.CalculateTrustStatus(verification, ctx.Repo.Repository.GetTrustModel(), func(user *user_model.User) (bool, error) {
  348. return repo_model.IsOwnerMemberCollaborator(ctx, ctx.Repo.Repository, user.ID)
  349. }, nil); err != nil {
  350. ctx.ServerError("CalculateTrustStatus", err)
  351. return
  352. }
  353. note := &git.Note{}
  354. err = git.GetNote(ctx, ctx.Repo.GitRepo, commitID, note)
  355. if err == nil {
  356. ctx.Data["NoteCommit"] = note.Commit
  357. ctx.Data["NoteAuthor"] = user_model.ValidateCommitWithEmail(ctx, note.Commit)
  358. rctx := renderhelper.NewRenderContextRepoComment(ctx, ctx.Repo.Repository, renderhelper.RepoCommentOptions{CurrentRefPath: path.Join("commit", util.PathEscapeSegments(commitID))})
  359. ctx.Data["NoteRendered"], err = markup.PostProcessCommitMessage(rctx, template.HTMLEscapeString(string(charset.ToUTF8WithFallback(note.Message, charset.ConvertOpts{}))))
  360. if err != nil {
  361. ctx.ServerError("PostProcessCommitMessage", err)
  362. return
  363. }
  364. }
  365. pr, _ := issues_model.GetPullRequestByMergedCommit(ctx, ctx.Repo.Repository.ID, commitID)
  366. if pr != nil {
  367. ctx.Data["MergedPRIssueNumber"] = pr.Index
  368. }
  369. ctx.HTML(http.StatusOK, tplCommitPage)
  370. }
  371. // RawDiff dumps diff results of repository in given commit ID to io.Writer
  372. func RawDiff(ctx *context.Context) {
  373. var gitRepo *git.Repository
  374. if ctx.Data["PageIsWiki"] != nil {
  375. wikiRepo, err := gitrepo.OpenRepository(ctx, ctx.Repo.Repository.WikiStorageRepo())
  376. if err != nil {
  377. ctx.ServerError("OpenRepository", err)
  378. return
  379. }
  380. defer wikiRepo.Close()
  381. gitRepo = wikiRepo
  382. } else {
  383. gitRepo = ctx.Repo.GitRepo
  384. if gitRepo == nil {
  385. ctx.ServerError("GitRepo not open", fmt.Errorf("no open git repo for '%s'", ctx.Repo.Repository.FullName()))
  386. return
  387. }
  388. }
  389. if err := git.GetRawDiff(
  390. gitRepo,
  391. ctx.PathParam("sha"),
  392. git.RawDiffType(ctx.PathParam("ext")),
  393. ctx.Resp,
  394. ); err != nil {
  395. if git.IsErrNotExist(err) {
  396. ctx.NotFound(errors.New("commit " + ctx.PathParam("sha") + " does not exist."))
  397. return
  398. }
  399. ctx.ServerError("GetRawDiff", err)
  400. return
  401. }
  402. }
  403. func processGitCommits(ctx *context.Context, gitCommits []*git.Commit) ([]*git_model.SignCommitWithStatuses, error) {
  404. commits, err := git_service.ConvertFromGitCommit(ctx, gitCommits, ctx.Repo.Repository)
  405. if err != nil {
  406. return nil, err
  407. }
  408. if !ctx.Repo.CanRead(unit_model.TypeActions) {
  409. for _, commit := range commits {
  410. if commit.Status == nil {
  411. continue
  412. }
  413. commit.Status.HideActionsURL(ctx)
  414. git_model.CommitStatusesHideActionsURL(ctx, commit.Statuses)
  415. }
  416. }
  417. return commits, nil
  418. }