repo.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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/modules/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. _, _ = isIssuesPage, isWikiPage
  127. ownerName := ctx.Params(":username")
  128. repoName := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  129. refName := ctx.Params(":branchname")
  130. if len(refName) == 0 {
  131. refName = ctx.Params(":path")
  132. }
  133. // Check if the user is the same as the repository owner
  134. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(ownerName) {
  135. owner = ctx.User
  136. } else {
  137. owner, err = models.GetUserByName(ownerName)
  138. if err != nil {
  139. if errors.IsUserNotExist(err) {
  140. if ctx.Query("go-get") == "1" {
  141. earlyResponseForGoGetMeta(ctx)
  142. return
  143. }
  144. ctx.NotFound()
  145. } else {
  146. ctx.Handle(500, "GetUserByName", err)
  147. }
  148. return
  149. }
  150. }
  151. ctx.Repo.Owner = owner
  152. ctx.Data["Username"] = ctx.Repo.Owner.Name
  153. // Get repository.
  154. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  155. if err != nil {
  156. if errors.IsRepoNotExist(err) {
  157. if ctx.Query("go-get") == "1" {
  158. earlyResponseForGoGetMeta(ctx)
  159. return
  160. }
  161. ctx.NotFound()
  162. } else {
  163. ctx.Handle(500, "GetRepositoryByName", err)
  164. }
  165. return
  166. }
  167. ctx.Repo.Repository = repo
  168. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  169. ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare
  170. ctx.Repo.RepoLink = repo.Link()
  171. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  172. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  173. // Admin has super access.
  174. if ctx.IsSigned && ctx.User.IsAdmin {
  175. ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER
  176. } else {
  177. mode, err := models.AccessLevel(ctx.UserID(), repo)
  178. if err != nil {
  179. ctx.Handle(500, "AccessLevel", err)
  180. return
  181. }
  182. ctx.Repo.AccessMode = mode
  183. }
  184. // Check access
  185. if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE {
  186. if ctx.Query("go-get") == "1" {
  187. earlyResponseForGoGetMeta(ctx)
  188. return
  189. }
  190. // Redirect to any accessible page if not yet on it
  191. if repo.IsPartialPublic() &&
  192. (!(isIssuesPage || isWikiPage) ||
  193. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  194. (isWikiPage && !repo.CanGuestViewWiki())) {
  195. switch {
  196. case repo.CanGuestViewIssues():
  197. ctx.Redirect(repo.Link() + "/issues")
  198. case repo.CanGuestViewWiki():
  199. ctx.Redirect(repo.Link() + "/wiki")
  200. default:
  201. ctx.NotFound()
  202. }
  203. return
  204. }
  205. // Response 404 if user is on completely private repository or possible accessible page but owner doesn't enabled
  206. if !repo.IsPartialPublic() ||
  207. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  208. (isWikiPage && !repo.CanGuestViewWiki()) {
  209. ctx.NotFound()
  210. return
  211. }
  212. ctx.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
  213. ctx.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
  214. }
  215. if repo.IsMirror {
  216. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  217. if err != nil {
  218. ctx.Handle(500, "GetMirror", err)
  219. return
  220. }
  221. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  222. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  223. ctx.Data["Mirror"] = ctx.Repo.Mirror
  224. }
  225. gitRepo, err := git.OpenRepository(models.RepoPath(ownerName, repoName))
  226. if err != nil {
  227. ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(ownerName, repoName), err)
  228. return
  229. }
  230. ctx.Repo.GitRepo = gitRepo
  231. tags, err := ctx.Repo.GitRepo.GetTags()
  232. if err != nil {
  233. ctx.Handle(500, fmt.Sprintf("GetTags '%s'", ctx.Repo.Repository.RepoPath()), err)
  234. return
  235. }
  236. ctx.Data["Tags"] = tags
  237. ctx.Repo.Repository.NumTags = len(tags)
  238. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  239. ctx.Data["Repository"] = repo
  240. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  241. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  242. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  243. ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter()
  244. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  245. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  246. ctx.Data["CloneLink"] = repo.CloneLink()
  247. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  248. if ctx.IsSigned {
  249. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  250. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  251. }
  252. // repo is bare and display enable
  253. if ctx.Repo.Repository.IsBare {
  254. return
  255. }
  256. ctx.Data["TagName"] = ctx.Repo.TagName
  257. brs, err := ctx.Repo.GitRepo.GetBranches()
  258. if err != nil {
  259. ctx.Handle(500, "GetBranches", err)
  260. return
  261. }
  262. ctx.Data["Branches"] = brs
  263. ctx.Data["BrancheCount"] = len(brs)
  264. // If not branch selected, try default one.
  265. // If default branch doesn't exists, fall back to some other branch.
  266. if len(ctx.Repo.BranchName) == 0 {
  267. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  268. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  269. } else if len(brs) > 0 {
  270. ctx.Repo.BranchName = brs[0]
  271. }
  272. }
  273. ctx.Data["BranchName"] = ctx.Repo.BranchName
  274. ctx.Data["CommitID"] = ctx.Repo.CommitID
  275. if ctx.Query("go-get") == "1" {
  276. ctx.Data["GoGetImport"] = composeGoGetImport(owner.Name, repo.Name)
  277. prefix := setting.AppUrl + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName)
  278. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  279. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  280. }
  281. ctx.Data["IsGuest"] = !ctx.Repo.HasAccess()
  282. }
  283. }
  284. // RepoRef handles repository reference name including those contain `/`.
  285. func RepoRef() macaron.Handler {
  286. return func(ctx *Context) {
  287. // Empty repository does not have reference information.
  288. if ctx.Repo.Repository.IsBare {
  289. return
  290. }
  291. var (
  292. refName string
  293. err error
  294. )
  295. // For API calls.
  296. if ctx.Repo.GitRepo == nil {
  297. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  298. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  299. if err != nil {
  300. ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  301. return
  302. }
  303. }
  304. // Get default branch.
  305. if len(ctx.Params("*")) == 0 {
  306. refName = ctx.Repo.Repository.DefaultBranch
  307. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  308. brs, err := ctx.Repo.GitRepo.GetBranches()
  309. if err != nil {
  310. ctx.Handle(500, "GetBranches", err)
  311. return
  312. }
  313. refName = brs[0]
  314. }
  315. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  316. if err != nil {
  317. ctx.Handle(500, "GetBranchCommit", err)
  318. return
  319. }
  320. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  321. ctx.Repo.IsViewBranch = true
  322. } else {
  323. hasMatched := false
  324. parts := strings.Split(ctx.Params("*"), "/")
  325. for i, part := range parts {
  326. refName = strings.TrimPrefix(refName+"/"+part, "/")
  327. if ctx.Repo.GitRepo.IsBranchExist(refName) ||
  328. ctx.Repo.GitRepo.IsTagExist(refName) {
  329. if i < len(parts)-1 {
  330. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  331. }
  332. hasMatched = true
  333. break
  334. }
  335. }
  336. if !hasMatched && len(parts[0]) == 40 {
  337. refName = parts[0]
  338. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  339. }
  340. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  341. ctx.Repo.IsViewBranch = true
  342. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  343. if err != nil {
  344. ctx.Handle(500, "GetBranchCommit", err)
  345. return
  346. }
  347. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  348. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  349. ctx.Repo.IsViewTag = true
  350. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  351. if err != nil {
  352. ctx.Handle(500, "GetTagCommit", err)
  353. return
  354. }
  355. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  356. } else if len(refName) == 40 {
  357. ctx.Repo.IsViewCommit = true
  358. ctx.Repo.CommitID = refName
  359. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  360. if err != nil {
  361. ctx.NotFound()
  362. return
  363. }
  364. } else {
  365. ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  366. return
  367. }
  368. }
  369. ctx.Repo.BranchName = refName
  370. ctx.Data["BranchName"] = ctx.Repo.BranchName
  371. ctx.Data["CommitID"] = ctx.Repo.CommitID
  372. ctx.Data["TreePath"] = ctx.Repo.TreePath
  373. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  374. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  375. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  376. // People who have push access or have fored repository can propose a new pull request.
  377. if ctx.Repo.IsWriter() || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  378. // Pull request is allowed if this is a fork repository
  379. // and base repository accepts pull requests.
  380. if ctx.Repo.Repository.BaseRepo != nil {
  381. if ctx.Repo.Repository.BaseRepo.AllowsPulls() {
  382. ctx.Repo.PullRequest.Allowed = true
  383. // In-repository pull requests has higher priority than cross-repository if user is viewing
  384. // base repository and 1) has write access to it 2) has forked it.
  385. if ctx.Repo.IsWriter() {
  386. ctx.Data["BaseRepo"] = ctx.Repo.Repository.BaseRepo
  387. ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository.BaseRepo
  388. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  389. } else {
  390. ctx.Data["BaseRepo"] = ctx.Repo.Repository
  391. ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository
  392. ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName
  393. }
  394. }
  395. } else {
  396. // Or, this is repository accepts pull requests between branches.
  397. if ctx.Repo.Repository.AllowsPulls() {
  398. ctx.Data["BaseRepo"] = ctx.Repo.Repository
  399. ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository
  400. ctx.Repo.PullRequest.Allowed = true
  401. ctx.Repo.PullRequest.SameRepo = true
  402. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  403. }
  404. }
  405. }
  406. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  407. }
  408. }
  409. func RequireRepoAdmin() macaron.Handler {
  410. return func(ctx *Context) {
  411. if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) {
  412. ctx.NotFound()
  413. return
  414. }
  415. }
  416. }
  417. func RequireRepoWriter() macaron.Handler {
  418. return func(ctx *Context) {
  419. if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) {
  420. ctx.NotFound()
  421. return
  422. }
  423. }
  424. }
  425. // GitHookService checks if repository Git hooks service has been enabled.
  426. func GitHookService() macaron.Handler {
  427. return func(ctx *Context) {
  428. if !ctx.User.CanEditGitHook() {
  429. ctx.NotFound()
  430. return
  431. }
  432. }
  433. }