repo.go 13 KB

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