1
0

repo.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package context
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/url"
  6. "strings"
  7. "github.com/cockroachdb/errors"
  8. "github.com/editorconfig/editorconfig-core-go/v2"
  9. "gopkg.in/macaron.v1"
  10. "github.com/gogs/git-module"
  11. "gogs.io/gogs/internal/conf"
  12. "gogs.io/gogs/internal/database"
  13. "gogs.io/gogs/internal/repoutil"
  14. )
  15. type PullRequest struct {
  16. BaseRepo *database.Repository
  17. Allowed bool
  18. SameRepo bool
  19. HeadInfo string // [<user>:]<branch>
  20. }
  21. type Repository struct {
  22. AccessMode database.AccessMode
  23. IsWatching bool
  24. IsViewBranch bool
  25. IsViewTag bool
  26. IsViewCommit bool
  27. Repository *database.Repository
  28. Owner *database.User
  29. Commit *git.Commit
  30. Tag *git.Tag
  31. GitRepo *git.Repository
  32. BranchName string
  33. TagName string
  34. TreePath string
  35. CommitID string
  36. RepoLink string
  37. CloneLink repoutil.CloneLink
  38. CommitsCount int64
  39. Mirror *database.Mirror
  40. PullRequest *PullRequest
  41. }
  42. // IsOwner returns true if current user is the owner of repository.
  43. func (r *Repository) IsOwner() bool {
  44. return r.AccessMode >= database.AccessModeOwner
  45. }
  46. // IsAdmin returns true if current user has admin or higher access of repository.
  47. func (r *Repository) IsAdmin() bool {
  48. return r.AccessMode >= database.AccessModeAdmin
  49. }
  50. // IsWriter returns true if current user has write or higher access of repository.
  51. func (r *Repository) IsWriter() bool {
  52. return r.AccessMode >= database.AccessModeWrite
  53. }
  54. // HasAccess returns true if the current user has at least read access for this repository
  55. func (r *Repository) HasAccess() bool {
  56. return r.AccessMode >= database.AccessModeRead
  57. }
  58. // CanEnableEditor returns true if repository is editable and user has proper access level.
  59. func (r *Repository) CanEnableEditor() bool {
  60. return r.Repository.CanEnableEditor() && r.IsViewBranch && r.IsWriter() && !r.Repository.IsBranchRequirePullRequest(r.BranchName)
  61. }
  62. // Editorconfig returns the ".editorconfig" definition if found in the HEAD of the default branch.
  63. func (r *Repository) Editorconfig() (*editorconfig.Editorconfig, error) {
  64. commit, err := r.GitRepo.BranchCommit(r.Repository.DefaultBranch)
  65. if err != nil {
  66. return nil, errors.Wrapf(err, "get commit of branch %q ", r.Repository.DefaultBranch)
  67. }
  68. entry, err := commit.TreeEntry(".editorconfig")
  69. if err != nil {
  70. return nil, errors.Wrap(err, "get .editorconfig")
  71. }
  72. p, err := entry.Blob().Bytes()
  73. if err != nil {
  74. return nil, errors.Wrap(err, "read .editorconfig")
  75. }
  76. return editorconfig.Parse(bytes.NewReader(p))
  77. }
  78. // MakeURL accepts a string or url.URL as argument and returns escaped URL prepended with repository URL.
  79. func (r *Repository) MakeURL(location any) string {
  80. switch location := location.(type) {
  81. case string:
  82. tempURL := url.URL{
  83. Path: r.RepoLink + "/" + location,
  84. }
  85. return tempURL.String()
  86. case url.URL:
  87. location.Path = r.RepoLink + "/" + location.Path
  88. return location.String()
  89. default:
  90. panic("location type must be either string or url.URL")
  91. }
  92. }
  93. // PullRequestURL returns URL for composing a pull request.
  94. // This function does not check if the repository can actually compose a pull request.
  95. func (r *Repository) PullRequestURL(baseBranch, headBranch string) string {
  96. repoLink := r.RepoLink
  97. if r.PullRequest.BaseRepo != nil {
  98. repoLink = r.PullRequest.BaseRepo.Link()
  99. }
  100. return fmt.Sprintf("%s/compare/%s...%s:%s", repoLink, baseBranch, r.Owner.Name, headBranch)
  101. }
  102. // [0]: issues, [1]: wiki
  103. func RepoAssignment(pages ...bool) macaron.Handler {
  104. return func(c *Context) {
  105. var (
  106. owner *database.User
  107. err error
  108. isIssuesPage bool
  109. isWikiPage bool
  110. )
  111. if len(pages) > 0 {
  112. isIssuesPage = pages[0]
  113. }
  114. if len(pages) > 1 {
  115. isWikiPage = pages[1]
  116. }
  117. ownerName := c.Params(":username")
  118. repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
  119. // Check if the user is the same as the repository owner
  120. if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) {
  121. owner = c.User
  122. } else {
  123. owner, err = database.Handle.Users().GetByUsername(c.Req.Context(), ownerName)
  124. if err != nil {
  125. c.NotFoundOrError(err, "get user by name")
  126. return
  127. }
  128. }
  129. c.Repo.Owner = owner
  130. c.Data["Username"] = c.Repo.Owner.Name
  131. repo, err := database.GetRepositoryByName(owner.ID, repoName)
  132. if err != nil {
  133. c.NotFoundOrError(err, "get repository by name")
  134. return
  135. }
  136. c.Repo.Repository = repo
  137. c.Data["RepoName"] = c.Repo.Repository.Name
  138. c.Data["IsBareRepo"] = c.Repo.Repository.IsBare
  139. c.Repo.RepoLink = repo.Link()
  140. c.Data["RepoLink"] = c.Repo.RepoLink
  141. c.Data["RepoRelPath"] = c.Repo.Owner.Name + "/" + c.Repo.Repository.Name
  142. // Admin has super access
  143. if c.IsLogged && c.User.IsAdmin {
  144. c.Repo.AccessMode = database.AccessModeOwner
  145. } else {
  146. c.Repo.AccessMode = database.Handle.Permissions().AccessMode(c.Req.Context(), c.UserID(), repo.ID,
  147. database.AccessModeOptions{
  148. OwnerID: repo.OwnerID,
  149. Private: repo.IsPrivate,
  150. },
  151. )
  152. }
  153. // If the authenticated user has no direct access, see if the repository is a fork
  154. // and whether the user has access to the base repository.
  155. if c.Repo.AccessMode == database.AccessModeNone && repo.BaseRepo != nil {
  156. mode := min(
  157. // Users shouldn't have indirect access level higher than write.
  158. database.Handle.Permissions().AccessMode(c.Req.Context(), c.UserID(), repo.BaseRepo.ID,
  159. database.AccessModeOptions{
  160. OwnerID: repo.BaseRepo.OwnerID,
  161. Private: repo.BaseRepo.IsPrivate,
  162. },
  163. ),
  164. database.AccessModeWrite,
  165. )
  166. c.Repo.AccessMode = mode
  167. }
  168. // Check access
  169. if c.Repo.AccessMode == database.AccessModeNone {
  170. // Redirect to any accessible page if not yet on it
  171. if repo.IsPartialPublic() &&
  172. (!(isIssuesPage || isWikiPage) ||
  173. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  174. (isWikiPage && !repo.CanGuestViewWiki())) {
  175. switch {
  176. case repo.CanGuestViewIssues():
  177. c.Redirect(repo.Link() + "/issues")
  178. case repo.CanGuestViewWiki():
  179. c.Redirect(repo.Link() + "/wiki")
  180. default:
  181. c.NotFound()
  182. }
  183. return
  184. }
  185. // Response 404 if user is on completely private repository or possible accessible page but owner doesn't enabled
  186. if !repo.IsPartialPublic() ||
  187. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  188. (isWikiPage && !repo.CanGuestViewWiki()) {
  189. c.NotFound()
  190. return
  191. }
  192. c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
  193. c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
  194. }
  195. if repo.IsMirror {
  196. c.Repo.Mirror, err = database.GetMirrorByRepoID(repo.ID)
  197. if err != nil {
  198. c.Error(err, "get mirror by repository ID")
  199. return
  200. }
  201. c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune
  202. c.Data["MirrorInterval"] = c.Repo.Mirror.Interval
  203. c.Data["Mirror"] = c.Repo.Mirror
  204. }
  205. gitRepo, err := git.Open(database.RepoPath(ownerName, repoName))
  206. if err != nil {
  207. c.Error(err, "open repository")
  208. return
  209. }
  210. c.Repo.GitRepo = gitRepo
  211. tags, err := c.Repo.GitRepo.Tags()
  212. if err != nil {
  213. c.Error(err, "get tags")
  214. return
  215. }
  216. c.Data["Tags"] = tags
  217. c.Repo.Repository.NumTags = len(tags)
  218. c.Data["Title"] = owner.Name + "/" + repo.Name
  219. c.Data["Repository"] = repo
  220. c.Data["Owner"] = c.Repo.Repository.Owner
  221. c.Data["IsRepositoryOwner"] = c.Repo.IsOwner()
  222. c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin()
  223. c.Data["IsRepositoryWriter"] = c.Repo.IsWriter()
  224. c.Data["DisableSSH"] = conf.SSH.Disabled
  225. c.Data["DisableHTTP"] = conf.Repository.DisableHTTPGit
  226. c.Data["CloneLink"] = repo.CloneLink()
  227. c.Data["WikiCloneLink"] = repo.WikiCloneLink()
  228. if c.IsLogged {
  229. c.Data["IsWatchingRepo"] = database.IsWatching(c.User.ID, repo.ID)
  230. c.Data["IsStaringRepo"] = database.IsStaring(c.User.ID, repo.ID)
  231. }
  232. // repo is bare and display enable
  233. if c.Repo.Repository.IsBare {
  234. return
  235. }
  236. c.Data["TagName"] = c.Repo.TagName
  237. branches, err := c.Repo.GitRepo.Branches()
  238. if err != nil {
  239. c.Error(err, "get branches")
  240. return
  241. }
  242. c.Data["Branches"] = branches
  243. c.Data["BranchCount"] = len(branches)
  244. // If not branch selected, try default one.
  245. // If default branch doesn't exists, fall back to some other branch.
  246. if c.Repo.BranchName == "" {
  247. if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.HasBranch(c.Repo.Repository.DefaultBranch) {
  248. c.Repo.BranchName = c.Repo.Repository.DefaultBranch
  249. } else if len(branches) > 0 {
  250. c.Repo.BranchName = branches[0]
  251. }
  252. }
  253. c.Data["BranchName"] = c.Repo.BranchName
  254. c.Data["CommitID"] = c.Repo.CommitID
  255. c.Data["IsGuest"] = !c.Repo.HasAccess()
  256. }
  257. }
  258. // RepoRef handles repository reference name including those contain `/`.
  259. func RepoRef() macaron.Handler {
  260. return func(c *Context) {
  261. // Empty repository does not have reference information.
  262. if c.Repo.Repository.IsBare {
  263. return
  264. }
  265. var (
  266. refName string
  267. err error
  268. )
  269. // For API calls.
  270. if c.Repo.GitRepo == nil {
  271. repoPath := database.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
  272. c.Repo.GitRepo, err = git.Open(repoPath)
  273. if err != nil {
  274. c.Error(err, "open repository")
  275. return
  276. }
  277. }
  278. // Get default branch.
  279. if c.Params("*") == "" {
  280. refName = c.Repo.Repository.DefaultBranch
  281. if !c.Repo.GitRepo.HasBranch(refName) {
  282. branches, err := c.Repo.GitRepo.Branches()
  283. if err != nil {
  284. c.Error(err, "get branches")
  285. return
  286. }
  287. refName = branches[0]
  288. }
  289. c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
  290. if err != nil {
  291. c.Error(err, "get branch commit")
  292. return
  293. }
  294. c.Repo.CommitID = c.Repo.Commit.ID.String()
  295. c.Repo.IsViewBranch = true
  296. } else {
  297. hasMatched := false
  298. parts := strings.Split(c.Params("*"), "/")
  299. for i, part := range parts {
  300. refName = strings.TrimPrefix(refName+"/"+part, "/")
  301. if c.Repo.GitRepo.HasBranch(refName) ||
  302. c.Repo.GitRepo.HasTag(refName) {
  303. if i < len(parts)-1 {
  304. c.Repo.TreePath = strings.Join(parts[i+1:], "/")
  305. }
  306. hasMatched = true
  307. break
  308. }
  309. }
  310. if !hasMatched && len(parts[0]) == 40 {
  311. refName = parts[0]
  312. c.Repo.TreePath = strings.Join(parts[1:], "/")
  313. }
  314. if c.Repo.GitRepo.HasBranch(refName) {
  315. c.Repo.IsViewBranch = true
  316. c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
  317. if err != nil {
  318. c.Error(err, "get branch commit")
  319. return
  320. }
  321. c.Repo.CommitID = c.Repo.Commit.ID.String()
  322. } else if c.Repo.GitRepo.HasTag(refName) {
  323. c.Repo.IsViewTag = true
  324. c.Repo.Commit, err = c.Repo.GitRepo.TagCommit(refName)
  325. if err != nil {
  326. c.Error(err, "get tag commit")
  327. return
  328. }
  329. c.Repo.CommitID = c.Repo.Commit.ID.String()
  330. } else if len(refName) == 40 {
  331. c.Repo.IsViewCommit = true
  332. c.Repo.CommitID = refName
  333. c.Repo.Commit, err = c.Repo.GitRepo.CatFileCommit(refName)
  334. if err != nil {
  335. c.NotFound()
  336. return
  337. }
  338. } else {
  339. c.NotFound()
  340. return
  341. }
  342. }
  343. c.Repo.BranchName = refName
  344. c.Data["BranchName"] = c.Repo.BranchName
  345. c.Data["CommitID"] = c.Repo.CommitID
  346. c.Data["TreePath"] = c.Repo.TreePath
  347. c.Data["IsViewBranch"] = c.Repo.IsViewBranch
  348. c.Data["IsViewTag"] = c.Repo.IsViewTag
  349. c.Data["IsViewCommit"] = c.Repo.IsViewCommit
  350. // People who have push access or have forked repository can propose a new pull request.
  351. if c.Repo.IsWriter() || (c.IsLogged && database.Handle.Repositories().HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID)) {
  352. // Pull request is allowed if this is a fork repository
  353. // and base repository accepts pull requests.
  354. if c.Repo.Repository.BaseRepo != nil {
  355. if c.Repo.Repository.BaseRepo.AllowsPulls() {
  356. c.Repo.PullRequest.Allowed = true
  357. // In-repository pull requests has higher priority than cross-repository if user is viewing
  358. // base repository and 1) has write access to it 2) has forked it.
  359. if c.Repo.IsWriter() {
  360. c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
  361. c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
  362. c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
  363. } else {
  364. c.Data["BaseRepo"] = c.Repo.Repository
  365. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  366. c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
  367. }
  368. }
  369. } else {
  370. // Or, this is repository accepts pull requests between branches.
  371. if c.Repo.Repository.AllowsPulls() {
  372. c.Data["BaseRepo"] = c.Repo.Repository
  373. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  374. c.Repo.PullRequest.Allowed = true
  375. c.Repo.PullRequest.SameRepo = true
  376. c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
  377. }
  378. }
  379. }
  380. c.Data["PullRequestCtx"] = c.Repo.PullRequest
  381. }
  382. }
  383. func RequireRepoAdmin() macaron.Handler {
  384. return func(c *Context) {
  385. if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
  386. c.NotFound()
  387. return
  388. }
  389. }
  390. }
  391. func RequireRepoWriter() macaron.Handler {
  392. return func(c *Context) {
  393. if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
  394. c.NotFound()
  395. return
  396. }
  397. }
  398. }
  399. // GitHookService checks if repository Git hooks service has been enabled.
  400. func GitHookService() macaron.Handler {
  401. return func(c *Context) {
  402. if !c.User.CanEditGitHook() {
  403. c.NotFound()
  404. return
  405. }
  406. }
  407. }