repo.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. c.Repo.AccessMode = db.Perms.AccessMode(c.UserID(), repo.ID,
  149. db.AccessModeOptions{
  150. OwnerID: repo.OwnerID,
  151. Private: repo.IsPrivate,
  152. },
  153. )
  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 && repo.BaseRepo != nil {
  158. mode := db.Perms.AccessMode(c.UserID(), repo.BaseRepo.ID,
  159. db.AccessModeOptions{
  160. OwnerID: repo.BaseRepo.OwnerID,
  161. Private: repo.BaseRepo.IsPrivate,
  162. },
  163. )
  164. // Users shouldn't have indirect access level higher than write.
  165. if mode > db.AccessModeWrite {
  166. mode = db.AccessModeWrite
  167. }
  168. c.Repo.AccessMode = mode
  169. }
  170. // Check access
  171. if c.Repo.AccessMode == db.AccessModeNone {
  172. // Redirect to any accessible page if not yet on it
  173. if repo.IsPartialPublic() &&
  174. (!(isIssuesPage || isWikiPage) ||
  175. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  176. (isWikiPage && !repo.CanGuestViewWiki())) {
  177. switch {
  178. case repo.CanGuestViewIssues():
  179. c.Redirect(repo.Link() + "/issues")
  180. case repo.CanGuestViewWiki():
  181. c.Redirect(repo.Link() + "/wiki")
  182. default:
  183. c.NotFound()
  184. }
  185. return
  186. }
  187. // Response 404 if user is on completely private repository or possible accessible page but owner doesn't enabled
  188. if !repo.IsPartialPublic() ||
  189. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  190. (isWikiPage && !repo.CanGuestViewWiki()) {
  191. c.NotFound()
  192. return
  193. }
  194. c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
  195. c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
  196. }
  197. if repo.IsMirror {
  198. c.Repo.Mirror, err = db.GetMirrorByRepoID(repo.ID)
  199. if err != nil {
  200. c.Error(err, "get mirror by repository ID")
  201. return
  202. }
  203. c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune
  204. c.Data["MirrorInterval"] = c.Repo.Mirror.Interval
  205. c.Data["Mirror"] = c.Repo.Mirror
  206. }
  207. gitRepo, err := git.Open(db.RepoPath(ownerName, repoName))
  208. if err != nil {
  209. c.Error(err, "open repository")
  210. return
  211. }
  212. c.Repo.GitRepo = gitRepo
  213. tags, err := c.Repo.GitRepo.Tags()
  214. if err != nil {
  215. c.Error(err, "get tags")
  216. return
  217. }
  218. c.Data["Tags"] = tags
  219. c.Repo.Repository.NumTags = len(tags)
  220. c.Data["Title"] = owner.Name + "/" + repo.Name
  221. c.Data["Repository"] = repo
  222. c.Data["Owner"] = c.Repo.Repository.Owner
  223. c.Data["IsRepositoryOwner"] = c.Repo.IsOwner()
  224. c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin()
  225. c.Data["IsRepositoryWriter"] = c.Repo.IsWriter()
  226. c.Data["DisableSSH"] = conf.SSH.Disabled
  227. c.Data["DisableHTTP"] = conf.Repository.DisableHTTPGit
  228. c.Data["CloneLink"] = repo.CloneLink()
  229. c.Data["WikiCloneLink"] = repo.WikiCloneLink()
  230. if c.IsLogged {
  231. c.Data["IsWatchingRepo"] = db.IsWatching(c.User.ID, repo.ID)
  232. c.Data["IsStaringRepo"] = db.IsStaring(c.User.ID, repo.ID)
  233. }
  234. // repo is bare and display enable
  235. if c.Repo.Repository.IsBare {
  236. return
  237. }
  238. c.Data["TagName"] = c.Repo.TagName
  239. branches, err := c.Repo.GitRepo.Branches()
  240. if err != nil {
  241. c.Error(err, "get branches")
  242. return
  243. }
  244. c.Data["Branches"] = branches
  245. c.Data["BranchCount"] = len(branches)
  246. // If not branch selected, try default one.
  247. // If default branch doesn't exists, fall back to some other branch.
  248. if len(c.Repo.BranchName) == 0 {
  249. if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.HasBranch(c.Repo.Repository.DefaultBranch) {
  250. c.Repo.BranchName = c.Repo.Repository.DefaultBranch
  251. } else if len(branches) > 0 {
  252. c.Repo.BranchName = branches[0]
  253. }
  254. }
  255. c.Data["BranchName"] = c.Repo.BranchName
  256. c.Data["CommitID"] = c.Repo.CommitID
  257. c.Data["IsGuest"] = !c.Repo.HasAccess()
  258. }
  259. }
  260. // RepoRef handles repository reference name including those contain `/`.
  261. func RepoRef() macaron.Handler {
  262. return func(c *Context) {
  263. // Empty repository does not have reference information.
  264. if c.Repo.Repository.IsBare {
  265. return
  266. }
  267. var (
  268. refName string
  269. err error
  270. )
  271. // For API calls.
  272. if c.Repo.GitRepo == nil {
  273. repoPath := db.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
  274. c.Repo.GitRepo, err = git.Open(repoPath)
  275. if err != nil {
  276. c.Error(err, "open repository")
  277. return
  278. }
  279. }
  280. // Get default branch.
  281. if len(c.Params("*")) == 0 {
  282. refName = c.Repo.Repository.DefaultBranch
  283. if !c.Repo.GitRepo.HasBranch(refName) {
  284. branches, err := c.Repo.GitRepo.Branches()
  285. if err != nil {
  286. c.Error(err, "get branches")
  287. return
  288. }
  289. refName = branches[0]
  290. }
  291. c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
  292. if err != nil {
  293. c.Error(err, "get branch commit")
  294. return
  295. }
  296. c.Repo.CommitID = c.Repo.Commit.ID.String()
  297. c.Repo.IsViewBranch = true
  298. } else {
  299. hasMatched := false
  300. parts := strings.Split(c.Params("*"), "/")
  301. for i, part := range parts {
  302. refName = strings.TrimPrefix(refName+"/"+part, "/")
  303. if c.Repo.GitRepo.HasBranch(refName) ||
  304. c.Repo.GitRepo.HasTag(refName) {
  305. if i < len(parts)-1 {
  306. c.Repo.TreePath = strings.Join(parts[i+1:], "/")
  307. }
  308. hasMatched = true
  309. break
  310. }
  311. }
  312. if !hasMatched && len(parts[0]) == 40 {
  313. refName = parts[0]
  314. c.Repo.TreePath = strings.Join(parts[1:], "/")
  315. }
  316. if c.Repo.GitRepo.HasBranch(refName) {
  317. c.Repo.IsViewBranch = true
  318. c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
  319. if err != nil {
  320. c.Error(err, "get branch commit")
  321. return
  322. }
  323. c.Repo.CommitID = c.Repo.Commit.ID.String()
  324. } else if c.Repo.GitRepo.HasTag(refName) {
  325. c.Repo.IsViewTag = true
  326. c.Repo.Commit, err = c.Repo.GitRepo.TagCommit(refName)
  327. if err != nil {
  328. c.Error(err, "get tag commit")
  329. return
  330. }
  331. c.Repo.CommitID = c.Repo.Commit.ID.String()
  332. } else if len(refName) == 40 {
  333. c.Repo.IsViewCommit = true
  334. c.Repo.CommitID = refName
  335. c.Repo.Commit, err = c.Repo.GitRepo.CatFileCommit(refName)
  336. if err != nil {
  337. c.NotFound()
  338. return
  339. }
  340. } else {
  341. c.NotFound()
  342. return
  343. }
  344. }
  345. c.Repo.BranchName = refName
  346. c.Data["BranchName"] = c.Repo.BranchName
  347. c.Data["CommitID"] = c.Repo.CommitID
  348. c.Data["TreePath"] = c.Repo.TreePath
  349. c.Data["IsViewBranch"] = c.Repo.IsViewBranch
  350. c.Data["IsViewTag"] = c.Repo.IsViewTag
  351. c.Data["IsViewCommit"] = c.Repo.IsViewCommit
  352. // People who have push access or have forked repository can propose a new pull request.
  353. if c.Repo.IsWriter() || (c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID)) {
  354. // Pull request is allowed if this is a fork repository
  355. // and base repository accepts pull requests.
  356. if c.Repo.Repository.BaseRepo != nil {
  357. if c.Repo.Repository.BaseRepo.AllowsPulls() {
  358. c.Repo.PullRequest.Allowed = true
  359. // In-repository pull requests has higher priority than cross-repository if user is viewing
  360. // base repository and 1) has write access to it 2) has forked it.
  361. if c.Repo.IsWriter() {
  362. c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
  363. c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
  364. c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
  365. } else {
  366. c.Data["BaseRepo"] = c.Repo.Repository
  367. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  368. c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
  369. }
  370. }
  371. } else {
  372. // Or, this is repository accepts pull requests between branches.
  373. if c.Repo.Repository.AllowsPulls() {
  374. c.Data["BaseRepo"] = c.Repo.Repository
  375. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  376. c.Repo.PullRequest.Allowed = true
  377. c.Repo.PullRequest.SameRepo = true
  378. c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
  379. }
  380. }
  381. }
  382. c.Data["PullRequestCtx"] = c.Repo.PullRequest
  383. }
  384. }
  385. func RequireRepoAdmin() macaron.Handler {
  386. return func(c *Context) {
  387. if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
  388. c.NotFound()
  389. return
  390. }
  391. }
  392. }
  393. func RequireRepoWriter() macaron.Handler {
  394. return func(c *Context) {
  395. if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
  396. c.NotFound()
  397. return
  398. }
  399. }
  400. }
  401. // GitHookService checks if repository Git hooks service has been enabled.
  402. func GitHookService() macaron.Handler {
  403. return func(c *Context) {
  404. if !c.User.CanEditGitHook() {
  405. c.NotFound()
  406. return
  407. }
  408. }
  409. }