repo.go 13 KB

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