repo.go 12 KB

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