repo.go 13 KB

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