repo.go 12 KB

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