repo.go 13 KB

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