repo.go 13 KB

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