You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. "code.gitea.io/git"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/setting"
  13. "github.com/Unknwon/com"
  14. editorconfig "gopkg.in/editorconfig/editorconfig-core-go.v1"
  15. macaron "gopkg.in/macaron.v1"
  16. )
  17. // PullRequest contains informations to make a pull request
  18. type PullRequest struct {
  19. BaseRepo *models.Repository
  20. Allowed bool
  21. SameRepo bool
  22. HeadInfo string // [<user>:]<branch>
  23. }
  24. // Repository contains information to operate a repository
  25. type Repository struct {
  26. AccessMode models.AccessMode
  27. IsWatching bool
  28. IsViewBranch bool
  29. IsViewTag bool
  30. IsViewCommit bool
  31. Repository *models.Repository
  32. Owner *models.User
  33. Commit *git.Commit
  34. Tag *git.Tag
  35. GitRepo *git.Repository
  36. BranchName string
  37. TagName string
  38. TreePath string
  39. CommitID string
  40. RepoLink string
  41. CloneLink models.CloneLink
  42. CommitsCount int64
  43. Mirror *models.Mirror
  44. PullRequest *PullRequest
  45. }
  46. // IsOwner returns true if current user is the owner of repository.
  47. func (r *Repository) IsOwner() bool {
  48. return r.AccessMode >= models.AccessModeOwner
  49. }
  50. // IsAdmin returns true if current user has admin or higher access of repository.
  51. func (r *Repository) IsAdmin() bool {
  52. return r.AccessMode >= models.AccessModeAdmin
  53. }
  54. // IsWriter returns true if current user has write or higher access of repository.
  55. func (r *Repository) IsWriter() bool {
  56. return r.AccessMode >= models.AccessModeWrite
  57. }
  58. // HasAccess returns true if the current user has at least read access for this repository
  59. func (r *Repository) HasAccess() bool {
  60. return r.AccessMode >= models.AccessModeRead
  61. }
  62. // CanEnableEditor returns true if repository is editable and user has proper access level.
  63. func (r *Repository) CanEnableEditor() bool {
  64. return r.Repository.CanEnableEditor() && r.IsViewBranch && r.IsWriter()
  65. }
  66. // CanCommitToBranch returns true if repository is editable and user has proper access level
  67. // and branch is not protected
  68. func (r *Repository) CanCommitToBranch() (bool, error) {
  69. protectedBranch, err := r.Repository.IsProtectedBranch(r.BranchName)
  70. if err != nil {
  71. return false, err
  72. }
  73. return r.CanEnableEditor() && !protectedBranch, nil
  74. }
  75. // GetEditorconfig returns the .editorconfig definition if found in the
  76. // HEAD of the default repo branch.
  77. func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) {
  78. commit, err := r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  79. if err != nil {
  80. return nil, err
  81. }
  82. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  83. if err != nil {
  84. return nil, err
  85. }
  86. reader, err := treeEntry.Blob().Data()
  87. if err != nil {
  88. return nil, err
  89. }
  90. data, err := ioutil.ReadAll(reader)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return editorconfig.ParseBytes(data)
  95. }
  96. // RetrieveBaseRepo retrieves base repository
  97. func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
  98. // Non-fork repository will not return error in this method.
  99. if err := repo.GetBaseRepo(); err != nil {
  100. if models.IsErrRepoNotExist(err) {
  101. repo.IsFork = false
  102. repo.ForkID = 0
  103. return
  104. }
  105. ctx.Handle(500, "GetBaseRepo", err)
  106. return
  107. } else if err = repo.BaseRepo.GetOwner(); err != nil {
  108. ctx.Handle(500, "BaseRepo.GetOwner", err)
  109. return
  110. }
  111. }
  112. // composeGoGetImport returns go-get-import meta content.
  113. func composeGoGetImport(owner, repo string) string {
  114. return path.Join(setting.Domain, setting.AppSubURL, owner, repo)
  115. }
  116. // earlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  117. // if user does not have actual access to the requested repository,
  118. // or the owner or repository does not exist at all.
  119. // This is particular a workaround for "go get" command which does not respect
  120. // .netrc file.
  121. func earlyResponseForGoGetMeta(ctx *Context) {
  122. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  123. map[string]string{
  124. "GoGetImport": composeGoGetImport(ctx.Params(":username"), strings.TrimSuffix(ctx.Params(":reponame"), ".git")),
  125. "CloneLink": models.ComposeHTTPSCloneURL(ctx.Params(":username"), ctx.Params(":reponame")),
  126. })))
  127. }
  128. // RedirectToRepo redirect to a differently-named repository
  129. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  130. ownerName := ctx.Params(":username")
  131. previousRepoName := ctx.Params(":reponame")
  132. repo, err := models.GetRepositoryByID(redirectRepoID)
  133. if err != nil {
  134. ctx.Handle(500, "GetRepositoryByID", err)
  135. return
  136. }
  137. redirectPath := strings.Replace(
  138. ctx.Req.URL.Path,
  139. fmt.Sprintf("%s/%s", ownerName, previousRepoName),
  140. fmt.Sprintf("%s/%s", ownerName, repo.Name),
  141. 1,
  142. )
  143. ctx.Redirect(redirectPath)
  144. }
  145. // RepoAssignment returns a macaron to handle repository assignment
  146. func RepoAssignment() macaron.Handler {
  147. return func(ctx *Context) {
  148. var (
  149. owner *models.User
  150. err error
  151. )
  152. userName := ctx.Params(":username")
  153. repoName := ctx.Params(":reponame")
  154. // Check if the user is the same as the repository owner
  155. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  156. owner = ctx.User
  157. } else {
  158. owner, err = models.GetUserByName(userName)
  159. if err != nil {
  160. if models.IsErrUserNotExist(err) {
  161. if ctx.Query("go-get") == "1" {
  162. earlyResponseForGoGetMeta(ctx)
  163. return
  164. }
  165. ctx.Handle(404, "GetUserByName", nil)
  166. } else {
  167. ctx.Handle(500, "GetUserByName", err)
  168. }
  169. return
  170. }
  171. }
  172. ctx.Repo.Owner = owner
  173. ctx.Data["Username"] = ctx.Repo.Owner.Name
  174. // Get repository.
  175. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  176. if err != nil {
  177. if models.IsErrRepoNotExist(err) {
  178. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  179. if err == nil {
  180. RedirectToRepo(ctx, redirectRepoID)
  181. } else if models.IsErrRepoRedirectNotExist(err) {
  182. if ctx.Query("go-get") == "1" {
  183. earlyResponseForGoGetMeta(ctx)
  184. return
  185. }
  186. ctx.Handle(404, "GetRepositoryByName", nil)
  187. } else {
  188. ctx.Handle(500, "LookupRepoRedirect", err)
  189. }
  190. } else {
  191. ctx.Handle(500, "GetRepositoryByName", err)
  192. }
  193. return
  194. }
  195. repo.Owner = owner
  196. // Admin has super access.
  197. if ctx.IsSigned && ctx.User.IsAdmin {
  198. ctx.Repo.AccessMode = models.AccessModeOwner
  199. } else {
  200. var userID int64
  201. if ctx.User != nil {
  202. userID = ctx.User.ID
  203. }
  204. mode, err := models.AccessLevel(userID, repo)
  205. if err != nil {
  206. ctx.Handle(500, "AccessLevel", err)
  207. return
  208. }
  209. ctx.Repo.AccessMode = mode
  210. }
  211. // Check access.
  212. if ctx.Repo.AccessMode == models.AccessModeNone {
  213. if ctx.Query("go-get") == "1" {
  214. earlyResponseForGoGetMeta(ctx)
  215. return
  216. }
  217. ctx.Handle(404, "no access right", err)
  218. return
  219. }
  220. ctx.Data["HasAccess"] = true
  221. if repo.IsMirror {
  222. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  223. if err != nil {
  224. ctx.Handle(500, "GetMirror", err)
  225. return
  226. }
  227. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  228. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  229. ctx.Data["Mirror"] = ctx.Repo.Mirror
  230. }
  231. ctx.Repo.Repository = repo
  232. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  233. ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare
  234. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  235. if err != nil {
  236. ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  237. return
  238. }
  239. ctx.Repo.GitRepo = gitRepo
  240. ctx.Repo.RepoLink = repo.Link()
  241. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  242. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  243. tags, err := ctx.Repo.GitRepo.GetTags()
  244. if err != nil {
  245. ctx.Handle(500, "GetTags", err)
  246. return
  247. }
  248. ctx.Data["Tags"] = tags
  249. count, err := models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  250. IncludeDrafts: false,
  251. })
  252. if err != nil {
  253. ctx.Handle(500, "GetReleaseCountByRepoID", err)
  254. return
  255. }
  256. ctx.Repo.Repository.NumReleases = int(count)
  257. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  258. ctx.Data["Repository"] = repo
  259. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  260. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  261. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  262. ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter()
  263. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  264. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  265. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  266. ctx.Data["CloneLink"] = repo.CloneLink()
  267. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  268. if ctx.IsSigned {
  269. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  270. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  271. }
  272. // repo is bare and display enable
  273. if ctx.Repo.Repository.IsBare {
  274. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  275. return
  276. }
  277. ctx.Data["TagName"] = ctx.Repo.TagName
  278. brs, err := ctx.Repo.GitRepo.GetBranches()
  279. if err != nil {
  280. ctx.Handle(500, "GetBranches", err)
  281. return
  282. }
  283. ctx.Data["Branches"] = brs
  284. ctx.Data["BrancheCount"] = len(brs)
  285. // If not branch selected, try default one.
  286. // If default branch doesn't exists, fall back to some other branch.
  287. if len(ctx.Repo.BranchName) == 0 {
  288. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  289. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  290. } else if len(brs) > 0 {
  291. ctx.Repo.BranchName = brs[0]
  292. }
  293. }
  294. ctx.Data["BranchName"] = ctx.Repo.BranchName
  295. ctx.Data["CommitID"] = ctx.Repo.CommitID
  296. if repo.IsFork {
  297. RetrieveBaseRepo(ctx, repo)
  298. if ctx.Written() {
  299. return
  300. }
  301. }
  302. // People who have push access or have forked repository can propose a new pull request.
  303. if ctx.Repo.IsWriter() || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  304. // Pull request is allowed if this is a fork repository
  305. // and base repository accepts pull requests.
  306. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  307. ctx.Data["BaseRepo"] = repo.BaseRepo
  308. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  309. ctx.Repo.PullRequest.Allowed = true
  310. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  311. } else {
  312. // Or, this is repository accepts pull requests between branches.
  313. if repo.AllowsPulls() {
  314. ctx.Data["BaseRepo"] = repo
  315. ctx.Repo.PullRequest.BaseRepo = repo
  316. ctx.Repo.PullRequest.Allowed = true
  317. ctx.Repo.PullRequest.SameRepo = true
  318. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  319. }
  320. }
  321. // Reset repo units as otherwise user specific units wont be loaded later
  322. ctx.Repo.Repository.Units = nil
  323. }
  324. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  325. if ctx.Query("go-get") == "1" {
  326. ctx.Data["GoGetImport"] = composeGoGetImport(owner.Name, repo.Name)
  327. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName)
  328. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  329. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  330. }
  331. }
  332. }
  333. // RepoRef handles repository reference name including those contain `/`.
  334. func RepoRef() macaron.Handler {
  335. return func(ctx *Context) {
  336. // Empty repository does not have reference information.
  337. if ctx.Repo.Repository.IsBare {
  338. return
  339. }
  340. var (
  341. refName string
  342. err error
  343. )
  344. // For API calls.
  345. if ctx.Repo.GitRepo == nil {
  346. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  347. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  348. if err != nil {
  349. ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  350. return
  351. }
  352. }
  353. // Get default branch.
  354. if len(ctx.Params("*")) == 0 {
  355. refName = ctx.Repo.Repository.DefaultBranch
  356. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  357. brs, err := ctx.Repo.GitRepo.GetBranches()
  358. if err != nil {
  359. ctx.Handle(500, "GetBranches", err)
  360. return
  361. } else if len(brs) == 0 {
  362. err = fmt.Errorf("No branches in non-bare repository %s",
  363. ctx.Repo.GitRepo.Path)
  364. ctx.Handle(500, "GetBranches", err)
  365. return
  366. }
  367. refName = brs[0]
  368. }
  369. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  370. if err != nil {
  371. ctx.Handle(500, "GetBranchCommit", err)
  372. return
  373. }
  374. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  375. ctx.Repo.IsViewBranch = true
  376. } else {
  377. hasMatched := false
  378. parts := strings.Split(ctx.Params("*"), "/")
  379. for i, part := range parts {
  380. refName = strings.TrimPrefix(refName+"/"+part, "/")
  381. if ctx.Repo.GitRepo.IsBranchExist(refName) ||
  382. ctx.Repo.GitRepo.IsTagExist(refName) {
  383. if i < len(parts)-1 {
  384. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  385. }
  386. hasMatched = true
  387. break
  388. }
  389. }
  390. if !hasMatched && len(parts[0]) == 40 {
  391. refName = parts[0]
  392. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  393. }
  394. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  395. ctx.Repo.IsViewBranch = true
  396. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  397. if err != nil {
  398. ctx.Handle(500, "GetBranchCommit", err)
  399. return
  400. }
  401. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  402. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  403. ctx.Repo.IsViewTag = true
  404. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  405. if err != nil {
  406. ctx.Handle(500, "GetTagCommit", err)
  407. return
  408. }
  409. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  410. } else if len(refName) == 40 {
  411. ctx.Repo.IsViewCommit = true
  412. ctx.Repo.CommitID = refName
  413. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  414. if err != nil {
  415. ctx.Handle(404, "GetCommit", nil)
  416. return
  417. }
  418. } else {
  419. ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  420. return
  421. }
  422. }
  423. ctx.Repo.BranchName = refName
  424. ctx.Data["BranchName"] = ctx.Repo.BranchName
  425. ctx.Data["CommitID"] = ctx.Repo.CommitID
  426. ctx.Data["TreePath"] = ctx.Repo.TreePath
  427. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  428. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  429. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  430. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  431. if err != nil {
  432. ctx.Handle(500, "CommitsCount", err)
  433. return
  434. }
  435. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  436. }
  437. }
  438. // RequireRepoAdmin returns a macaron middleware for requiring repository admin permission
  439. func RequireRepoAdmin() macaron.Handler {
  440. return func(ctx *Context) {
  441. if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) {
  442. ctx.Handle(404, ctx.Req.RequestURI, nil)
  443. return
  444. }
  445. }
  446. }
  447. // RequireRepoWriter returns a macaron middleware for requiring repository write permission
  448. func RequireRepoWriter() macaron.Handler {
  449. return func(ctx *Context) {
  450. if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) {
  451. ctx.Handle(404, ctx.Req.RequestURI, nil)
  452. return
  453. }
  454. }
  455. }
  456. // LoadRepoUnits loads repsitory's units, it should be called after repository and user loaded
  457. func LoadRepoUnits() macaron.Handler {
  458. return func(ctx *Context) {
  459. var isAdmin bool
  460. if ctx.User != nil && ctx.User.IsAdmin {
  461. isAdmin = true
  462. }
  463. var userID int64
  464. if ctx.User != nil {
  465. userID = ctx.User.ID
  466. }
  467. err := ctx.Repo.Repository.LoadUnitsByUserID(userID, isAdmin)
  468. if err != nil {
  469. ctx.Handle(500, "LoadUnitsByUserID", err)
  470. return
  471. }
  472. }
  473. }
  474. // CheckUnit will check whether
  475. func CheckUnit(unitType models.UnitType) macaron.Handler {
  476. return func(ctx *Context) {
  477. if !ctx.Repo.Repository.UnitEnabled(unitType) {
  478. ctx.Handle(404, "CheckUnit", fmt.Errorf("%s: %v", ctx.Tr("units.error.unit_not_allowed"), unitType))
  479. }
  480. }
  481. }
  482. // GitHookService checks if repository Git hooks service has been enabled.
  483. func GitHookService() macaron.Handler {
  484. return func(ctx *Context) {
  485. if !ctx.User.CanEditGitHook() {
  486. ctx.Handle(404, "GitHookService", nil)
  487. return
  488. }
  489. }
  490. }
  491. // UnitTypes returns a macaron middleware to set unit types to context variables.
  492. func UnitTypes() macaron.Handler {
  493. return func(ctx *Context) {
  494. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  495. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  496. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  497. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  498. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  499. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  500. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  501. }
  502. }