repo.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. "path"
  9. "strings"
  10. "github.com/Unknwon/com"
  11. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  12. "gopkg.in/macaron.v1"
  13. "github.com/gogits/git-module"
  14. "github.com/gogits/gogs/models"
  15. "github.com/gogits/gogs/models/errors"
  16. "github.com/gogits/gogs/modules/setting"
  17. )
  18. type PullRequest struct {
  19. BaseRepo *models.Repository
  20. Allowed bool
  21. SameRepo bool
  22. HeadInfo string // [<user>:]<branch>
  23. }
  24. type Repository struct {
  25. AccessMode models.AccessMode
  26. IsWatching bool
  27. IsViewBranch bool
  28. IsViewTag bool
  29. IsViewCommit bool
  30. Repository *models.Repository
  31. Owner *models.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 models.CloneLink
  41. CommitsCount int64
  42. Mirror *models.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 >= models.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 >= models.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 >= models.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 >= models.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. // PullRequestURL returns URL for composing a pull request.
  87. // This function does not check if the repository can actually compose a pull request.
  88. func (r *Repository) PullRequestURL(baseBranch, headBranch string) string {
  89. repoLink := r.RepoLink
  90. if r.PullRequest.BaseRepo != nil {
  91. repoLink = r.PullRequest.BaseRepo.Link()
  92. }
  93. return fmt.Sprintf("%s/compare/%s...%s:%s", repoLink, baseBranch, r.Owner.Name, headBranch)
  94. }
  95. // composeGoGetImport returns go-get-import meta content.
  96. func composeGoGetImport(owner, repo string) string {
  97. return path.Join(setting.Domain, setting.AppSubUrl, owner, repo)
  98. }
  99. // earlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  100. // if user does not have actual access to the requested repository,
  101. // or the owner or repository does not exist at all.
  102. // This is particular a workaround for "go get" command which does not respect
  103. // .netrc file.
  104. func earlyResponseForGoGetMeta(ctx *Context) {
  105. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  106. map[string]string{
  107. "GoGetImport": composeGoGetImport(ctx.Params(":username"), ctx.Params(":reponame")),
  108. "CloneLink": models.ComposeHTTPSCloneURL(ctx.Params(":username"), ctx.Params(":reponame")),
  109. })))
  110. }
  111. func RepoAssignment() macaron.Handler {
  112. return func(ctx *Context) {
  113. var (
  114. owner *models.User
  115. err error
  116. )
  117. ownerName := ctx.Params(":username")
  118. repoName := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  119. refName := ctx.Params(":branchname")
  120. if len(refName) == 0 {
  121. refName = ctx.Params(":path")
  122. }
  123. // Check if the user is the same as the repository owner
  124. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(ownerName) {
  125. owner = ctx.User
  126. } else {
  127. owner, err = models.GetUserByName(ownerName)
  128. if err != nil {
  129. if errors.IsUserNotExist(err) {
  130. if ctx.Query("go-get") == "1" {
  131. earlyResponseForGoGetMeta(ctx)
  132. return
  133. }
  134. ctx.NotFound()
  135. } else {
  136. ctx.Handle(500, "GetUserByName", err)
  137. }
  138. return
  139. }
  140. }
  141. ctx.Repo.Owner = owner
  142. ctx.Data["Username"] = ctx.Repo.Owner.Name
  143. // Get repository.
  144. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  145. if err != nil {
  146. if errors.IsRepoNotExist(err) {
  147. if ctx.Query("go-get") == "1" {
  148. earlyResponseForGoGetMeta(ctx)
  149. return
  150. }
  151. ctx.NotFound()
  152. } else {
  153. ctx.Handle(500, "GetRepositoryByName", err)
  154. }
  155. return
  156. } else if err = repo.GetOwner(); err != nil {
  157. ctx.Handle(500, "GetOwner", err)
  158. return
  159. }
  160. // Admin has super access.
  161. if ctx.IsSigned && ctx.User.IsAdmin {
  162. ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER
  163. } else {
  164. var userID int64
  165. if ctx.IsSigned {
  166. userID = ctx.User.ID
  167. }
  168. mode, err := models.AccessLevel(userID, repo)
  169. if err != nil {
  170. ctx.Handle(500, "AccessLevel", err)
  171. return
  172. }
  173. ctx.Repo.AccessMode = mode
  174. }
  175. // Check access.
  176. if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE {
  177. if ctx.Query("go-get") == "1" {
  178. earlyResponseForGoGetMeta(ctx)
  179. return
  180. }
  181. ctx.NotFound()
  182. return
  183. }
  184. ctx.Data["HasAccess"] = true
  185. if repo.IsMirror {
  186. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  187. if err != nil {
  188. ctx.Handle(500, "GetMirror", err)
  189. return
  190. }
  191. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  192. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  193. ctx.Data["Mirror"] = ctx.Repo.Mirror
  194. }
  195. ctx.Repo.Repository = repo
  196. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  197. ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare
  198. gitRepo, err := git.OpenRepository(models.RepoPath(ownerName, repoName))
  199. if err != nil {
  200. ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(ownerName, repoName), err)
  201. return
  202. }
  203. ctx.Repo.GitRepo = gitRepo
  204. ctx.Repo.RepoLink = repo.Link()
  205. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  206. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  207. tags, err := ctx.Repo.GitRepo.GetTags()
  208. if err != nil {
  209. ctx.Handle(500, fmt.Sprintf("GetTags '%s'", ctx.Repo.Repository.RepoPath()), err)
  210. return
  211. }
  212. ctx.Data["Tags"] = tags
  213. ctx.Repo.Repository.NumTags = len(tags)
  214. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  215. ctx.Data["Repository"] = repo
  216. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  217. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  218. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  219. ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter()
  220. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  221. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  222. ctx.Data["CloneLink"] = repo.CloneLink()
  223. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  224. if ctx.IsSigned {
  225. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  226. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  227. }
  228. // repo is bare and display enable
  229. if ctx.Repo.Repository.IsBare {
  230. return
  231. }
  232. ctx.Data["TagName"] = ctx.Repo.TagName
  233. brs, err := ctx.Repo.GitRepo.GetBranches()
  234. if err != nil {
  235. ctx.Handle(500, "GetBranches", err)
  236. return
  237. }
  238. ctx.Data["Branches"] = brs
  239. ctx.Data["BrancheCount"] = len(brs)
  240. // If not branch selected, try default one.
  241. // If default branch doesn't exists, fall back to some other branch.
  242. if len(ctx.Repo.BranchName) == 0 {
  243. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  244. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  245. } else if len(brs) > 0 {
  246. ctx.Repo.BranchName = brs[0]
  247. }
  248. }
  249. ctx.Data["BranchName"] = ctx.Repo.BranchName
  250. ctx.Data["CommitID"] = ctx.Repo.CommitID
  251. if ctx.Query("go-get") == "1" {
  252. ctx.Data["GoGetImport"] = composeGoGetImport(owner.Name, repo.Name)
  253. prefix := setting.AppUrl + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName)
  254. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  255. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  256. }
  257. }
  258. }
  259. // RepoRef handles repository reference name including those contain `/`.
  260. func RepoRef() macaron.Handler {
  261. return func(ctx *Context) {
  262. // Empty repository does not have reference information.
  263. if ctx.Repo.Repository.IsBare {
  264. return
  265. }
  266. var (
  267. refName string
  268. err error
  269. )
  270. // For API calls.
  271. if ctx.Repo.GitRepo == nil {
  272. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  273. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  274. if err != nil {
  275. ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  276. return
  277. }
  278. }
  279. // Get default branch.
  280. if len(ctx.Params("*")) == 0 {
  281. refName = ctx.Repo.Repository.DefaultBranch
  282. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  283. brs, err := ctx.Repo.GitRepo.GetBranches()
  284. if err != nil {
  285. ctx.Handle(500, "GetBranches", err)
  286. return
  287. }
  288. refName = brs[0]
  289. }
  290. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  291. if err != nil {
  292. ctx.Handle(500, "GetBranchCommit", err)
  293. return
  294. }
  295. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  296. ctx.Repo.IsViewBranch = true
  297. } else {
  298. hasMatched := false
  299. parts := strings.Split(ctx.Params("*"), "/")
  300. for i, part := range parts {
  301. refName = strings.TrimPrefix(refName+"/"+part, "/")
  302. if ctx.Repo.GitRepo.IsBranchExist(refName) ||
  303. ctx.Repo.GitRepo.IsTagExist(refName) {
  304. if i < len(parts)-1 {
  305. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  306. }
  307. hasMatched = true
  308. break
  309. }
  310. }
  311. if !hasMatched && len(parts[0]) == 40 {
  312. refName = parts[0]
  313. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  314. }
  315. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  316. ctx.Repo.IsViewBranch = true
  317. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  318. if err != nil {
  319. ctx.Handle(500, "GetBranchCommit", err)
  320. return
  321. }
  322. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  323. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  324. ctx.Repo.IsViewTag = true
  325. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  326. if err != nil {
  327. ctx.Handle(500, "GetTagCommit", err)
  328. return
  329. }
  330. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  331. } else if len(refName) == 40 {
  332. ctx.Repo.IsViewCommit = true
  333. ctx.Repo.CommitID = refName
  334. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  335. if err != nil {
  336. ctx.NotFound()
  337. return
  338. }
  339. } else {
  340. ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  341. return
  342. }
  343. }
  344. ctx.Repo.BranchName = refName
  345. ctx.Data["BranchName"] = ctx.Repo.BranchName
  346. ctx.Data["CommitID"] = ctx.Repo.CommitID
  347. ctx.Data["TreePath"] = ctx.Repo.TreePath
  348. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  349. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  350. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  351. // People who have push access or have fored repository can propose a new pull request.
  352. if ctx.Repo.IsWriter() || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  353. // Pull request is allowed if this is a fork repository
  354. // and base repository accepts pull requests.
  355. if ctx.Repo.Repository.BaseRepo != nil {
  356. if ctx.Repo.Repository.BaseRepo.AllowsPulls() {
  357. ctx.Repo.PullRequest.Allowed = true
  358. // In-repository pull requests has higher priority than cross-repository if user is viewing
  359. // base repository and 1) has write access to it 2) has forked it.
  360. if ctx.Repo.IsWriter() {
  361. ctx.Data["BaseRepo"] = ctx.Repo.Repository.BaseRepo
  362. ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository.BaseRepo
  363. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  364. } else {
  365. ctx.Data["BaseRepo"] = ctx.Repo.Repository
  366. ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository
  367. ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName
  368. }
  369. }
  370. } else {
  371. // Or, this is repository accepts pull requests between branches.
  372. if ctx.Repo.Repository.AllowsPulls() {
  373. ctx.Data["BaseRepo"] = ctx.Repo.Repository
  374. ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository
  375. ctx.Repo.PullRequest.Allowed = true
  376. ctx.Repo.PullRequest.SameRepo = true
  377. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  378. }
  379. }
  380. }
  381. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  382. }
  383. }
  384. func RequireRepoAdmin() macaron.Handler {
  385. return func(ctx *Context) {
  386. if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) {
  387. ctx.NotFound()
  388. return
  389. }
  390. }
  391. }
  392. func RequireRepoWriter() macaron.Handler {
  393. return func(ctx *Context) {
  394. if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) {
  395. ctx.NotFound()
  396. return
  397. }
  398. }
  399. }
  400. // GitHookService checks if repository Git hooks service has been enabled.
  401. func GitHookService() macaron.Handler {
  402. return func(ctx *Context) {
  403. if !ctx.User.CanEditGitHook() {
  404. ctx.NotFound()
  405. return
  406. }
  407. }
  408. }