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.

commit.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. repo_model "code.gitea.io/gitea/models/repo"
  16. user_model "code.gitea.io/gitea/models/user"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/charset"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/gitgraph"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/markup"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/util"
  26. "code.gitea.io/gitea/services/gitdiff"
  27. git_service "code.gitea.io/gitea/services/repository"
  28. )
  29. const (
  30. tplCommits base.TplName = "repo/commits"
  31. tplGraph base.TplName = "repo/graph"
  32. tplGraphDiv base.TplName = "repo/graph/div"
  33. tplCommitPage base.TplName = "repo/commit_page"
  34. )
  35. // RefCommits render commits page
  36. func RefCommits(ctx *context.Context) {
  37. switch {
  38. case len(ctx.Repo.TreePath) == 0:
  39. Commits(ctx)
  40. case ctx.Repo.TreePath == "search":
  41. SearchCommits(ctx)
  42. default:
  43. FileHistory(ctx)
  44. }
  45. }
  46. // Commits render branch's commits
  47. func Commits(ctx *context.Context) {
  48. ctx.Data["PageIsCommits"] = true
  49. if ctx.Repo.Commit == nil {
  50. ctx.NotFound("Commit not found", nil)
  51. return
  52. }
  53. ctx.Data["PageIsViewCode"] = true
  54. commitsCount, err := ctx.Repo.GetCommitsCount()
  55. if err != nil {
  56. ctx.ServerError("GetCommitsCount", err)
  57. return
  58. }
  59. page := ctx.FormInt("page")
  60. if page <= 1 {
  61. page = 1
  62. }
  63. pageSize := ctx.FormInt("limit")
  64. if pageSize <= 0 {
  65. pageSize = setting.Git.CommitsRangeSize
  66. }
  67. // Both `git log branchName` and `git log commitId` work.
  68. commits, err := ctx.Repo.Commit.CommitsByRange(page, pageSize, "")
  69. if err != nil {
  70. ctx.ServerError("CommitsByRange", err)
  71. return
  72. }
  73. ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository)
  74. ctx.Data["Username"] = ctx.Repo.Owner.Name
  75. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  76. ctx.Data["CommitCount"] = commitsCount
  77. pager := context.NewPagination(int(commitsCount), pageSize, page, 5)
  78. pager.SetDefaultParams(ctx)
  79. ctx.Data["Page"] = pager
  80. ctx.HTML(http.StatusOK, tplCommits)
  81. }
  82. // Graph render commit graph - show commits from all branches.
  83. func Graph(ctx *context.Context) {
  84. ctx.Data["Title"] = ctx.Tr("repo.commit_graph")
  85. ctx.Data["PageIsCommits"] = true
  86. ctx.Data["PageIsViewCode"] = true
  87. mode := strings.ToLower(ctx.FormTrim("mode"))
  88. if mode != "monochrome" {
  89. mode = "color"
  90. }
  91. ctx.Data["Mode"] = mode
  92. hidePRRefs := ctx.FormBool("hide-pr-refs")
  93. ctx.Data["HidePRRefs"] = hidePRRefs
  94. branches := ctx.FormStrings("branch")
  95. realBranches := make([]string, len(branches))
  96. copy(realBranches, branches)
  97. for i, branch := range realBranches {
  98. if strings.HasPrefix(branch, "--") {
  99. realBranches[i] = git.BranchPrefix + branch
  100. }
  101. }
  102. ctx.Data["SelectedBranches"] = realBranches
  103. files := ctx.FormStrings("file")
  104. commitsCount, err := ctx.Repo.GetCommitsCount()
  105. if err != nil {
  106. ctx.ServerError("GetCommitsCount", err)
  107. return
  108. }
  109. graphCommitsCount, err := ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files)
  110. if err != nil {
  111. 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)
  112. realBranches = []string{}
  113. branches = []string{}
  114. graphCommitsCount, err = ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files)
  115. if err != nil {
  116. ctx.ServerError("GetCommitGraphsCount", err)
  117. return
  118. }
  119. }
  120. page := ctx.FormInt("page")
  121. graph, err := gitgraph.GetCommitGraph(ctx.Repo.GitRepo, page, 0, hidePRRefs, realBranches, files)
  122. if err != nil {
  123. ctx.ServerError("GetCommitGraph", err)
  124. return
  125. }
  126. if err := graph.LoadAndProcessCommits(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil {
  127. ctx.ServerError("LoadAndProcessCommits", err)
  128. return
  129. }
  130. ctx.Data["Graph"] = graph
  131. gitRefs, err := ctx.Repo.GitRepo.GetRefs()
  132. if err != nil {
  133. ctx.ServerError("GitRepo.GetRefs", err)
  134. return
  135. }
  136. ctx.Data["AllRefs"] = gitRefs
  137. ctx.Data["Username"] = ctx.Repo.Owner.Name
  138. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  139. ctx.Data["CommitCount"] = commitsCount
  140. paginator := context.NewPagination(int(graphCommitsCount), setting.UI.GraphMaxCommitNum, page, 5)
  141. paginator.AddParam(ctx, "mode", "Mode")
  142. paginator.AddParam(ctx, "hide-pr-refs", "HidePRRefs")
  143. for _, branch := range branches {
  144. paginator.AddParamString("branch", branch)
  145. }
  146. for _, file := range files {
  147. paginator.AddParamString("file", file)
  148. }
  149. ctx.Data["Page"] = paginator
  150. if ctx.FormBool("div-only") {
  151. ctx.HTML(http.StatusOK, tplGraphDiv)
  152. return
  153. }
  154. ctx.HTML(http.StatusOK, tplGraph)
  155. }
  156. // SearchCommits render commits filtered by keyword
  157. func SearchCommits(ctx *context.Context) {
  158. ctx.Data["PageIsCommits"] = true
  159. ctx.Data["PageIsViewCode"] = true
  160. query := ctx.FormTrim("q")
  161. if len(query) == 0 {
  162. ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchNameSubURL())
  163. return
  164. }
  165. all := ctx.FormBool("all")
  166. opts := git.NewSearchCommitsOptions(query, all)
  167. commits, err := ctx.Repo.Commit.SearchCommits(opts)
  168. if err != nil {
  169. ctx.ServerError("SearchCommits", err)
  170. return
  171. }
  172. ctx.Data["CommitCount"] = len(commits)
  173. ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository)
  174. ctx.Data["Keyword"] = query
  175. if all {
  176. ctx.Data["All"] = "checked"
  177. }
  178. ctx.Data["Username"] = ctx.Repo.Owner.Name
  179. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  180. ctx.HTML(http.StatusOK, tplCommits)
  181. }
  182. // FileHistory show a file's reversions
  183. func FileHistory(ctx *context.Context) {
  184. ctx.Data["IsRepoToolbarCommits"] = true
  185. fileName := ctx.Repo.TreePath
  186. if len(fileName) == 0 {
  187. Commits(ctx)
  188. return
  189. }
  190. commitsCount, err := ctx.Repo.GitRepo.FileCommitsCount(ctx.Repo.RefName, fileName)
  191. if err != nil {
  192. ctx.ServerError("FileCommitsCount", err)
  193. return
  194. } else if commitsCount == 0 {
  195. ctx.NotFound("FileCommitsCount", nil)
  196. return
  197. }
  198. page := ctx.FormInt("page")
  199. if page <= 1 {
  200. page = 1
  201. }
  202. commits, err := ctx.Repo.GitRepo.CommitsByFileAndRange(
  203. git.CommitsByFileAndRangeOptions{
  204. Revision: ctx.Repo.RefName,
  205. File: fileName,
  206. Page: page,
  207. })
  208. if err != nil {
  209. ctx.ServerError("CommitsByFileAndRange", err)
  210. return
  211. }
  212. ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository)
  213. ctx.Data["Username"] = ctx.Repo.Owner.Name
  214. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  215. ctx.Data["FileName"] = fileName
  216. ctx.Data["CommitCount"] = commitsCount
  217. pager := context.NewPagination(int(commitsCount), setting.Git.CommitsRangeSize, page, 5)
  218. pager.SetDefaultParams(ctx)
  219. ctx.Data["Page"] = pager
  220. ctx.HTML(http.StatusOK, tplCommits)
  221. }
  222. func LoadBranchesAndTags(ctx *context.Context) {
  223. response, err := git_service.LoadBranchesAndTags(ctx, ctx.Repo, ctx.Params("sha"))
  224. if err == nil {
  225. ctx.JSON(http.StatusOK, response)
  226. return
  227. }
  228. ctx.NotFoundOrServerError(fmt.Sprintf("could not load branches and tags the commit %s belongs to", ctx.Params("sha")), git.IsErrNotExist, err)
  229. }
  230. // Diff show different from current commit to previous commit
  231. func Diff(ctx *context.Context) {
  232. ctx.Data["PageIsDiff"] = true
  233. userName := ctx.Repo.Owner.Name
  234. repoName := ctx.Repo.Repository.Name
  235. commitID := ctx.Params(":sha")
  236. var (
  237. gitRepo *git.Repository
  238. err error
  239. )
  240. if ctx.Data["PageIsWiki"] != nil {
  241. gitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.WikiPath())
  242. if err != nil {
  243. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  244. return
  245. }
  246. defer gitRepo.Close()
  247. } else {
  248. gitRepo = ctx.Repo.GitRepo
  249. }
  250. commit, err := gitRepo.GetCommit(commitID)
  251. if err != nil {
  252. if git.IsErrNotExist(err) {
  253. ctx.NotFound("Repo.GitRepo.GetCommit", err)
  254. } else {
  255. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  256. }
  257. return
  258. }
  259. if len(commitID) != git.SHAFullLength {
  260. commitID = commit.ID.String()
  261. }
  262. fileOnly := ctx.FormBool("file-only")
  263. maxLines, maxFiles := setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffFiles
  264. files := ctx.FormStrings("files")
  265. if fileOnly && (len(files) == 2 || len(files) == 1) {
  266. maxLines, maxFiles = -1, -1
  267. }
  268. diff, err := gitdiff.GetDiff(gitRepo, &gitdiff.DiffOptions{
  269. AfterCommitID: commitID,
  270. SkipTo: ctx.FormString("skip-to"),
  271. MaxLines: maxLines,
  272. MaxLineCharacters: setting.Git.MaxGitDiffLineCharacters,
  273. MaxFiles: maxFiles,
  274. WhitespaceBehavior: gitdiff.GetWhitespaceFlag(ctx.Data["WhitespaceBehavior"].(string)),
  275. }, files...)
  276. if err != nil {
  277. ctx.NotFound("GetDiff", err)
  278. return
  279. }
  280. parents := make([]string, commit.ParentCount())
  281. for i := 0; i < commit.ParentCount(); i++ {
  282. sha, err := commit.ParentID(i)
  283. if err != nil {
  284. ctx.NotFound("repo.Diff", err)
  285. return
  286. }
  287. parents[i] = sha.String()
  288. }
  289. ctx.Data["CommitID"] = commitID
  290. ctx.Data["AfterCommitID"] = commitID
  291. ctx.Data["Username"] = userName
  292. ctx.Data["Reponame"] = repoName
  293. var parentCommit *git.Commit
  294. if commit.ParentCount() > 0 {
  295. parentCommit, err = gitRepo.GetCommit(parents[0])
  296. if err != nil {
  297. ctx.NotFound("GetParentCommit", err)
  298. return
  299. }
  300. }
  301. setCompareContext(ctx, parentCommit, commit, userName, repoName)
  302. ctx.Data["Title"] = commit.Summary() + " · " + base.ShortSha(commitID)
  303. ctx.Data["Commit"] = commit
  304. ctx.Data["Diff"] = diff
  305. statuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, commitID, db.ListOptions{ListAll: true})
  306. if err != nil {
  307. log.Error("GetLatestCommitStatus: %v", err)
  308. }
  309. ctx.Data["CommitStatus"] = git_model.CalcCommitStatus(statuses)
  310. ctx.Data["CommitStatuses"] = statuses
  311. verification := asymkey_model.ParseCommitWithSignature(ctx, commit)
  312. ctx.Data["Verification"] = verification
  313. ctx.Data["Author"] = user_model.ValidateCommitWithEmail(ctx, commit)
  314. ctx.Data["Parents"] = parents
  315. ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0
  316. if err := asymkey_model.CalculateTrustStatus(verification, ctx.Repo.Repository.GetTrustModel(), func(user *user_model.User) (bool, error) {
  317. return repo_model.IsOwnerMemberCollaborator(ctx, ctx.Repo.Repository, user.ID)
  318. }, nil); err != nil {
  319. ctx.ServerError("CalculateTrustStatus", err)
  320. return
  321. }
  322. note := &git.Note{}
  323. err = git.GetNote(ctx, ctx.Repo.GitRepo, commitID, note)
  324. if err == nil {
  325. ctx.Data["NoteCommit"] = note.Commit
  326. ctx.Data["NoteAuthor"] = user_model.ValidateCommitWithEmail(ctx, note.Commit)
  327. ctx.Data["NoteRendered"], err = markup.RenderCommitMessage(&markup.RenderContext{
  328. Links: markup.Links{
  329. Base: ctx.Repo.RepoLink,
  330. BranchPath: path.Join("commit", util.PathEscapeSegments(commitID)),
  331. },
  332. Metas: ctx.Repo.Repository.ComposeMetas(),
  333. GitRepo: ctx.Repo.GitRepo,
  334. Ctx: ctx,
  335. }, template.HTMLEscapeString(string(charset.ToUTF8WithFallback(note.Message, charset.ConvertOpts{}))))
  336. if err != nil {
  337. ctx.ServerError("RenderCommitMessage", err)
  338. return
  339. }
  340. }
  341. ctx.Data["BranchName"], err = commit.GetBranchName()
  342. if err != nil {
  343. ctx.ServerError("commit.GetBranchName", err)
  344. return
  345. }
  346. ctx.HTML(http.StatusOK, tplCommitPage)
  347. }
  348. // RawDiff dumps diff results of repository in given commit ID to io.Writer
  349. func RawDiff(ctx *context.Context) {
  350. var gitRepo *git.Repository
  351. if ctx.Data["PageIsWiki"] != nil {
  352. wikiRepo, err := git.OpenRepository(ctx, ctx.Repo.Repository.WikiPath())
  353. if err != nil {
  354. ctx.ServerError("OpenRepository", err)
  355. return
  356. }
  357. defer wikiRepo.Close()
  358. gitRepo = wikiRepo
  359. } else {
  360. gitRepo = ctx.Repo.GitRepo
  361. if gitRepo == nil {
  362. ctx.ServerError("GitRepo not open", fmt.Errorf("no open git repo for '%s'", ctx.Repo.Repository.FullName()))
  363. return
  364. }
  365. }
  366. if err := git.GetRawDiff(
  367. gitRepo,
  368. ctx.Params(":sha"),
  369. git.RawDiffType(ctx.Params(":ext")),
  370. ctx.Resp,
  371. ); err != nil {
  372. if git.IsErrNotExist(err) {
  373. ctx.NotFound("GetRawDiff",
  374. errors.New("commit "+ctx.Params(":sha")+" does not exist."))
  375. return
  376. }
  377. ctx.ServerError("GetRawDiff", err)
  378. return
  379. }
  380. }