repo.go 12 KB

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