repo.go 12 KB

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