選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

commit.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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/git"
  20. "code.gitea.io/gitea/modules/gitgraph"
  21. "code.gitea.io/gitea/modules/gitrepo"
  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/context"
  27. "code.gitea.io/gitea/services/gitdiff"
  28. git_service "code.gitea.io/gitea/services/repository"
  29. )
  30. const (
  31. tplCommits base.TplName = "repo/commits"
  32. tplGraph base.TplName = "repo/graph"
  33. tplGraphDiv base.TplName = "repo/graph/div"
  34. tplCommitPage base.TplName = "repo/commit_page"
  35. )
  36. // RefCommits render commits page
  37. func RefCommits(ctx *context.Context) {
  38. switch {
  39. case len(ctx.Repo.TreePath) == 0:
  40. Commits(ctx)
  41. case ctx.Repo.TreePath == "search":
  42. SearchCommits(ctx)
  43. default:
  44. FileHistory(ctx)
  45. }
  46. }
  47. // Commits render branch's commits
  48. func Commits(ctx *context.Context) {
  49. ctx.Data["PageIsCommits"] = true
  50. if ctx.Repo.Commit == nil {
  51. ctx.NotFound("Commit not found", nil)
  52. return
  53. }
  54. ctx.Data["PageIsViewCode"] = true
  55. commitsCount, err := ctx.Repo.GetCommitsCount()
  56. if err != nil {
  57. ctx.ServerError("GetCommitsCount", err)
  58. return
  59. }
  60. page := ctx.FormInt("page")
  61. if page <= 1 {
  62. page = 1
  63. }
  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"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository)
  75. ctx.Data["Username"] = ctx.Repo.Owner.Name
  76. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  77. ctx.Data["CommitCount"] = commitsCount
  78. pager := context.NewPagination(int(commitsCount), pageSize, page, 5)
  79. pager.SetDefaultParams(ctx)
  80. ctx.Data["Page"] = pager
  81. ctx.HTML(http.StatusOK, tplCommits)
  82. }
  83. // Graph render commit graph - show commits from all branches.
  84. func Graph(ctx *context.Context) {
  85. ctx.Data["Title"] = ctx.Tr("repo.commit_graph")
  86. ctx.Data["PageIsCommits"] = true
  87. ctx.Data["PageIsViewCode"] = true
  88. mode := strings.ToLower(ctx.FormTrim("mode"))
  89. if mode != "monochrome" {
  90. mode = "color"
  91. }
  92. ctx.Data["Mode"] = mode
  93. hidePRRefs := ctx.FormBool("hide-pr-refs")
  94. ctx.Data["HidePRRefs"] = hidePRRefs
  95. branches := ctx.FormStrings("branch")
  96. realBranches := make([]string, len(branches))
  97. copy(realBranches, branches)
  98. for i, branch := range realBranches {
  99. if strings.HasPrefix(branch, "--") {
  100. realBranches[i] = git.BranchPrefix + branch
  101. }
  102. }
  103. ctx.Data["SelectedBranches"] = realBranches
  104. files := ctx.FormStrings("file")
  105. commitsCount, err := ctx.Repo.GetCommitsCount()
  106. if err != nil {
  107. ctx.ServerError("GetCommitsCount", err)
  108. return
  109. }
  110. graphCommitsCount, err := ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files)
  111. if err != nil {
  112. 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)
  113. realBranches = []string{}
  114. branches = []string{}
  115. graphCommitsCount, err = ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files)
  116. if err != nil {
  117. ctx.ServerError("GetCommitGraphsCount", err)
  118. return
  119. }
  120. }
  121. page := ctx.FormInt("page")
  122. graph, err := gitgraph.GetCommitGraph(ctx.Repo.GitRepo, page, 0, hidePRRefs, realBranches, files)
  123. if err != nil {
  124. ctx.ServerError("GetCommitGraph", err)
  125. return
  126. }
  127. if err := graph.LoadAndProcessCommits(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo); err != nil {
  128. ctx.ServerError("LoadAndProcessCommits", err)
  129. return
  130. }
  131. ctx.Data["Graph"] = graph
  132. gitRefs, err := ctx.Repo.GitRepo.GetRefs()
  133. if err != nil {
  134. ctx.ServerError("GitRepo.GetRefs", err)
  135. return
  136. }
  137. ctx.Data["AllRefs"] = gitRefs
  138. ctx.Data["Username"] = ctx.Repo.Owner.Name
  139. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  140. ctx.Data["CommitCount"] = commitsCount
  141. paginator := context.NewPagination(int(graphCommitsCount), setting.UI.GraphMaxCommitNum, page, 5)
  142. paginator.AddParamString("mode", mode)
  143. paginator.AddParamString("hide-pr-refs", fmt.Sprint(hidePRRefs))
  144. for _, branch := range branches {
  145. paginator.AddParamString("branch", branch)
  146. }
  147. for _, file := range files {
  148. paginator.AddParamString("file", file)
  149. }
  150. ctx.Data["Page"] = paginator
  151. if ctx.FormBool("div-only") {
  152. ctx.HTML(http.StatusOK, tplGraphDiv)
  153. return
  154. }
  155. ctx.HTML(http.StatusOK, tplGraph)
  156. }
  157. // SearchCommits render commits filtered by keyword
  158. func SearchCommits(ctx *context.Context) {
  159. ctx.Data["PageIsCommits"] = true
  160. ctx.Data["PageIsViewCode"] = true
  161. query := ctx.FormTrim("q")
  162. if len(query) == 0 {
  163. ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchNameSubURL())
  164. return
  165. }
  166. all := ctx.FormBool("all")
  167. opts := git.NewSearchCommitsOptions(query, all)
  168. commits, err := ctx.Repo.Commit.SearchCommits(opts)
  169. if err != nil {
  170. ctx.ServerError("SearchCommits", err)
  171. return
  172. }
  173. ctx.Data["CommitCount"] = len(commits)
  174. ctx.Data["Commits"] = git_model.ConvertFromGitCommit(ctx, commits, ctx.Repo.Repository)
  175. ctx.Data["Keyword"] = query
  176. if all {
  177. ctx.Data["All"] = true
  178. }
  179. ctx.Data["Username"] = ctx.Repo.Owner.Name
  180. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  181. ctx.HTML(http.StatusOK, tplCommits)
  182. }
  183. // FileHistory show a file's reversions
  184. func FileHistory(ctx *context.Context) {
  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 = gitrepo.OpenWikiRepository(ctx, ctx.Repo.Repository)
  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) != commit.ID.Type().FullLength() {
  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(ctx, 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.ListOptionsAll)
  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(ctx),
  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 := gitrepo.OpenWikiRepository(ctx, ctx.Repo.Repository)
  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. }