repo.go 14 KB

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