repo.go 13 KB

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