2
0

repo.go 13 KB

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