repo.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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/G-Node/git-module"
  12. "github.com/G-Node/gogs/models"
  13. "github.com/G-Node/gogs/models/errors"
  14. "github.com/G-Node/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.UserAccessMode(c.UserID(), repo)
  142. if err != nil {
  143. c.ServerError("UserAccessMode", 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["ShowHTTP"] = setting.Repository.ShowHTTPGit
  207. c.Data["CloneLink"] = repo.CloneLink()
  208. c.Data["WikiCloneLink"] = repo.WikiCloneLink()
  209. if c.IsLogged {
  210. c.Data["IsWatchingRepo"] = models.IsWatching(c.User.ID, repo.ID)
  211. c.Data["IsStaringRepo"] = models.IsStaring(c.User.ID, repo.ID)
  212. c.Data["HasForked"] = c.User.HasForkedRepo(c.Repo.Repository.ID)
  213. }
  214. // repo is bare and display enable
  215. if c.Repo.Repository.IsBare {
  216. return
  217. }
  218. c.Data["TagName"] = c.Repo.TagName
  219. brs, err := c.Repo.GitRepo.GetBranches()
  220. if err != nil {
  221. c.ServerError("GetBranches", err)
  222. return
  223. }
  224. c.Data["Branches"] = brs
  225. c.Data["BrancheCount"] = len(brs)
  226. // If not branch selected, try default one.
  227. // If default branch doesn't exists, fall back to some other branch.
  228. if len(c.Repo.BranchName) == 0 {
  229. if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(c.Repo.Repository.DefaultBranch) {
  230. c.Repo.BranchName = c.Repo.Repository.DefaultBranch
  231. } else if len(brs) > 0 {
  232. c.Repo.BranchName = brs[0]
  233. }
  234. }
  235. c.Data["BranchName"] = c.Repo.BranchName
  236. c.Data["CommitID"] = c.Repo.CommitID
  237. c.Data["IsGuest"] = !c.Repo.HasAccess()
  238. }
  239. }
  240. // RepoRef handles repository reference name including those contain `/`.
  241. func RepoRef() macaron.Handler {
  242. return func(c *Context) {
  243. // Empty repository does not have reference information.
  244. if c.Repo.Repository.IsBare {
  245. return
  246. }
  247. var (
  248. refName string
  249. err error
  250. )
  251. // For API calls.
  252. if c.Repo.GitRepo == nil {
  253. repoPath := models.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
  254. c.Repo.GitRepo, err = git.OpenRepository(repoPath)
  255. if err != nil {
  256. c.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  257. return
  258. }
  259. }
  260. // Get default branch.
  261. if len(c.Params("*")) == 0 {
  262. refName = c.Repo.Repository.DefaultBranch
  263. if !c.Repo.GitRepo.IsBranchExist(refName) {
  264. brs, err := c.Repo.GitRepo.GetBranches()
  265. if err != nil {
  266. c.Handle(500, "GetBranches", err)
  267. return
  268. }
  269. refName = brs[0]
  270. }
  271. c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName)
  272. if err != nil {
  273. c.Handle(500, "GetBranchCommit", err)
  274. return
  275. }
  276. c.Repo.CommitID = c.Repo.Commit.ID.String()
  277. c.Repo.IsViewBranch = true
  278. } else {
  279. hasMatched := false
  280. parts := strings.Split(c.Params("*"), "/")
  281. for i, part := range parts {
  282. refName = strings.TrimPrefix(refName+"/"+part, "/")
  283. if c.Repo.GitRepo.IsBranchExist(refName) ||
  284. c.Repo.GitRepo.IsTagExist(refName) {
  285. if i < len(parts)-1 {
  286. c.Repo.TreePath = strings.Join(parts[i+1:], "/")
  287. }
  288. hasMatched = true
  289. break
  290. }
  291. }
  292. if !hasMatched && len(parts[0]) == 40 {
  293. refName = parts[0]
  294. c.Repo.TreePath = strings.Join(parts[1:], "/")
  295. }
  296. if c.Repo.GitRepo.IsBranchExist(refName) {
  297. c.Repo.IsViewBranch = true
  298. c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName)
  299. if err != nil {
  300. c.Handle(500, "GetBranchCommit", err)
  301. return
  302. }
  303. c.Repo.CommitID = c.Repo.Commit.ID.String()
  304. } else if c.Repo.GitRepo.IsTagExist(refName) {
  305. c.Repo.IsViewTag = true
  306. c.Repo.Commit, err = c.Repo.GitRepo.GetTagCommit(refName)
  307. if err != nil {
  308. c.Handle(500, "GetTagCommit", err)
  309. return
  310. }
  311. c.Repo.CommitID = c.Repo.Commit.ID.String()
  312. } else if len(refName) == 40 {
  313. c.Repo.IsViewCommit = true
  314. c.Repo.CommitID = refName
  315. c.Repo.Commit, err = c.Repo.GitRepo.GetCommit(refName)
  316. if err != nil {
  317. c.NotFound()
  318. return
  319. }
  320. } else {
  321. c.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  322. return
  323. }
  324. }
  325. c.Repo.BranchName = refName
  326. c.Data["BranchName"] = c.Repo.BranchName
  327. c.Data["CommitID"] = c.Repo.CommitID
  328. c.Data["TreePath"] = c.Repo.TreePath
  329. c.Data["IsViewBranch"] = c.Repo.IsViewBranch
  330. c.Data["IsViewTag"] = c.Repo.IsViewTag
  331. c.Data["IsViewCommit"] = c.Repo.IsViewCommit
  332. // People who have push access or have fored repository can propose a new pull request.
  333. if c.Repo.IsWriter() || (c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID)) {
  334. // Pull request is allowed if this is a fork repository
  335. // and base repository accepts pull requests.
  336. if c.Repo.Repository.BaseRepo != nil {
  337. if c.Repo.Repository.BaseRepo.AllowsPulls() {
  338. c.Repo.PullRequest.Allowed = true
  339. // In-repository pull requests has higher priority than cross-repository if user is viewing
  340. // base repository and 1) has write access to it 2) has forked it.
  341. if c.Repo.IsWriter() {
  342. c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
  343. c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
  344. c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
  345. } else {
  346. c.Data["BaseRepo"] = c.Repo.Repository
  347. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  348. c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
  349. }
  350. }
  351. } else {
  352. // Or, this is repository accepts pull requests between branches.
  353. if c.Repo.Repository.AllowsPulls() {
  354. c.Data["BaseRepo"] = c.Repo.Repository
  355. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  356. c.Repo.PullRequest.Allowed = true
  357. c.Repo.PullRequest.SameRepo = true
  358. c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
  359. }
  360. }
  361. }
  362. c.Data["PullRequestCtx"] = c.Repo.PullRequest
  363. }
  364. }
  365. func RequireRepoAdmin() macaron.Handler {
  366. return func(c *Context) {
  367. if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
  368. c.NotFound()
  369. return
  370. }
  371. }
  372. }
  373. func RequireRepoWriter() macaron.Handler {
  374. return func(c *Context) {
  375. if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
  376. c.NotFound()
  377. return
  378. }
  379. }
  380. }
  381. // GitHookService checks if repository Git hooks service has been enabled.
  382. func GitHookService() macaron.Handler {
  383. return func(c *Context) {
  384. if !c.User.CanEditGitHook() {
  385. c.NotFound()
  386. return
  387. }
  388. }
  389. }