repo.go 12 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/gogs/git-module"
  12. "github.com/gogs/gogs/models"
  13. "github.com/gogs/gogs/models/errors"
  14. "github.com/gogs/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(c *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 := c.Params(":username")
  109. repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
  110. refName := c.Params(":branchname")
  111. if len(refName) == 0 {
  112. refName = c.Params(":path")
  113. }
  114. // Check if the user is the same as the repository owner
  115. if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) {
  116. owner = c.User
  117. } else {
  118. owner, err = models.GetUserByName(ownerName)
  119. if err != nil {
  120. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  121. return
  122. }
  123. }
  124. c.Repo.Owner = owner
  125. c.Data["Username"] = c.Repo.Owner.Name
  126. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  127. if err != nil {
  128. c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
  129. return
  130. }
  131. c.Repo.Repository = repo
  132. c.Data["RepoName"] = c.Repo.Repository.Name
  133. c.Data["IsBareRepo"] = c.Repo.Repository.IsBare
  134. c.Repo.RepoLink = repo.Link()
  135. c.Data["RepoLink"] = c.Repo.RepoLink
  136. c.Data["RepoRelPath"] = c.Repo.Owner.Name + "/" + c.Repo.Repository.Name
  137. // Admin has super access.
  138. if c.IsLogged && c.User.IsAdmin {
  139. c.Repo.AccessMode = models.ACCESS_MODE_OWNER
  140. } else {
  141. mode, err := models.AccessLevel(c.UserID(), repo)
  142. if err != nil {
  143. c.ServerError("AccessLevel", err)
  144. return
  145. }
  146. c.Repo.AccessMode = mode
  147. }
  148. // Check access
  149. if c.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. c.Redirect(repo.Link() + "/issues")
  158. case repo.CanGuestViewWiki():
  159. c.Redirect(repo.Link() + "/wiki")
  160. default:
  161. c.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. c.NotFound()
  170. return
  171. }
  172. c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
  173. c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
  174. }
  175. if repo.IsMirror {
  176. c.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  177. if err != nil {
  178. c.ServerError("GetMirror", err)
  179. return
  180. }
  181. c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune
  182. c.Data["MirrorInterval"] = c.Repo.Mirror.Interval
  183. c.Data["Mirror"] = c.Repo.Mirror
  184. }
  185. gitRepo, err := git.OpenRepository(models.RepoPath(ownerName, repoName))
  186. if err != nil {
  187. c.ServerError(fmt.Sprintf("RepoAssignment Invalid repo '%s'", c.Repo.Repository.RepoPath()), err)
  188. return
  189. }
  190. c.Repo.GitRepo = gitRepo
  191. tags, err := c.Repo.GitRepo.GetTags()
  192. if err != nil {
  193. c.ServerError(fmt.Sprintf("GetTags '%s'", c.Repo.Repository.RepoPath()), err)
  194. return
  195. }
  196. c.Data["Tags"] = tags
  197. c.Repo.Repository.NumTags = len(tags)
  198. c.Data["Title"] = owner.Name + "/" + repo.Name
  199. c.Data["Repository"] = repo
  200. c.Data["Owner"] = c.Repo.Repository.Owner
  201. c.Data["IsRepositoryOwner"] = c.Repo.IsOwner()
  202. c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin()
  203. c.Data["IsRepositoryWriter"] = c.Repo.IsWriter()
  204. c.Data["DisableSSH"] = setting.SSH.Disabled
  205. c.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  206. c.Data["CloneLink"] = repo.CloneLink()
  207. c.Data["WikiCloneLink"] = repo.WikiCloneLink()
  208. if c.IsLogged {
  209. c.Data["IsWatchingRepo"] = models.IsWatching(c.User.ID, repo.ID)
  210. c.Data["IsStaringRepo"] = models.IsStaring(c.User.ID, repo.ID)
  211. }
  212. // repo is bare and display enable
  213. if c.Repo.Repository.IsBare {
  214. return
  215. }
  216. c.Data["TagName"] = c.Repo.TagName
  217. brs, err := c.Repo.GitRepo.GetBranches()
  218. if err != nil {
  219. c.ServerError("GetBranches", err)
  220. return
  221. }
  222. c.Data["Branches"] = brs
  223. c.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(c.Repo.BranchName) == 0 {
  227. if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(c.Repo.Repository.DefaultBranch) {
  228. c.Repo.BranchName = c.Repo.Repository.DefaultBranch
  229. } else if len(brs) > 0 {
  230. c.Repo.BranchName = brs[0]
  231. }
  232. }
  233. c.Data["BranchName"] = c.Repo.BranchName
  234. c.Data["CommitID"] = c.Repo.CommitID
  235. c.Data["IsGuest"] = !c.Repo.HasAccess()
  236. }
  237. }
  238. // RepoRef handles repository reference name including those contain `/`.
  239. func RepoRef() macaron.Handler {
  240. return func(c *Context) {
  241. // Empty repository does not have reference information.
  242. if c.Repo.Repository.IsBare {
  243. return
  244. }
  245. var (
  246. refName string
  247. err error
  248. )
  249. // For API calls.
  250. if c.Repo.GitRepo == nil {
  251. repoPath := models.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
  252. c.Repo.GitRepo, err = git.OpenRepository(repoPath)
  253. if err != nil {
  254. c.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  255. return
  256. }
  257. }
  258. // Get default branch.
  259. if len(c.Params("*")) == 0 {
  260. refName = c.Repo.Repository.DefaultBranch
  261. if !c.Repo.GitRepo.IsBranchExist(refName) {
  262. brs, err := c.Repo.GitRepo.GetBranches()
  263. if err != nil {
  264. c.Handle(500, "GetBranches", err)
  265. return
  266. }
  267. refName = brs[0]
  268. }
  269. c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName)
  270. if err != nil {
  271. c.Handle(500, "GetBranchCommit", err)
  272. return
  273. }
  274. c.Repo.CommitID = c.Repo.Commit.ID.String()
  275. c.Repo.IsViewBranch = true
  276. } else {
  277. hasMatched := false
  278. parts := strings.Split(c.Params("*"), "/")
  279. for i, part := range parts {
  280. refName = strings.TrimPrefix(refName+"/"+part, "/")
  281. if c.Repo.GitRepo.IsBranchExist(refName) ||
  282. c.Repo.GitRepo.IsTagExist(refName) {
  283. if i < len(parts)-1 {
  284. c.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. c.Repo.TreePath = strings.Join(parts[1:], "/")
  293. }
  294. if c.Repo.GitRepo.IsBranchExist(refName) {
  295. c.Repo.IsViewBranch = true
  296. c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName)
  297. if err != nil {
  298. c.Handle(500, "GetBranchCommit", err)
  299. return
  300. }
  301. c.Repo.CommitID = c.Repo.Commit.ID.String()
  302. } else if c.Repo.GitRepo.IsTagExist(refName) {
  303. c.Repo.IsViewTag = true
  304. c.Repo.Commit, err = c.Repo.GitRepo.GetTagCommit(refName)
  305. if err != nil {
  306. c.Handle(500, "GetTagCommit", err)
  307. return
  308. }
  309. c.Repo.CommitID = c.Repo.Commit.ID.String()
  310. } else if len(refName) == 40 {
  311. c.Repo.IsViewCommit = true
  312. c.Repo.CommitID = refName
  313. c.Repo.Commit, err = c.Repo.GitRepo.GetCommit(refName)
  314. if err != nil {
  315. c.NotFound()
  316. return
  317. }
  318. } else {
  319. c.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  320. return
  321. }
  322. }
  323. c.Repo.BranchName = refName
  324. c.Data["BranchName"] = c.Repo.BranchName
  325. c.Data["CommitID"] = c.Repo.CommitID
  326. c.Data["TreePath"] = c.Repo.TreePath
  327. c.Data["IsViewBranch"] = c.Repo.IsViewBranch
  328. c.Data["IsViewTag"] = c.Repo.IsViewTag
  329. c.Data["IsViewCommit"] = c.Repo.IsViewCommit
  330. // People who have push access or have fored repository can propose a new pull request.
  331. if c.Repo.IsWriter() || (c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID)) {
  332. // Pull request is allowed if this is a fork repository
  333. // and base repository accepts pull requests.
  334. if c.Repo.Repository.BaseRepo != nil {
  335. if c.Repo.Repository.BaseRepo.AllowsPulls() {
  336. c.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 c.Repo.IsWriter() {
  340. c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
  341. c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
  342. c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
  343. } else {
  344. c.Data["BaseRepo"] = c.Repo.Repository
  345. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  346. c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
  347. }
  348. }
  349. } else {
  350. // Or, this is repository accepts pull requests between branches.
  351. if c.Repo.Repository.AllowsPulls() {
  352. c.Data["BaseRepo"] = c.Repo.Repository
  353. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  354. c.Repo.PullRequest.Allowed = true
  355. c.Repo.PullRequest.SameRepo = true
  356. c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
  357. }
  358. }
  359. }
  360. c.Data["PullRequestCtx"] = c.Repo.PullRequest
  361. }
  362. }
  363. func RequireRepoAdmin() macaron.Handler {
  364. return func(c *Context) {
  365. if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
  366. c.NotFound()
  367. return
  368. }
  369. }
  370. }
  371. func RequireRepoWriter() macaron.Handler {
  372. return func(c *Context) {
  373. if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
  374. c.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(c *Context) {
  382. if !c.User.CanEditGitHook() {
  383. c.NotFound()
  384. return
  385. }
  386. }
  387. }