repo.go 13 KB

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