repo.go 13 KB

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