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 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "context"
  8. "fmt"
  9. "html"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "path"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/models/db"
  17. git_model "code.gitea.io/gitea/models/git"
  18. issues_model "code.gitea.io/gitea/models/issues"
  19. access_model "code.gitea.io/gitea/models/perm/access"
  20. repo_model "code.gitea.io/gitea/models/repo"
  21. unit_model "code.gitea.io/gitea/models/unit"
  22. user_model "code.gitea.io/gitea/models/user"
  23. "code.gitea.io/gitea/modules/cache"
  24. "code.gitea.io/gitea/modules/git"
  25. code_indexer "code.gitea.io/gitea/modules/indexer/code"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup/markdown"
  28. repo_module "code.gitea.io/gitea/modules/repository"
  29. "code.gitea.io/gitea/modules/setting"
  30. api "code.gitea.io/gitea/modules/structs"
  31. "code.gitea.io/gitea/modules/util"
  32. asymkey_service "code.gitea.io/gitea/services/asymkey"
  33. "github.com/editorconfig/editorconfig-core-go/v2"
  34. )
  35. // IssueTemplateDirCandidates issue templates directory
  36. var IssueTemplateDirCandidates = []string{
  37. "ISSUE_TEMPLATE",
  38. "issue_template",
  39. ".gitea/ISSUE_TEMPLATE",
  40. ".gitea/issue_template",
  41. ".github/ISSUE_TEMPLATE",
  42. ".github/issue_template",
  43. ".gitlab/ISSUE_TEMPLATE",
  44. ".gitlab/issue_template",
  45. }
  46. // PullRequest contains information to make a pull request
  47. type PullRequest struct {
  48. BaseRepo *repo_model.Repository
  49. Allowed bool
  50. SameRepo bool
  51. HeadInfoSubURL string // [<user>:]<branch> url segment
  52. }
  53. // Repository contains information to operate a repository
  54. type Repository struct {
  55. access_model.Permission
  56. IsWatching bool
  57. IsViewBranch bool
  58. IsViewTag bool
  59. IsViewCommit bool
  60. Repository *repo_model.Repository
  61. Owner *user_model.User
  62. Commit *git.Commit
  63. Tag *git.Tag
  64. GitRepo *git.Repository
  65. RefName string
  66. BranchName string
  67. TagName string
  68. TreePath string
  69. CommitID string
  70. RepoLink string
  71. CloneLink repo_model.CloneLink
  72. CommitsCount int64
  73. Mirror *repo_model.Mirror
  74. PullRequest *PullRequest
  75. }
  76. // CanWriteToBranch checks if the branch is writable by the user
  77. func (r *Repository) CanWriteToBranch(user *user_model.User, branch string) bool {
  78. return issues_model.CanMaintainerWriteToBranch(r.Permission, branch, user)
  79. }
  80. // CanEnableEditor returns true if repository is editable and user has proper access level.
  81. func (r *Repository) CanEnableEditor(user *user_model.User) bool {
  82. return r.IsViewBranch && r.CanWriteToBranch(user, r.BranchName) && r.Repository.CanEnableEditor() && !r.Repository.IsArchived
  83. }
  84. // CanCreateBranch returns true if repository is editable and user has proper access level.
  85. func (r *Repository) CanCreateBranch() bool {
  86. return r.Permission.CanWrite(unit_model.TypeCode) && r.Repository.CanCreateBranch()
  87. }
  88. // RepoMustNotBeArchived checks if a repo is archived
  89. func RepoMustNotBeArchived() func(ctx *Context) {
  90. return func(ctx *Context) {
  91. if ctx.Repo.Repository.IsArchived {
  92. ctx.NotFound("IsArchived", fmt.Errorf(ctx.Tr("repo.archive.title")))
  93. }
  94. }
  95. }
  96. // CanCommitToBranchResults represents the results of CanCommitToBranch
  97. type CanCommitToBranchResults struct {
  98. CanCommitToBranch bool
  99. EditorEnabled bool
  100. UserCanPush bool
  101. RequireSigned bool
  102. WillSign bool
  103. SigningKey string
  104. WontSignReason string
  105. }
  106. // CanCommitToBranch returns true if repository is editable and user has proper access level
  107. // and branch is not protected for push
  108. func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error) {
  109. protectedBranch, err := git_model.GetProtectedBranchBy(ctx, r.Repository.ID, r.BranchName)
  110. if err != nil {
  111. return CanCommitToBranchResults{}, err
  112. }
  113. userCanPush := true
  114. requireSigned := false
  115. if protectedBranch != nil {
  116. userCanPush = protectedBranch.CanUserPush(doer.ID)
  117. requireSigned = protectedBranch.RequireSignedCommits
  118. }
  119. sign, keyID, _, err := asymkey_service.SignCRUDAction(ctx, r.Repository.RepoPath(), doer, r.Repository.RepoPath(), git.BranchPrefix+r.BranchName)
  120. canCommit := r.CanEnableEditor(doer) && userCanPush
  121. if requireSigned {
  122. canCommit = canCommit && sign
  123. }
  124. wontSignReason := ""
  125. if err != nil {
  126. if asymkey_service.IsErrWontSign(err) {
  127. wontSignReason = string(err.(*asymkey_service.ErrWontSign).Reason)
  128. err = nil
  129. } else {
  130. wontSignReason = "error"
  131. }
  132. }
  133. return CanCommitToBranchResults{
  134. CanCommitToBranch: canCommit,
  135. EditorEnabled: r.CanEnableEditor(doer),
  136. UserCanPush: userCanPush,
  137. RequireSigned: requireSigned,
  138. WillSign: sign,
  139. SigningKey: keyID,
  140. WontSignReason: wontSignReason,
  141. }, err
  142. }
  143. // CanUseTimetracker returns whether or not a user can use the timetracker.
  144. func (r *Repository) CanUseTimetracker(issue *issues_model.Issue, user *user_model.User) bool {
  145. // Checking for following:
  146. // 1. Is timetracker enabled
  147. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  148. isAssigned, _ := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user)
  149. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  150. r.Permission.CanWriteIssuesOrPulls(issue.IsPull) || issue.IsPoster(user.ID) || isAssigned)
  151. }
  152. // CanCreateIssueDependencies returns whether or not a user can create dependencies.
  153. func (r *Repository) CanCreateIssueDependencies(user *user_model.User, isPull bool) bool {
  154. return r.Repository.IsDependenciesEnabled() && r.Permission.CanWriteIssuesOrPulls(isPull)
  155. }
  156. // GetCommitsCount returns cached commit count for current view
  157. func (r *Repository) GetCommitsCount() (int64, error) {
  158. var contextName string
  159. if r.IsViewBranch {
  160. contextName = r.BranchName
  161. } else if r.IsViewTag {
  162. contextName = r.TagName
  163. } else {
  164. contextName = r.CommitID
  165. }
  166. return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) {
  167. return r.Commit.CommitsCount()
  168. })
  169. }
  170. // GetCommitGraphsCount returns cached commit count for current view
  171. func (r *Repository) GetCommitGraphsCount(ctx context.Context, hidePRRefs bool, branches, files []string) (int64, error) {
  172. cacheKey := fmt.Sprintf("commits-count-%d-graph-%t-%s-%s", r.Repository.ID, hidePRRefs, branches, files)
  173. return cache.GetInt64(cacheKey, func() (int64, error) {
  174. if len(branches) == 0 {
  175. return git.AllCommitsCount(ctx, r.Repository.RepoPath(), hidePRRefs, files...)
  176. }
  177. return git.CommitsCountFiles(ctx, r.Repository.RepoPath(), branches, files)
  178. })
  179. }
  180. // BranchNameSubURL sub-URL for the BranchName field
  181. func (r *Repository) BranchNameSubURL() string {
  182. switch {
  183. case r.IsViewBranch:
  184. return "branch/" + util.PathEscapeSegments(r.BranchName)
  185. case r.IsViewTag:
  186. return "tag/" + util.PathEscapeSegments(r.TagName)
  187. case r.IsViewCommit:
  188. return "commit/" + util.PathEscapeSegments(r.CommitID)
  189. }
  190. log.Error("Unknown view type for repo: %v", r)
  191. return ""
  192. }
  193. // FileExists returns true if a file exists in the given repo branch
  194. func (r *Repository) FileExists(path, branch string) (bool, error) {
  195. if branch == "" {
  196. branch = r.Repository.DefaultBranch
  197. }
  198. commit, err := r.GitRepo.GetBranchCommit(branch)
  199. if err != nil {
  200. return false, err
  201. }
  202. if _, err := commit.GetTreeEntryByPath(path); err != nil {
  203. return false, err
  204. }
  205. return true, nil
  206. }
  207. // GetEditorconfig returns the .editorconfig definition if found in the
  208. // HEAD of the default repo branch.
  209. func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (*editorconfig.Editorconfig, error) {
  210. if r.GitRepo == nil {
  211. return nil, nil
  212. }
  213. var (
  214. err error
  215. commit *git.Commit
  216. )
  217. if len(optCommit) != 0 {
  218. commit = optCommit[0]
  219. } else {
  220. commit, err = r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  221. if err != nil {
  222. return nil, err
  223. }
  224. }
  225. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  226. if err != nil {
  227. return nil, err
  228. }
  229. if treeEntry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  230. return nil, git.ErrNotExist{ID: "", RelPath: ".editorconfig"}
  231. }
  232. reader, err := treeEntry.Blob().DataAsync()
  233. if err != nil {
  234. return nil, err
  235. }
  236. defer reader.Close()
  237. return editorconfig.Parse(reader)
  238. }
  239. // RetrieveBaseRepo retrieves base repository
  240. func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository) {
  241. // Non-fork repository will not return error in this method.
  242. if err := repo.GetBaseRepo(); err != nil {
  243. if repo_model.IsErrRepoNotExist(err) {
  244. repo.IsFork = false
  245. repo.ForkID = 0
  246. return
  247. }
  248. ctx.ServerError("GetBaseRepo", err)
  249. return
  250. } else if err = repo.BaseRepo.GetOwner(ctx); err != nil {
  251. ctx.ServerError("BaseRepo.GetOwner", err)
  252. return
  253. }
  254. }
  255. // RetrieveTemplateRepo retrieves template repository used to generate this repository
  256. func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository) {
  257. // Non-generated repository will not return error in this method.
  258. templateRepo, err := repo_model.GetTemplateRepo(ctx, repo)
  259. if err != nil {
  260. if repo_model.IsErrRepoNotExist(err) {
  261. repo.TemplateID = 0
  262. return
  263. }
  264. ctx.ServerError("GetTemplateRepo", err)
  265. return
  266. } else if err = templateRepo.GetOwner(ctx); err != nil {
  267. ctx.ServerError("TemplateRepo.GetOwner", err)
  268. return
  269. }
  270. perm, err := access_model.GetUserRepoPermission(ctx, templateRepo, ctx.Doer)
  271. if err != nil {
  272. ctx.ServerError("GetUserRepoPermission", err)
  273. return
  274. }
  275. if !perm.CanRead(unit_model.TypeCode) {
  276. repo.TemplateID = 0
  277. }
  278. }
  279. // ComposeGoGetImport returns go-get-import meta content.
  280. func ComposeGoGetImport(owner, repo string) string {
  281. /// setting.AppUrl is guaranteed to be parse as url
  282. appURL, _ := url.Parse(setting.AppURL)
  283. return path.Join(appURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo))
  284. }
  285. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  286. // if user does not have actual access to the requested repository,
  287. // or the owner or repository does not exist at all.
  288. // This is particular a workaround for "go get" command which does not respect
  289. // .netrc file.
  290. func EarlyResponseForGoGetMeta(ctx *Context) {
  291. username := ctx.Params(":username")
  292. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  293. if username == "" || reponame == "" {
  294. ctx.PlainText(http.StatusBadRequest, "invalid repository path")
  295. return
  296. }
  297. goImportContent := fmt.Sprintf("%s git %s", ComposeGoGetImport(username, reponame), repo_model.ComposeHTTPSCloneURL(username, reponame))
  298. htmlMeta := fmt.Sprintf(`<meta name="go-import" content="%s">`, html.EscapeString(goImportContent))
  299. ctx.PlainText(http.StatusOK, htmlMeta)
  300. }
  301. // RedirectToRepo redirect to a differently-named repository
  302. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  303. ownerName := ctx.Params(":username")
  304. previousRepoName := ctx.Params(":reponame")
  305. repo, err := repo_model.GetRepositoryByID(redirectRepoID)
  306. if err != nil {
  307. ctx.ServerError("GetRepositoryByID", err)
  308. return
  309. }
  310. redirectPath := strings.Replace(
  311. ctx.Req.URL.EscapedPath(),
  312. url.PathEscape(ownerName)+"/"+url.PathEscape(previousRepoName),
  313. url.PathEscape(repo.OwnerName)+"/"+url.PathEscape(repo.Name),
  314. 1,
  315. )
  316. if ctx.Req.URL.RawQuery != "" {
  317. redirectPath += "?" + ctx.Req.URL.RawQuery
  318. }
  319. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath), http.StatusTemporaryRedirect)
  320. }
  321. func repoAssignment(ctx *Context, repo *repo_model.Repository) {
  322. var err error
  323. if err = repo.GetOwner(ctx); err != nil {
  324. ctx.ServerError("GetOwner", err)
  325. return
  326. }
  327. ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
  328. if err != nil {
  329. ctx.ServerError("GetUserRepoPermission", err)
  330. return
  331. }
  332. // Check access.
  333. if !ctx.Repo.Permission.HasAccess() {
  334. if ctx.FormString("go-get") == "1" {
  335. EarlyResponseForGoGetMeta(ctx)
  336. return
  337. }
  338. ctx.NotFound("no access right", nil)
  339. return
  340. }
  341. ctx.Data["HasAccess"] = true
  342. ctx.Data["Permission"] = &ctx.Repo.Permission
  343. if repo.IsMirror {
  344. ctx.Repo.Mirror, err = repo_model.GetMirrorByRepoID(ctx, repo.ID)
  345. if err == nil {
  346. ctx.Repo.Mirror.Repo = repo
  347. ctx.Data["IsPullMirror"] = true
  348. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  349. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  350. ctx.Data["Mirror"] = ctx.Repo.Mirror
  351. } else if err != repo_model.ErrMirrorNotExist {
  352. ctx.ServerError("GetMirrorByRepoID", err)
  353. return
  354. }
  355. }
  356. pushMirrors, err := repo_model.GetPushMirrorsByRepoID(repo.ID)
  357. if err != nil {
  358. ctx.ServerError("GetPushMirrorsByRepoID", err)
  359. return
  360. }
  361. ctx.Repo.Repository = repo
  362. ctx.Data["PushMirrors"] = pushMirrors
  363. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  364. ctx.Data["IsEmptyRepo"] = ctx.Repo.Repository.IsEmpty
  365. }
  366. // RepoIDAssignment returns a handler which assigns the repo to the context.
  367. func RepoIDAssignment() func(ctx *Context) {
  368. return func(ctx *Context) {
  369. repoID := ctx.ParamsInt64(":repoid")
  370. // Get repository.
  371. repo, err := repo_model.GetRepositoryByID(repoID)
  372. if err != nil {
  373. if repo_model.IsErrRepoNotExist(err) {
  374. ctx.NotFound("GetRepositoryByID", nil)
  375. } else {
  376. ctx.ServerError("GetRepositoryByID", err)
  377. }
  378. return
  379. }
  380. repoAssignment(ctx, repo)
  381. }
  382. }
  383. // RepoAssignment returns a middleware to handle repository assignment
  384. func RepoAssignment(ctx *Context) (cancel context.CancelFunc) {
  385. if _, repoAssignmentOnce := ctx.Data["repoAssignmentExecuted"]; repoAssignmentOnce {
  386. log.Trace("RepoAssignment was exec already, skipping second call ...")
  387. return
  388. }
  389. ctx.Data["repoAssignmentExecuted"] = true
  390. var (
  391. owner *user_model.User
  392. err error
  393. )
  394. userName := ctx.Params(":username")
  395. repoName := ctx.Params(":reponame")
  396. repoName = strings.TrimSuffix(repoName, ".git")
  397. repoName = strings.TrimSuffix(repoName, ".rss")
  398. repoName = strings.TrimSuffix(repoName, ".atom")
  399. // Check if the user is the same as the repository owner
  400. if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(userName) {
  401. owner = ctx.Doer
  402. } else {
  403. owner, err = user_model.GetUserByName(ctx, userName)
  404. if err != nil {
  405. if user_model.IsErrUserNotExist(err) {
  406. if ctx.FormString("go-get") == "1" {
  407. EarlyResponseForGoGetMeta(ctx)
  408. return
  409. }
  410. ctx.NotFound("GetUserByName", nil)
  411. } else {
  412. ctx.ServerError("GetUserByName", err)
  413. }
  414. return
  415. }
  416. }
  417. ctx.Repo.Owner = owner
  418. ctx.ContextUser = owner
  419. ctx.Data["Username"] = ctx.Repo.Owner.Name
  420. // redirect link to wiki
  421. if strings.HasSuffix(repoName, ".wiki") {
  422. // ctx.Req.URL.Path does not have the preceding appSubURL - any redirect must have this added
  423. // Now we happen to know that all of our paths are: /:username/:reponame/whatever_else
  424. originalRepoName := ctx.Params(":reponame")
  425. redirectRepoName := strings.TrimSuffix(repoName, ".wiki")
  426. redirectRepoName += originalRepoName[len(redirectRepoName)+5:]
  427. redirectPath := strings.Replace(
  428. ctx.Req.URL.EscapedPath(),
  429. url.PathEscape(userName)+"/"+url.PathEscape(originalRepoName),
  430. url.PathEscape(userName)+"/"+url.PathEscape(redirectRepoName)+"/wiki",
  431. 1,
  432. )
  433. if ctx.Req.URL.RawQuery != "" {
  434. redirectPath += "?" + ctx.Req.URL.RawQuery
  435. }
  436. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath))
  437. return
  438. }
  439. // Get repository.
  440. repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
  441. if err != nil {
  442. if repo_model.IsErrRepoNotExist(err) {
  443. redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
  444. if err == nil {
  445. RedirectToRepo(ctx, redirectRepoID)
  446. } else if repo_model.IsErrRedirectNotExist(err) {
  447. if ctx.FormString("go-get") == "1" {
  448. EarlyResponseForGoGetMeta(ctx)
  449. return
  450. }
  451. ctx.NotFound("GetRepositoryByName", nil)
  452. } else {
  453. ctx.ServerError("LookupRepoRedirect", err)
  454. }
  455. } else {
  456. ctx.ServerError("GetRepositoryByName", err)
  457. }
  458. return
  459. }
  460. repo.Owner = owner
  461. repoAssignment(ctx, repo)
  462. if ctx.Written() {
  463. return
  464. }
  465. ctx.Repo.RepoLink = repo.Link()
  466. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  467. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  468. unit, err := ctx.Repo.Repository.GetUnit(unit_model.TypeExternalTracker)
  469. if err == nil {
  470. ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL
  471. }
  472. ctx.Data["NumTags"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  473. IncludeTags: true,
  474. })
  475. if err != nil {
  476. ctx.ServerError("GetReleaseCountByRepoID", err)
  477. return
  478. }
  479. ctx.Data["NumReleases"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{})
  480. if err != nil {
  481. ctx.ServerError("GetReleaseCountByRepoID", err)
  482. return
  483. }
  484. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  485. ctx.Data["Repository"] = repo
  486. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  487. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  488. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  489. ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
  490. ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(unit_model.TypeCode)
  491. ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(unit_model.TypeIssues)
  492. ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(unit_model.TypePullRequests)
  493. canSignedUserFork, err := repo_module.CanUserForkRepo(ctx.Doer, ctx.Repo.Repository)
  494. if err != nil {
  495. ctx.ServerError("CanUserForkRepo", err)
  496. return
  497. }
  498. ctx.Data["CanSignedUserFork"] = canSignedUserFork
  499. userAndOrgForks, err := repo_model.GetForksByUserAndOrgs(ctx, ctx.Doer, ctx.Repo.Repository)
  500. if err != nil {
  501. ctx.ServerError("GetForksByUserAndOrgs", err)
  502. return
  503. }
  504. ctx.Data["UserAndOrgForks"] = userAndOrgForks
  505. // canSignedUserFork is true if the current user doesn't have a fork of this repo yet or
  506. // if he owns an org that doesn't have a fork of this repo yet
  507. // If multiple forks are available or if the user can fork to another account, but there is already a fork: open selection dialog
  508. ctx.Data["ShowForkModal"] = len(userAndOrgForks) > 1 || (canSignedUserFork && len(userAndOrgForks) > 0)
  509. ctx.Data["RepoCloneLink"] = repo.CloneLink()
  510. cloneButtonShowHTTPS := !setting.Repository.DisableHTTPGit
  511. cloneButtonShowSSH := !setting.SSH.Disabled && (ctx.IsSigned || setting.SSH.ExposeAnonymous)
  512. if !cloneButtonShowHTTPS && !cloneButtonShowSSH {
  513. // We have to show at least one link, so we just show the HTTPS
  514. cloneButtonShowHTTPS = true
  515. }
  516. ctx.Data["CloneButtonShowHTTPS"] = cloneButtonShowHTTPS
  517. ctx.Data["CloneButtonShowSSH"] = cloneButtonShowSSH
  518. ctx.Data["CloneButtonOriginLink"] = ctx.Data["RepoCloneLink"] // it may be rewritten to the WikiCloneLink by the router middleware
  519. ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
  520. if setting.Indexer.RepoIndexerEnabled {
  521. ctx.Data["CodeIndexerUnavailable"] = !code_indexer.IsAvailable()
  522. }
  523. if ctx.IsSigned {
  524. ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx.Doer.ID, repo.ID)
  525. ctx.Data["IsStaringRepo"] = repo_model.IsStaring(ctx, ctx.Doer.ID, repo.ID)
  526. }
  527. if repo.IsFork {
  528. RetrieveBaseRepo(ctx, repo)
  529. if ctx.Written() {
  530. return
  531. }
  532. }
  533. if repo.IsGenerated() {
  534. RetrieveTemplateRepo(ctx, repo)
  535. if ctx.Written() {
  536. return
  537. }
  538. }
  539. isHomeOrSettings := ctx.Link == ctx.Repo.RepoLink || ctx.Link == ctx.Repo.RepoLink+"/settings" || strings.HasPrefix(ctx.Link, ctx.Repo.RepoLink+"/settings/")
  540. // Disable everything when the repo is being created
  541. if ctx.Repo.Repository.IsBeingCreated() || ctx.Repo.Repository.IsBroken() {
  542. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  543. if !isHomeOrSettings {
  544. ctx.Redirect(ctx.Repo.RepoLink)
  545. }
  546. return
  547. }
  548. gitRepo, err := git.OpenRepository(ctx, repo_model.RepoPath(userName, repoName))
  549. if err != nil {
  550. if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "no such file or directory") {
  551. log.Error("Repository %-v has a broken repository on the file system: %s Error: %v", ctx.Repo.Repository, ctx.Repo.Repository.RepoPath(), err)
  552. ctx.Repo.Repository.Status = repo_model.RepositoryBroken
  553. ctx.Repo.Repository.IsEmpty = true
  554. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  555. // Only allow access to base of repo or settings
  556. if !isHomeOrSettings {
  557. ctx.Redirect(ctx.Repo.RepoLink)
  558. }
  559. return
  560. }
  561. ctx.ServerError("RepoAssignment Invalid repo "+repo_model.RepoPath(userName, repoName), err)
  562. return
  563. }
  564. if ctx.Repo.GitRepo != nil {
  565. ctx.Repo.GitRepo.Close()
  566. }
  567. ctx.Repo.GitRepo = gitRepo
  568. // We opened it, we should close it
  569. cancel = func() {
  570. // If it's been set to nil then assume someone else has closed it.
  571. if ctx.Repo.GitRepo != nil {
  572. ctx.Repo.GitRepo.Close()
  573. }
  574. }
  575. // Stop at this point when the repo is empty.
  576. if ctx.Repo.Repository.IsEmpty {
  577. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  578. return
  579. }
  580. tags, err := ctx.Repo.GitRepo.GetTags(0, 0)
  581. if err != nil {
  582. if strings.Contains(err.Error(), "fatal: not a git repository ") {
  583. log.Error("Repository %-v has a broken repository on the file system: %s Error: %v", ctx.Repo.Repository, ctx.Repo.Repository.RepoPath(), err)
  584. ctx.Repo.Repository.Status = repo_model.RepositoryBroken
  585. ctx.Repo.Repository.IsEmpty = true
  586. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  587. // Only allow access to base of repo or settings
  588. if !isHomeOrSettings {
  589. ctx.Redirect(ctx.Repo.RepoLink)
  590. }
  591. return
  592. }
  593. ctx.ServerError("GetTags", err)
  594. return
  595. }
  596. ctx.Data["Tags"] = tags
  597. brs, _, err := ctx.Repo.GitRepo.GetBranchNames(0, 0)
  598. if err != nil {
  599. ctx.ServerError("GetBranches", err)
  600. return
  601. }
  602. ctx.Data["Branches"] = brs
  603. ctx.Data["BranchesCount"] = len(brs)
  604. // If not branch selected, try default one.
  605. // If default branch doesn't exists, fall back to some other branch.
  606. if len(ctx.Repo.BranchName) == 0 {
  607. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  608. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  609. } else if len(brs) > 0 {
  610. ctx.Repo.BranchName = brs[0]
  611. }
  612. ctx.Repo.RefName = ctx.Repo.BranchName
  613. }
  614. ctx.Data["BranchName"] = ctx.Repo.BranchName
  615. // People who have push access or have forked repository can propose a new pull request.
  616. canPush := ctx.Repo.CanWrite(unit_model.TypeCode) ||
  617. (ctx.IsSigned && repo_model.HasForkedRepo(ctx.Doer.ID, ctx.Repo.Repository.ID))
  618. canCompare := false
  619. // Pull request is allowed if this is a fork repository
  620. // and base repository accepts pull requests.
  621. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  622. canCompare = true
  623. ctx.Data["BaseRepo"] = repo.BaseRepo
  624. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  625. ctx.Repo.PullRequest.Allowed = canPush
  626. ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.Repo.Owner.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName)
  627. } else if repo.AllowsPulls() {
  628. // Or, this is repository accepts pull requests between branches.
  629. canCompare = true
  630. ctx.Data["BaseRepo"] = repo
  631. ctx.Repo.PullRequest.BaseRepo = repo
  632. ctx.Repo.PullRequest.Allowed = canPush
  633. ctx.Repo.PullRequest.SameRepo = true
  634. ctx.Repo.PullRequest.HeadInfoSubURL = util.PathEscapeSegments(ctx.Repo.BranchName)
  635. }
  636. ctx.Data["CanCompareOrPull"] = canCompare
  637. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  638. if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer {
  639. repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository)
  640. if err != nil {
  641. ctx.ServerError("GetPendingRepositoryTransfer", err)
  642. return
  643. }
  644. if err := repoTransfer.LoadAttributes(); err != nil {
  645. ctx.ServerError("LoadRecipient", err)
  646. return
  647. }
  648. ctx.Data["RepoTransfer"] = repoTransfer
  649. if ctx.Doer != nil {
  650. ctx.Data["CanUserAcceptTransfer"] = repoTransfer.CanUserAcceptTransfer(ctx.Doer)
  651. }
  652. }
  653. if ctx.FormString("go-get") == "1" {
  654. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  655. prefix := repo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(ctx.Repo.BranchName)
  656. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  657. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  658. }
  659. return cancel
  660. }
  661. // RepoRefType type of repo reference
  662. type RepoRefType int
  663. const (
  664. // RepoRefLegacy unknown type, make educated guess and redirect.
  665. // for backward compatibility with previous URL scheme
  666. RepoRefLegacy RepoRefType = iota
  667. // RepoRefAny is for usage where educated guess is needed
  668. // but redirect can not be made
  669. RepoRefAny
  670. // RepoRefBranch branch
  671. RepoRefBranch
  672. // RepoRefTag tag
  673. RepoRefTag
  674. // RepoRefCommit commit
  675. RepoRefCommit
  676. // RepoRefBlob blob
  677. RepoRefBlob
  678. )
  679. // RepoRef handles repository reference names when the ref name is not
  680. // explicitly given
  681. func RepoRef() func(*Context) context.CancelFunc {
  682. // since no ref name is explicitly specified, ok to just use branch
  683. return RepoRefByType(RepoRefBranch)
  684. }
  685. // RefTypeIncludesBranches returns true if ref type can be a branch
  686. func (rt RepoRefType) RefTypeIncludesBranches() bool {
  687. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch {
  688. return true
  689. }
  690. return false
  691. }
  692. // RefTypeIncludesTags returns true if ref type can be a tag
  693. func (rt RepoRefType) RefTypeIncludesTags() bool {
  694. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag {
  695. return true
  696. }
  697. return false
  698. }
  699. func getRefNameFromPath(ctx *Context, path string, isExist func(string) bool) string {
  700. refName := ""
  701. parts := strings.Split(path, "/")
  702. for i, part := range parts {
  703. refName = strings.TrimPrefix(refName+"/"+part, "/")
  704. if isExist(refName) {
  705. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  706. return refName
  707. }
  708. }
  709. return ""
  710. }
  711. func getRefName(ctx *Context, pathType RepoRefType) string {
  712. path := ctx.Params("*")
  713. switch pathType {
  714. case RepoRefLegacy, RepoRefAny:
  715. if refName := getRefName(ctx, RepoRefBranch); len(refName) > 0 {
  716. return refName
  717. }
  718. if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
  719. return refName
  720. }
  721. // For legacy and API support only full commit sha
  722. parts := strings.Split(path, "/")
  723. if len(parts) > 0 && len(parts[0]) == 40 {
  724. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  725. return parts[0]
  726. }
  727. if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
  728. return refName
  729. }
  730. ctx.Repo.TreePath = path
  731. return ctx.Repo.Repository.DefaultBranch
  732. case RepoRefBranch:
  733. ref := getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist)
  734. if len(ref) == 0 {
  735. // maybe it's a renamed branch
  736. return getRefNameFromPath(ctx, path, func(s string) bool {
  737. b, exist, err := git_model.FindRenamedBranch(ctx.Repo.Repository.ID, s)
  738. if err != nil {
  739. log.Error("FindRenamedBranch", err)
  740. return false
  741. }
  742. if !exist {
  743. return false
  744. }
  745. ctx.Data["IsRenamedBranch"] = true
  746. ctx.Data["RenamedBranchName"] = b.To
  747. return true
  748. })
  749. }
  750. return ref
  751. case RepoRefTag:
  752. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
  753. case RepoRefCommit:
  754. parts := strings.Split(path, "/")
  755. if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= 40 {
  756. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  757. return parts[0]
  758. }
  759. case RepoRefBlob:
  760. _, err := ctx.Repo.GitRepo.GetBlob(path)
  761. if err != nil {
  762. return ""
  763. }
  764. return path
  765. default:
  766. log.Error("Unrecognized path type: %v", path)
  767. }
  768. return ""
  769. }
  770. // RepoRefByType handles repository reference name for a specific type
  771. // of repository reference
  772. func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context) context.CancelFunc {
  773. return func(ctx *Context) (cancel context.CancelFunc) {
  774. // Empty repository does not have reference information.
  775. if ctx.Repo.Repository.IsEmpty {
  776. return
  777. }
  778. var (
  779. refName string
  780. err error
  781. )
  782. if ctx.Repo.GitRepo == nil {
  783. repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  784. ctx.Repo.GitRepo, err = git.OpenRepository(ctx, repoPath)
  785. if err != nil {
  786. ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
  787. return
  788. }
  789. // We opened it, we should close it
  790. cancel = func() {
  791. // If it's been set to nil then assume someone else has closed it.
  792. if ctx.Repo.GitRepo != nil {
  793. ctx.Repo.GitRepo.Close()
  794. }
  795. }
  796. }
  797. // Get default branch.
  798. if len(ctx.Params("*")) == 0 {
  799. refName = ctx.Repo.Repository.DefaultBranch
  800. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  801. brs, _, err := ctx.Repo.GitRepo.GetBranchNames(0, 0)
  802. if err != nil {
  803. ctx.ServerError("GetBranches", err)
  804. return
  805. } else if len(brs) == 0 {
  806. err = fmt.Errorf("No branches in non-empty repository %s",
  807. ctx.Repo.GitRepo.Path)
  808. ctx.ServerError("GetBranches", err)
  809. return
  810. }
  811. refName = brs[0]
  812. }
  813. ctx.Repo.RefName = refName
  814. ctx.Repo.BranchName = refName
  815. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  816. if err != nil {
  817. ctx.ServerError("GetBranchCommit", err)
  818. return
  819. }
  820. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  821. ctx.Repo.IsViewBranch = true
  822. } else {
  823. refName = getRefName(ctx, refType)
  824. ctx.Repo.RefName = refName
  825. isRenamedBranch, has := ctx.Data["IsRenamedBranch"].(bool)
  826. if isRenamedBranch && has {
  827. renamedBranchName := ctx.Data["RenamedBranchName"].(string)
  828. ctx.Flash.Info(ctx.Tr("repo.branch.renamed", refName, renamedBranchName))
  829. link := setting.AppSubURL + strings.Replace(ctx.Req.URL.EscapedPath(), util.PathEscapeSegments(refName), util.PathEscapeSegments(renamedBranchName), 1)
  830. ctx.Redirect(link)
  831. return
  832. }
  833. if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
  834. ctx.Repo.IsViewBranch = true
  835. ctx.Repo.BranchName = refName
  836. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  837. if err != nil {
  838. ctx.ServerError("GetBranchCommit", err)
  839. return
  840. }
  841. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  842. } else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
  843. ctx.Repo.IsViewTag = true
  844. ctx.Repo.TagName = refName
  845. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  846. if err != nil {
  847. if git.IsErrNotExist(err) {
  848. ctx.NotFound("GetTagCommit", err)
  849. return
  850. }
  851. ctx.ServerError("GetTagCommit", err)
  852. return
  853. }
  854. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  855. } else if len(refName) >= 7 && len(refName) <= 40 {
  856. ctx.Repo.IsViewCommit = true
  857. ctx.Repo.CommitID = refName
  858. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  859. if err != nil {
  860. ctx.NotFound("GetCommit", err)
  861. return
  862. }
  863. // If short commit ID add canonical link header
  864. if len(refName) < 40 {
  865. ctx.RespHeader().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"",
  866. util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), util.PathEscapeSegments(refName), url.PathEscape(ctx.Repo.Commit.ID.String()), 1))))
  867. }
  868. } else {
  869. if len(ignoreNotExistErr) > 0 && ignoreNotExistErr[0] {
  870. return
  871. }
  872. ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  873. return
  874. }
  875. if refType == RepoRefLegacy {
  876. // redirect from old URL scheme to new URL scheme
  877. prefix := strings.TrimPrefix(setting.AppSubURL+strings.ToLower(strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*"))), strings.ToLower(ctx.Repo.RepoLink))
  878. ctx.Redirect(path.Join(
  879. ctx.Repo.RepoLink,
  880. util.PathEscapeSegments(prefix),
  881. ctx.Repo.BranchNameSubURL(),
  882. util.PathEscapeSegments(ctx.Repo.TreePath)))
  883. return
  884. }
  885. }
  886. ctx.Data["BranchName"] = ctx.Repo.BranchName
  887. ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  888. ctx.Data["TagName"] = ctx.Repo.TagName
  889. ctx.Data["CommitID"] = ctx.Repo.CommitID
  890. ctx.Data["TreePath"] = ctx.Repo.TreePath
  891. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  892. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  893. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  894. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  895. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  896. if err != nil {
  897. ctx.ServerError("GetCommitsCount", err)
  898. return
  899. }
  900. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  901. ctx.Repo.GitRepo.LastCommitCache = git.NewLastCommitCache(ctx.Repo.CommitsCount, ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, cache.GetCache())
  902. return cancel
  903. }
  904. }
  905. // GitHookService checks if repository Git hooks service has been enabled.
  906. func GitHookService() func(ctx *Context) {
  907. return func(ctx *Context) {
  908. if !ctx.Doer.CanEditGitHook() {
  909. ctx.NotFound("GitHookService", nil)
  910. return
  911. }
  912. }
  913. }
  914. // UnitTypes returns a middleware to set unit types to context variables.
  915. func UnitTypes() func(ctx *Context) {
  916. return func(ctx *Context) {
  917. ctx.Data["UnitTypeCode"] = unit_model.TypeCode
  918. ctx.Data["UnitTypeIssues"] = unit_model.TypeIssues
  919. ctx.Data["UnitTypePullRequests"] = unit_model.TypePullRequests
  920. ctx.Data["UnitTypeReleases"] = unit_model.TypeReleases
  921. ctx.Data["UnitTypeWiki"] = unit_model.TypeWiki
  922. ctx.Data["UnitTypeExternalWiki"] = unit_model.TypeExternalWiki
  923. ctx.Data["UnitTypeExternalTracker"] = unit_model.TypeExternalTracker
  924. ctx.Data["UnitTypeProjects"] = unit_model.TypeProjects
  925. ctx.Data["UnitTypePackages"] = unit_model.TypePackages
  926. }
  927. }
  928. // IssueTemplatesFromDefaultBranch checks for issue templates in the repo's default branch
  929. func (ctx *Context) IssueTemplatesFromDefaultBranch() []api.IssueTemplate {
  930. var issueTemplates []api.IssueTemplate
  931. if ctx.Repo.Repository.IsEmpty {
  932. return issueTemplates
  933. }
  934. if ctx.Repo.Commit == nil {
  935. var err error
  936. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  937. if err != nil {
  938. return issueTemplates
  939. }
  940. }
  941. for _, dirName := range IssueTemplateDirCandidates {
  942. tree, err := ctx.Repo.Commit.SubTree(dirName)
  943. if err != nil {
  944. continue
  945. }
  946. entries, err := tree.ListEntries()
  947. if err != nil {
  948. return issueTemplates
  949. }
  950. for _, entry := range entries {
  951. if strings.HasSuffix(entry.Name(), ".md") {
  952. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  953. log.Debug("Issue template is too large: %s", entry.Name())
  954. continue
  955. }
  956. r, err := entry.Blob().DataAsync()
  957. if err != nil {
  958. log.Debug("DataAsync: %v", err)
  959. continue
  960. }
  961. closed := false
  962. defer func() {
  963. if !closed {
  964. _ = r.Close()
  965. }
  966. }()
  967. data, err := io.ReadAll(r)
  968. if err != nil {
  969. log.Debug("ReadAll: %v", err)
  970. continue
  971. }
  972. _ = r.Close()
  973. var it api.IssueTemplate
  974. content, err := markdown.ExtractMetadata(string(data), &it)
  975. if err != nil {
  976. log.Debug("ExtractMetadata: %v", err)
  977. continue
  978. }
  979. it.Content = content
  980. it.FileName = entry.Name()
  981. if it.Valid() {
  982. issueTemplates = append(issueTemplates, it)
  983. }
  984. }
  985. }
  986. if len(issueTemplates) > 0 {
  987. return issueTemplates
  988. }
  989. }
  990. return issueTemplates
  991. }