repo.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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.ACCESS_MODE_OWNER
  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.ACCESS_MODE_ADMIN
  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.ACCESS_MODE_WRITE
  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.ACCESS_MODE_READ
  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.ACCESS_MODE_OWNER
  148. } else {
  149. mode, err := db.UserAccessMode(c.UserID(), repo)
  150. if err != nil {
  151. c.Error(err, "get user access mode")
  152. return
  153. }
  154. c.Repo.AccessMode = mode
  155. }
  156. // Check access
  157. if c.Repo.AccessMode == db.ACCESS_MODE_NONE {
  158. // Redirect to any accessible page if not yet on it
  159. if repo.IsPartialPublic() &&
  160. (!(isIssuesPage || isWikiPage) ||
  161. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  162. (isWikiPage && !repo.CanGuestViewWiki())) {
  163. switch {
  164. case repo.CanGuestViewIssues():
  165. c.Redirect(repo.Link() + "/issues")
  166. case repo.CanGuestViewWiki():
  167. c.Redirect(repo.Link() + "/wiki")
  168. default:
  169. c.NotFound()
  170. }
  171. return
  172. }
  173. // Response 404 if user is on completely private repository or possible accessible page but owner doesn't enabled
  174. if !repo.IsPartialPublic() ||
  175. (isIssuesPage && !repo.CanGuestViewIssues()) ||
  176. (isWikiPage && !repo.CanGuestViewWiki()) {
  177. c.NotFound()
  178. return
  179. }
  180. c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
  181. c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
  182. }
  183. if repo.IsMirror {
  184. c.Repo.Mirror, err = db.GetMirrorByRepoID(repo.ID)
  185. if err != nil {
  186. c.Error(err, "get mirror by repository ID")
  187. return
  188. }
  189. c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune
  190. c.Data["MirrorInterval"] = c.Repo.Mirror.Interval
  191. c.Data["Mirror"] = c.Repo.Mirror
  192. }
  193. gitRepo, err := git.Open(db.RepoPath(ownerName, repoName))
  194. if err != nil {
  195. c.Error(err, "open repository")
  196. return
  197. }
  198. c.Repo.GitRepo = gitRepo
  199. tags, err := c.Repo.GitRepo.Tags()
  200. if err != nil {
  201. c.Error(err, "get tags")
  202. return
  203. }
  204. c.Data["Tags"] = tags
  205. c.Repo.Repository.NumTags = len(tags)
  206. c.Data["Title"] = owner.Name + "/" + repo.Name
  207. c.Data["Repository"] = repo
  208. c.Data["Owner"] = c.Repo.Repository.Owner
  209. c.Data["IsRepositoryOwner"] = c.Repo.IsOwner()
  210. c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin()
  211. c.Data["IsRepositoryWriter"] = c.Repo.IsWriter()
  212. c.Data["DisableSSH"] = conf.SSH.Disabled
  213. c.Data["DisableHTTP"] = conf.Repository.DisableHTTPGit
  214. c.Data["ShowHTTP"] = conf.Repository.ShowHTTPGit
  215. c.Data["CloneLink"] = repo.CloneLink()
  216. c.Data["WikiCloneLink"] = repo.WikiCloneLink()
  217. if c.IsLogged {
  218. c.Data["IsWatchingRepo"] = db.IsWatching(c.User.ID, repo.ID)
  219. c.Data["IsStaringRepo"] = db.IsStaring(c.User.ID, repo.ID)
  220. c.Data["HasForked"] = c.User.HasForkedRepo(c.Repo.Repository.ID)
  221. }
  222. // repo is bare and display enable
  223. if c.Repo.Repository.IsBare {
  224. return
  225. }
  226. c.Data["TagName"] = c.Repo.TagName
  227. branches, err := c.Repo.GitRepo.Branches()
  228. if err != nil {
  229. c.Error(err, "get branches")
  230. return
  231. }
  232. c.Data["Branches"] = branches
  233. c.Data["BrancheCount"] = len(branches)
  234. // If not branch selected, try default one.
  235. // If default branch doesn't exists, fall back to some other branch.
  236. if len(c.Repo.BranchName) == 0 {
  237. if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.HasBranch(c.Repo.Repository.DefaultBranch) {
  238. c.Repo.BranchName = c.Repo.Repository.DefaultBranch
  239. } else if len(branches) > 0 {
  240. c.Repo.BranchName = branches[0]
  241. }
  242. }
  243. c.Data["BranchName"] = c.Repo.BranchName
  244. c.Data["CommitID"] = c.Repo.CommitID
  245. c.Data["IsGuest"] = !c.Repo.HasAccess()
  246. hasDC := hasDataCite(c)
  247. c.Data["HasDataCite"] = hasDC
  248. if hasDC {
  249. c.Data["IsDOIReady"] = isDOIReady(c)
  250. }
  251. if doi := getRepoDOI(c); doi != "" && libgin.IsRegisteredDOI(doi) {
  252. c.Data["DOI"] = doi
  253. }
  254. }
  255. }
  256. // RepoRef handles repository reference name including those contain `/`.
  257. func RepoRef() macaron.Handler {
  258. return func(c *Context) {
  259. // Empty repository does not have reference information.
  260. if c.Repo.Repository.IsBare {
  261. return
  262. }
  263. var (
  264. refName string
  265. err error
  266. )
  267. // For API calls.
  268. if c.Repo.GitRepo == nil {
  269. repoPath := db.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
  270. c.Repo.GitRepo, err = git.Open(repoPath)
  271. if err != nil {
  272. c.Error(err, "open repository")
  273. return
  274. }
  275. }
  276. // Get default branch.
  277. if len(c.Params("*")) == 0 {
  278. refName = c.Repo.Repository.DefaultBranch
  279. if !c.Repo.GitRepo.HasBranch(refName) {
  280. branches, err := c.Repo.GitRepo.Branches()
  281. if err != nil {
  282. c.Error(err, "get branches")
  283. return
  284. }
  285. refName = branches[0]
  286. }
  287. c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
  288. if err != nil {
  289. c.Error(err, "get branch commit")
  290. return
  291. }
  292. c.Repo.CommitID = c.Repo.Commit.ID.String()
  293. c.Repo.IsViewBranch = true
  294. } else {
  295. hasMatched := false
  296. parts := strings.Split(c.Params("*"), "/")
  297. for i, part := range parts {
  298. refName = strings.TrimPrefix(refName+"/"+part, "/")
  299. if c.Repo.GitRepo.HasBranch(refName) ||
  300. c.Repo.GitRepo.HasTag(refName) {
  301. if i < len(parts)-1 {
  302. c.Repo.TreePath = strings.Join(parts[i+1:], "/")
  303. }
  304. hasMatched = true
  305. break
  306. }
  307. }
  308. if !hasMatched && len(parts[0]) == 40 {
  309. refName = parts[0]
  310. c.Repo.TreePath = strings.Join(parts[1:], "/")
  311. }
  312. if c.Repo.GitRepo.HasBranch(refName) {
  313. c.Repo.IsViewBranch = true
  314. c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
  315. if err != nil {
  316. c.Error(err, "get branch commit")
  317. return
  318. }
  319. c.Repo.CommitID = c.Repo.Commit.ID.String()
  320. } else if c.Repo.GitRepo.HasTag(refName) {
  321. c.Repo.IsViewTag = true
  322. c.Repo.Commit, err = c.Repo.GitRepo.TagCommit(refName)
  323. if err != nil {
  324. c.Error(err, "get tag commit")
  325. return
  326. }
  327. c.Repo.CommitID = c.Repo.Commit.ID.String()
  328. } else if len(refName) == 40 {
  329. c.Repo.IsViewCommit = true
  330. c.Repo.CommitID = refName
  331. c.Repo.Commit, err = c.Repo.GitRepo.CatFileCommit(refName)
  332. if err != nil {
  333. c.NotFound()
  334. return
  335. }
  336. } else {
  337. c.NotFound()
  338. return
  339. }
  340. }
  341. c.Repo.BranchName = refName
  342. c.Data["BranchName"] = c.Repo.BranchName
  343. c.Data["CommitID"] = c.Repo.CommitID
  344. c.Data["TreePath"] = c.Repo.TreePath
  345. c.Data["IsViewBranch"] = c.Repo.IsViewBranch
  346. c.Data["IsViewTag"] = c.Repo.IsViewTag
  347. c.Data["IsViewCommit"] = c.Repo.IsViewCommit
  348. // People who have push access or have fored repository can propose a new pull request.
  349. if c.Repo.IsWriter() || (c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID)) {
  350. // Pull request is allowed if this is a fork repository
  351. // and base repository accepts pull requests.
  352. if c.Repo.Repository.BaseRepo != nil {
  353. if c.Repo.Repository.BaseRepo.AllowsPulls() {
  354. c.Repo.PullRequest.Allowed = true
  355. // In-repository pull requests has higher priority than cross-repository if user is viewing
  356. // base repository and 1) has write access to it 2) has forked it.
  357. if c.Repo.IsWriter() {
  358. c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
  359. c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
  360. c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
  361. } else {
  362. c.Data["BaseRepo"] = c.Repo.Repository
  363. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  364. c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
  365. }
  366. }
  367. } else {
  368. // Or, this is repository accepts pull requests between branches.
  369. if c.Repo.Repository.AllowsPulls() {
  370. c.Data["BaseRepo"] = c.Repo.Repository
  371. c.Repo.PullRequest.BaseRepo = c.Repo.Repository
  372. c.Repo.PullRequest.Allowed = true
  373. c.Repo.PullRequest.SameRepo = true
  374. c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
  375. }
  376. }
  377. }
  378. c.Data["PullRequestCtx"] = c.Repo.PullRequest
  379. }
  380. }
  381. func RequireRepoAdmin() macaron.Handler {
  382. return func(c *Context) {
  383. if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
  384. c.NotFound()
  385. return
  386. }
  387. }
  388. }
  389. func RequireRepoWriter() macaron.Handler {
  390. return func(c *Context) {
  391. if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
  392. c.NotFound()
  393. return
  394. }
  395. }
  396. }
  397. // GitHookService checks if repository Git hooks service has been enabled.
  398. func GitHookService() macaron.Handler {
  399. return func(c *Context) {
  400. if !c.User.CanEditGitHook() {
  401. c.NotFound()
  402. return
  403. }
  404. }
  405. }