repo.go 12 KB

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