repo.go 14 KB

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