Fix CodeQL code scanning alerts (#36858)

Fixes 10 CodeQL code scanning alerts:

- Change `NewPagination`/`SetLinkHeader` to accept `int64` for total
count, clamping internally to fix incorrect-integer-conversion alerts
([#110](https://github.com/go-gitea/gitea/security/code-scanning/110),
[#114](https://github.com/go-gitea/gitea/security/code-scanning/114),
[#115](https://github.com/go-gitea/gitea/security/code-scanning/115),
[#116](https://github.com/go-gitea/gitea/security/code-scanning/116))
- Use `strconv.Atoi()` in `htmlrenderer.go` to avoid int64 intermediate
([#105](https://github.com/go-gitea/gitea/security/code-scanning/105),
[#106](https://github.com/go-gitea/gitea/security/code-scanning/106))
- Clamp regex match indices in `escape_stream.go` to fix
allocation-size-overflow
([#161](https://github.com/go-gitea/gitea/security/code-scanning/161),
[#162](https://github.com/go-gitea/gitea/security/code-scanning/162),
[#163](https://github.com/go-gitea/gitea/security/code-scanning/163))
- Cap slice pre-allocation in `GetIssueDependencies`
([#181](https://github.com/go-gitea/gitea/security/code-scanning/181))

---------

Co-authored-by: Claude (Opus 4.6) <noreply@anthropic.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
silverwind
2026-03-08 15:35:50 +01:00
committed by GitHub
parent 3f1ef703d5
commit 0724344a8a
70 changed files with 155 additions and 168 deletions

View File

@@ -61,12 +61,14 @@ func (e *escapeStreamer) Text(data string) error {
until = len(data) until = len(data)
next = until next = until
} else { } else {
until, next = nextIdxs[0]+pos, nextIdxs[1]+pos until = min(nextIdxs[0]+pos, len(data))
next = min(nextIdxs[1]+pos, len(data))
} }
// from pos until we know that the runes are not \r\t\n or even ' ' // from pos until we know that the runes are not \r\t\n or even ' '
runes := make([]rune, 0, next-until) n := next - until
positions := make([]int, 0, next-until+1) runes := make([]rune, 0, n)
positions := make([]int, 0, n+1)
for pos < until { for pos < until {
r, sz := utf8.DecodeRune(dataBytes[pos:]) r, sz := utf8.DecodeRune(dataBytes[pos:])

View File

@@ -24,7 +24,7 @@ func indexSettingToGitGrepPathspecList() (list []string) {
return list return list
} }
func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Repository, ref git.RefName, keyword string, searchMode indexer.SearchModeType) (searchResults []*code_indexer.Result, total int, err error) { func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Repository, ref git.RefName, keyword string, searchMode indexer.SearchModeType) (searchResults []*code_indexer.Result, total int64, err error) {
grepMode := git.GrepModeWords grepMode := git.GrepModeWords
switch searchMode { switch searchMode {
case indexer.SearchModeExact: case indexer.SearchModeExact:
@@ -47,7 +47,7 @@ func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Rep
return nil, 0, fmt.Errorf("gitRepo.GetRefCommitID: %w", err) return nil, 0, fmt.Errorf("gitRepo.GetRefCommitID: %w", err)
} }
total = len(res) total = int64(len(res))
pageStart := min((page-1)*setting.UI.RepoSearchPagingNum, len(res)) pageStart := min((page-1)*setting.UI.RepoSearchPagingNum, len(res))
pageEnd := min(page*setting.UI.RepoSearchPagingNum, len(res)) pageEnd := min(page*setting.UI.RepoSearchPagingNum, len(res))
res = res[pageStart:pageEnd] res = res[pageStart:pageEnd]

View File

@@ -130,7 +130,7 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
} }
// PerformSearch perform a search on a repository // PerformSearch perform a search on a repository
func PerformSearch(ctx context.Context, opts *SearchOptions) (int, []*Result, []*SearchResultLanguages, error) { func PerformSearch(ctx context.Context, opts *SearchOptions) (int64, []*Result, []*SearchResultLanguages, error) {
if opts == nil || len(opts.Keyword) == 0 { if opts == nil || len(opts.Keyword) == 0 {
return 0, nil, nil, nil return 0, nil, nil, nil
} }
@@ -149,5 +149,5 @@ func PerformSearch(ctx context.Context, opts *SearchOptions) (int, []*Result, []
return 0, nil, nil, err return 0, nil, nil, err
} }
} }
return int(total), displayResults, resultLanguages, nil return total, displayResults, resultLanguages, nil
} }

View File

@@ -89,7 +89,7 @@ func (p *templateErrorPrettier) handleGenericTemplateError(err error) string {
return "" return ""
} }
tmplName, lineStr, message := groups[1], groups[2], groups[3] tmplName, lineStr, message := groups[1], groups[2], groups[3]
return p.makeDetailedError(message, tmplName, lineStr, -1, "") return p.makeDetailedError(message, tmplName, lineStr, "", "")
} }
var reFuncNotDefinedError = regexp.MustCompile(`^template: (.*):([0-9]+): (function "(.*)" not defined)`) var reFuncNotDefinedError = regexp.MustCompile(`^template: (.*):([0-9]+): (function "(.*)" not defined)`)
@@ -101,7 +101,7 @@ func (p *templateErrorPrettier) handleFuncNotDefinedError(err error) string {
} }
tmplName, lineStr, message, funcName := groups[1], groups[2], groups[3], groups[4] tmplName, lineStr, message, funcName := groups[1], groups[2], groups[3], groups[4]
funcName, _ = strconv.Unquote(`"` + funcName + `"`) funcName, _ = strconv.Unquote(`"` + funcName + `"`)
return p.makeDetailedError(message, tmplName, lineStr, -1, funcName) return p.makeDetailedError(message, tmplName, lineStr, "", funcName)
} }
var reUnexpectedOperandError = regexp.MustCompile(`^template: (.*):([0-9]+): (unexpected "(.*)" in operand)`) var reUnexpectedOperandError = regexp.MustCompile(`^template: (.*):([0-9]+): (unexpected "(.*)" in operand)`)
@@ -113,7 +113,7 @@ func (p *templateErrorPrettier) handleUnexpectedOperandError(err error) string {
} }
tmplName, lineStr, message, unexpected := groups[1], groups[2], groups[3], groups[4] tmplName, lineStr, message, unexpected := groups[1], groups[2], groups[3], groups[4]
unexpected, _ = strconv.Unquote(`"` + unexpected + `"`) unexpected, _ = strconv.Unquote(`"` + unexpected + `"`)
return p.makeDetailedError(message, tmplName, lineStr, -1, unexpected) return p.makeDetailedError(message, tmplName, lineStr, "", unexpected)
} }
var reExpectedEndError = regexp.MustCompile(`^template: (.*):([0-9]+): (expected end; found (.*))`) var reExpectedEndError = regexp.MustCompile(`^template: (.*):([0-9]+): (expected end; found (.*))`)
@@ -124,7 +124,7 @@ func (p *templateErrorPrettier) handleExpectedEndError(err error) string {
return "" return ""
} }
tmplName, lineStr, message, unexpected := groups[1], groups[2], groups[3], groups[4] tmplName, lineStr, message, unexpected := groups[1], groups[2], groups[3], groups[4]
return p.makeDetailedError(message, tmplName, lineStr, -1, unexpected) return p.makeDetailedError(message, tmplName, lineStr, "", unexpected)
} }
var ( var (
@@ -154,20 +154,20 @@ func HandleTemplateRenderingError(err error) string {
const dashSeparator = "----------------------------------------------------------------------" const dashSeparator = "----------------------------------------------------------------------"
func (p *templateErrorPrettier) makeDetailedError(errMsg, tmplName string, lineNum, posNum any, target string) string { func (p *templateErrorPrettier) makeDetailedError(errMsg, tmplName, lineNumStr, posNumStr, target string) string {
code, layer, err := p.assets.ReadLayeredFile(tmplName + ".tmpl") code, layer, err := p.assets.ReadLayeredFile(tmplName + ".tmpl")
if err != nil { if err != nil {
return fmt.Sprintf("template error: %s, and unable to find template file %q", errMsg, tmplName) return fmt.Sprintf("template error: %s, and unable to find template file %q", errMsg, tmplName)
} }
line, err := util.ToInt64(lineNum) line, err := strconv.Atoi(lineNumStr)
if err != nil { if err != nil {
return fmt.Sprintf("template error: %s, unable to parse template %q line number %q", errMsg, tmplName, lineNum) return fmt.Sprintf("template error: %s, unable to parse template %q line number %s", errMsg, tmplName, lineNumStr)
} }
pos, err := util.ToInt64(posNum) pos, err := strconv.Atoi(util.IfZero(posNumStr, "-1"))
if err != nil { if err != nil {
return fmt.Sprintf("template error: %s, unable to parse template %q pos number %q", errMsg, tmplName, posNum) return fmt.Sprintf("template error: %s, unable to parse template %q pos number %s", errMsg, tmplName, posNumStr)
} }
detail := extractErrorLine(code, int(line), int(pos), target) detail := extractErrorLine(code, line, pos, target)
var msg string var msg string
if pos >= 0 { if pos >= 0 {

View File

@@ -50,7 +50,7 @@ func ListUnadoptedRepositories(ctx *context.APIContext) {
return return
} }
ctx.SetTotalCountHeader(int64(count)) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, repoNames) ctx.JSON(http.StatusOK, repoNames)
} }

View File

@@ -51,7 +51,7 @@ func GetAllEmails(ctx *context.APIContext) {
results[i] = convert.ToEmailSearch(emails[i]) results[i] = convert.ToEmailSearch(emails[i])
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, &results) ctx.JSON(http.StatusOK, &results)
} }

View File

@@ -77,7 +77,7 @@ func ListHooks(ctx *context.APIContext) {
} }
hooks[i] = h hooks[i] = h
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, hooks) ctx.JSON(http.StatusOK, hooks)
} }

View File

@@ -117,7 +117,7 @@ func GetAllOrgs(ctx *context.APIContext) {
orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(users[i])) orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(users[i]))
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, &orgs) ctx.JSON(http.StatusOK, &orgs)
} }

View File

@@ -534,7 +534,7 @@ func SearchUsers(ctx *context.APIContext) {
results[i] = convert.ToUser(ctx, users[i], ctx.Doer) results[i] = convert.ToUser(ctx, users[i], ctx.Doer)
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, &results) ctx.JSON(http.StatusOK, &results)
} }

View File

@@ -125,7 +125,7 @@ func ListRepoNotifications(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(totalCount), opts.PageSize) ctx.SetLinkHeader(totalCount, opts.PageSize)
ctx.SetTotalCountHeader(totalCount) ctx.SetTotalCountHeader(totalCount)
ctx.JSON(http.StatusOK, convert.ToNotifications(ctx, nl)) ctx.JSON(http.StatusOK, convert.ToNotifications(ctx, nl))
} }

View File

@@ -86,7 +86,7 @@ func ListNotifications(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(totalCount), opts.PageSize) ctx.SetLinkHeader(totalCount, opts.PageSize)
ctx.SetTotalCountHeader(totalCount) ctx.SetTotalCountHeader(totalCount)
ctx.JSON(http.StatusOK, convert.ToNotifications(ctx, nl)) ctx.JSON(http.StatusOK, convert.ToNotifications(ctx, nl))
} }

View File

@@ -67,7 +67,7 @@ func (Action) ListActionsSecrets(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(count), opts.PageSize) ctx.SetLinkHeader(count, opts.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiSecrets) ctx.JSON(http.StatusOK, apiSecrets)
} }
@@ -240,7 +240,7 @@ func (Action) ListVariables(ctx *context.APIContext) {
Description: v.Description, Description: v.Description,
} }
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, variables) ctx.JSON(http.StatusOK, variables)
} }

View File

@@ -45,7 +45,7 @@ func listMembers(ctx *context.APIContext, isMember bool) {
apiMembers[i] = convert.ToUser(ctx, member, ctx.Doer) apiMembers[i] = convert.ToUser(ctx, member, ctx.Doer)
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiMembers) ctx.JSON(http.StatusOK, apiMembers)
} }

View File

@@ -42,7 +42,7 @@ func listUserOrgs(ctx *context.APIContext, u *user_model.User) {
apiOrgs[i] = convert.ToOrganization(ctx, orgs[i]) apiOrgs[i] = convert.ToOrganization(ctx, orgs[i])
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, &apiOrgs) ctx.JSON(http.StatusOK, &apiOrgs)
} }
@@ -215,7 +215,7 @@ func GetAll(ctx *context.APIContext) {
orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(publicOrgs[i])) orgs[i] = convert.ToOrganization(ctx, organization.OrgFromUser(publicOrgs[i]))
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, &orgs) ctx.JSON(http.StatusOK, &orgs)
} }

View File

@@ -70,7 +70,7 @@ func ListTeams(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiTeams) ctx.JSON(http.StatusOK, apiTeams)
} }
@@ -111,7 +111,7 @@ func ListUserTeams(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiTeams) ctx.JSON(http.StatusOK, apiTeams)
} }
@@ -411,7 +411,7 @@ func GetTeamMembers(ctx *context.APIContext) {
members[i] = convert.ToUser(ctx, member, ctx.Doer) members[i] = convert.ToUser(ctx, member, ctx.Doer)
} }
ctx.SetLinkHeader(ctx.Org.Team.NumMembers, listOptions.PageSize) ctx.SetLinkHeader(int64(ctx.Org.Team.NumMembers), listOptions.PageSize)
ctx.SetTotalCountHeader(int64(ctx.Org.Team.NumMembers)) ctx.SetTotalCountHeader(int64(ctx.Org.Team.NumMembers))
ctx.JSON(http.StatusOK, members) ctx.JSON(http.StatusOK, members)
} }
@@ -583,7 +583,7 @@ func GetTeamRepos(ctx *context.APIContext) {
} }
repos[i] = convert.ToRepo(ctx, repo, permission) repos[i] = convert.ToRepo(ctx, repo, permission)
} }
ctx.SetLinkHeader(team.NumRepos, listOptions.PageSize) ctx.SetLinkHeader(int64(team.NumRepos), listOptions.PageSize)
ctx.SetTotalCountHeader(int64(team.NumRepos)) ctx.SetTotalCountHeader(int64(team.NumRepos))
ctx.JSON(http.StatusOK, repos) ctx.JSON(http.StatusOK, repos)
} }
@@ -827,7 +827,7 @@ func SearchTeam(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, map[string]any{ ctx.JSON(http.StatusOK, map[string]any{
"ok": true, "ok": true,
@@ -882,7 +882,7 @@ func ListTeamActivityFeeds(ctx *context.APIContext) {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, convert.ToActivities(ctx, feeds, ctx.Doer)) ctx.JSON(http.StatusOK, convert.ToActivities(ctx, feeds, ctx.Doer))
} }

View File

@@ -68,7 +68,7 @@ func ListPackages(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiPackages) ctx.JSON(http.StatusOK, apiPackages)
} }
@@ -249,7 +249,7 @@ func ListPackageVersions(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiPackages) ctx.JSON(http.StatusOK, apiPackages)
} }

View File

@@ -91,7 +91,7 @@ func (Action) ListActionsSecrets(ctx *context.APIContext) {
Created: v.CreatedUnix.AsTime(), Created: v.CreatedUnix.AsTime(),
} }
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiSecrets) ctx.JSON(http.StatusOK, apiSecrets)
} }
@@ -506,7 +506,7 @@ func (Action) ListVariables(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, variables) ctx.JSON(http.StatusOK, variables)
} }
@@ -811,7 +811,7 @@ func ListActionTasks(ctx *context.APIContext) {
res.Entries[i] = convertedTask res.Entries[i] = convertedTask
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) // Duplicates api response field but it's better to set it for consistency ctx.SetTotalCountHeader(total) // Duplicates api response field but it's better to set it for consistency
ctx.JSON(http.StatusOK, &res) ctx.JSON(http.StatusOK, &res)
} }

View File

@@ -375,7 +375,7 @@ func ListBranches(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(totalNumOfBranches), listOptions.PageSize) ctx.SetLinkHeader(totalNumOfBranches, listOptions.PageSize)
ctx.SetTotalCountHeader(totalNumOfBranches) ctx.SetTotalCountHeader(totalNumOfBranches)
ctx.JSON(http.StatusOK, apiBranches) ctx.JSON(http.StatusOK, apiBranches)
} }

View File

@@ -290,7 +290,7 @@ func GetAllCommits(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(commitsCountTotal), listOptions.PageSize) ctx.SetLinkHeader(commitsCountTotal, listOptions.PageSize)
ctx.SetTotalCountHeader(commitsCountTotal) ctx.SetTotalCountHeader(commitsCountTotal)
// kept for backwards compatibility // kept for backwards compatibility

View File

@@ -299,7 +299,7 @@ func SearchIssues(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(total), limit) ctx.SetLinkHeader(total, limit)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, ctx.Doer, issues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, ctx.Doer, issues))
} }
@@ -527,7 +527,7 @@ func ListIssues(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, ctx.Doer, issues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, ctx.Doer, issues))
} }

View File

@@ -81,7 +81,7 @@ func GetIssueDependencies(ctx *context.APIContext) {
canWrite := ctx.Repo.Permission.CanWriteIssuesOrPulls(issue.IsPull) canWrite := ctx.Repo.Permission.CanWriteIssuesOrPulls(issue.IsPull)
blockerIssues := make([]*issues_model.Issue, 0, listOptions.PageSize) blockerIssues := make([]*issues_model.Issue, 0, min(listOptions.PageSize, setting.API.MaxResponseItems))
// 2. Get the issues this issue depends on, i.e. the `<#b>`: `<issue> <- <#b>` // 2. Get the issues this issue depends on, i.e. the `<#b>`: `<issue> <- <#b>`
blockersInfo, total, err := issue.BlockedByDependencies(ctx, listOptions) blockersInfo, total, err := issue.BlockedByDependencies(ctx, listOptions)
@@ -140,7 +140,7 @@ func GetIssueDependencies(ctx *context.APIContext) {
} }
blockerIssues = append(blockerIssues, &blocker.Issue) blockerIssues = append(blockerIssues, &blocker.Issue)
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, ctx.Doer, blockerIssues)) ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, ctx.Doer, blockerIssues))
} }

View File

@@ -179,7 +179,7 @@ func ListPushMirrors(ctx *context.APIContext) {
responsePushMirrors = append(responsePushMirrors, m) responsePushMirrors = append(responsePushMirrors, m)
} }
} }
ctx.SetLinkHeader(len(responsePushMirrors), utils.GetListOptions(ctx).PageSize) ctx.SetLinkHeader(int64(len(responsePushMirrors)), utils.GetListOptions(ctx).PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, responsePushMirrors) ctx.JSON(http.StatusOK, responsePushMirrors)
} }

View File

@@ -154,7 +154,7 @@ func ListPullRequests(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, &apiPrs) ctx.JSON(http.StatusOK, &apiPrs)
} }
@@ -1449,7 +1449,7 @@ func GetPullRequestCommits(ctx *context.APIContext) {
apiCommits = append(apiCommits, apiCommit) apiCommits = append(apiCommits, apiCommit)
} }
ctx.SetLinkHeader(totalNumberOfCommits, listOptions.PageSize) ctx.SetLinkHeader(int64(totalNumberOfCommits), listOptions.PageSize)
ctx.SetTotalCountHeader(int64(totalNumberOfCommits)) ctx.SetTotalCountHeader(int64(totalNumberOfCommits))
ctx.RespHeader().Set("X-Page", strconv.Itoa(listOptions.Page)) ctx.RespHeader().Set("X-Page", strconv.Itoa(listOptions.Page))
@@ -1591,7 +1591,7 @@ func GetPullRequestFiles(ctx *context.APIContext) {
apiFiles = append(apiFiles, convert.ToChangedFile(diff.Files[i], pr.BaseRepo, endCommitID)) apiFiles = append(apiFiles, convert.ToChangedFile(diff.Files[i], pr.BaseRepo, endCommitID))
} }
ctx.SetLinkHeader(totalNumberOfFiles, listOptions.PageSize) ctx.SetLinkHeader(int64(totalNumberOfFiles), listOptions.PageSize)
ctx.SetTotalCountHeader(int64(totalNumberOfFiles)) ctx.SetTotalCountHeader(int64(totalNumberOfFiles))
ctx.RespHeader().Set("X-Page", strconv.Itoa(listOptions.Page)) ctx.RespHeader().Set("X-Page", strconv.Itoa(listOptions.Page))

View File

@@ -202,7 +202,7 @@ func ListReleases(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(int(filteredCount), listOptions.PageSize) ctx.SetLinkHeader(filteredCount, listOptions.PageSize)
ctx.SetTotalCountHeader(filteredCount) ctx.SetTotalCountHeader(filteredCount)
ctx.JSON(http.StatusOK, rels) ctx.JSON(http.StatusOK, rels)
} }

View File

@@ -230,7 +230,7 @@ func Search(ctx *context.APIContext) {
} }
results[i] = convert.ToRepo(ctx, repo, permission) results[i] = convert.ToRepo(ctx, repo, permission)
} }
ctx.SetLinkHeader(int(count), opts.PageSize) ctx.SetLinkHeader(count, opts.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, api.SearchResults{ ctx.JSON(http.StatusOK, api.SearchResults{
OK: true, OK: true,

View File

@@ -206,7 +206,7 @@ func getCommitStatuses(ctx *context.APIContext, commitID string) {
apiStatuses = append(apiStatuses, convert.ToCommitStatus(ctx, status)) apiStatuses = append(apiStatuses, convert.ToCommitStatus(ctx, status))
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, apiStatuses) ctx.JSON(http.StatusOK, apiStatuses)
@@ -269,7 +269,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
ctx.APIErrorInternal(fmt.Errorf("CountLatestCommitStatus[%s, %s]: %w", repo.FullName(), refCommit.CommitID, err)) ctx.APIErrorInternal(fmt.Errorf("CountLatestCommitStatus[%s, %s]: %w", repo.FullName(), refCommit.CommitID, err))
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
combiStatus := convert.ToCombinedStatus(ctx, refCommit.Commit.ID.String(), statuses, combiStatus := convert.ToCombinedStatus(ctx, refCommit.Commit.ID.String(), statuses,

View File

@@ -333,7 +333,7 @@ func ListWikiPages(ctx *context.APIContext) {
pages = append(pages, wiki_service.ToWikiPageMetaData(wikiName, c, ctx.Repo.Repository)) pages = append(pages, wiki_service.ToWikiPageMetaData(wikiName, c, ctx.Repo.Repository))
} }
ctx.SetLinkHeader(len(entries), limit) ctx.SetLinkHeader(int64(len(entries)), limit)
ctx.SetTotalCountHeader(int64(len(entries))) ctx.SetTotalCountHeader(int64(len(entries)))
ctx.JSON(http.StatusOK, pages) ctx.JSON(http.StatusOK, pages)
} }

View File

@@ -79,7 +79,7 @@ func ListJobs(ctx *context.APIContext, ownerID, repoID, runID int64) {
} }
res.Entries[i] = convertedWorkflowJob res.Entries[i] = convertedWorkflowJob
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, &res) ctx.JSON(http.StatusOK, &res)
} }
@@ -185,7 +185,7 @@ func ListRuns(ctx *context.APIContext, ownerID, repoID int64) {
} }
res.Entries[i] = convertedRun res.Entries[i] = convertedRun
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, &res) ctx.JSON(http.StatusOK, &res)
} }

View File

@@ -36,7 +36,7 @@ func ListBlocks(ctx *context.APIContext, blocker *user_model.User) {
users = append(users, convert.ToUser(ctx, b.Blockee, blocker)) users = append(users, convert.ToUser(ctx, b.Blockee, blocker))
} }
ctx.SetLinkHeader(int(total), listOptions.PageSize) ctx.SetLinkHeader(total, listOptions.PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, &users) ctx.JSON(http.StatusOK, &users)
} }

View File

@@ -354,7 +354,7 @@ func ListVariables(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, variables) ctx.JSON(http.StatusOK, variables)
} }

View File

@@ -31,7 +31,7 @@ func listUserFollowers(ctx *context.APIContext, u *user_model.User) {
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
responseAPIUsers(ctx, users) responseAPIUsers(ctx, users)
} }
@@ -97,7 +97,7 @@ func listUserFollowing(ctx *context.APIContext, u *user_model.User) {
return return
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
responseAPIUsers(ctx, users) responseAPIUsers(ctx, users)
} }

View File

@@ -94,7 +94,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
} }
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, &apiKeys) ctx.JSON(http.StatusOK, &apiKeys)
} }

View File

@@ -47,7 +47,7 @@ func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) {
} }
} }
ctx.SetLinkHeader(int(count), opts.PageSize) ctx.SetLinkHeader(count, opts.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, &apiRepos) ctx.JSON(http.StatusOK, &apiRepos)
} }
@@ -130,7 +130,7 @@ func ListMyRepos(ctx *context.APIContext) {
results[i] = convert.ToRepo(ctx, repo, permission) results[i] = convert.ToRepo(ctx, repo, permission)
} }
ctx.SetLinkHeader(int(count), opts.ListOptions.PageSize) ctx.SetLinkHeader(count, opts.ListOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, &results) ctx.JSON(http.StatusOK, &results)
} }

View File

@@ -76,7 +76,7 @@ func GetStarredRepos(ctx *context.APIContext) {
return return
} }
ctx.SetLinkHeader(ctx.ContextUser.NumStars, utils.GetListOptions(ctx).PageSize) ctx.SetLinkHeader(int64(ctx.ContextUser.NumStars), utils.GetListOptions(ctx).PageSize)
ctx.SetTotalCountHeader(int64(ctx.ContextUser.NumStars)) ctx.SetTotalCountHeader(int64(ctx.ContextUser.NumStars))
ctx.JSON(http.StatusOK, &repos) ctx.JSON(http.StatusOK, &repos)
} }
@@ -108,7 +108,7 @@ func GetMyStarredRepos(ctx *context.APIContext) {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
} }
ctx.SetLinkHeader(ctx.Doer.NumStars, utils.GetListOptions(ctx).PageSize) ctx.SetLinkHeader(int64(ctx.Doer.NumStars), utils.GetListOptions(ctx).PageSize)
ctx.SetTotalCountHeader(int64(ctx.Doer.NumStars)) ctx.SetTotalCountHeader(int64(ctx.Doer.NumStars))
ctx.JSON(http.StatusOK, &repos) ctx.JSON(http.StatusOK, &repos)
} }

View File

@@ -91,7 +91,7 @@ func Search(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) ctx.SetLinkHeader(maxResults, listOptions.PageSize)
ctx.SetTotalCountHeader(maxResults) ctx.SetTotalCountHeader(maxResults)
ctx.JSON(http.StatusOK, map[string]any{ ctx.JSON(http.StatusOK, map[string]any{

View File

@@ -71,7 +71,7 @@ func GetWatchedRepos(ctx *context.APIContext) {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
} }
ctx.SetLinkHeader(int(total), utils.GetListOptions(ctx).PageSize) ctx.SetLinkHeader(total, utils.GetListOptions(ctx).PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, &repos) ctx.JSON(http.StatusOK, &repos)
} }
@@ -100,7 +100,7 @@ func GetMyWatchedRepos(ctx *context.APIContext) {
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
} }
ctx.SetLinkHeader(int(total), utils.GetListOptions(ctx).PageSize) ctx.SetLinkHeader(total, utils.GetListOptions(ctx).PageSize)
ctx.SetTotalCountHeader(total) ctx.SetTotalCountHeader(total)
ctx.JSON(http.StatusOK, &repos) ctx.JSON(http.StatusOK, &repos)
} }

View File

@@ -43,7 +43,7 @@ func ListOwnerHooks(ctx *context.APIContext, owner *user_model.User) {
return return
} }
} }
ctx.SetLinkHeader(int(count), listOptions.PageSize) ctx.SetLinkHeader(count, listOptions.PageSize)
ctx.SetTotalCountHeader(count) ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, apiHooks) ctx.JSON(http.StatusOK, apiHooks)
} }

View File

@@ -93,7 +93,7 @@ func Emails(ctx *context.Context) {
ctx.Data["Total"] = count ctx.Data["Total"] = count
ctx.Data["Emails"] = emails ctx.Data["Emails"] = emails
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -37,7 +37,7 @@ func Notices(ctx *context.Context) {
ctx.Data["Total"] = total ctx.Data["Total"] = total
ctx.Data["Page"] = context.NewPagination(int(total), setting.UI.Admin.NoticePagingNum, page, 5) ctx.Data["Page"] = context.NewPagination(total, setting.UI.Admin.NoticePagingNum, page, 5)
ctx.HTML(http.StatusOK, tplNotices) ctx.HTML(http.StatusOK, tplNotices)
} }

View File

@@ -73,7 +73,7 @@ func Packages(ctx *context.Context) {
ctx.Data["TotalBlobSize"] = totalBlobSize - totalUnreferencedBlobSize ctx.Data["TotalBlobSize"] = totalBlobSize - totalUnreferencedBlobSize
ctx.Data["TotalUnreferencedBlobSize"] = totalUnreferencedBlobSize ctx.Data["TotalUnreferencedBlobSize"] = totalUnreferencedBlobSize
pager := context.NewPagination(int(total), setting.UI.PackagesPagingNum, page, 5) pager := context.NewPagination(total, setting.UI.PackagesPagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -66,7 +66,7 @@ func Code(ctx *context.Context) {
} }
var ( var (
total int total int64
searchResults []*code_indexer.Result searchResults []*code_indexer.Result
searchResultLanguages []*code_indexer.SearchResultLanguages searchResultLanguages []*code_indexer.SearchResultLanguages
) )

View File

@@ -137,7 +137,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) {
ctx.Data["Repos"] = repos ctx.Data["Repos"] = repos
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
pager := context.NewPagination(int(count), opts.PageSize, page, 5) pager := context.NewPagination(count, opts.PageSize, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -119,7 +119,7 @@ func RenderUserSearch(ctx *context.Context, opts user_model.SearchUserOptions, t
ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -141,7 +141,7 @@ func home(ctx *context.Context, viewRepositories bool) {
ctx.Data["Repos"] = repos ctx.Data["Repos"] = repos
ctx.Data["Total"] = count ctx.Data["Total"] = count
pager := context.NewPagination(int(count), setting.UI.User.RepoPagingNum, page, 5) pager := context.NewPagination(count, setting.UI.User.RepoPagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -56,7 +56,7 @@ func Members(ctx *context.Context) {
return return
} }
pager := context.NewPagination(int(total), setting.UI.MembersPagingNum, page, 5) pager := context.NewPagination(total, setting.UI.MembersPagingNum, page, 5)
opts.ListOptions.Page = page opts.ListOptions.Page = page
opts.ListOptions.PageSize = setting.UI.MembersPagingNum opts.ListOptions.PageSize = setting.UI.MembersPagingNum
members, membersIsPublic, err := organization.FindOrgMembers(ctx, opts) members, membersIsPublic, err := organization.FindOrgMembers(ctx, opts)

View File

@@ -114,12 +114,7 @@ func Projects(ctx *context.Context) {
project.RenderedContent = renderUtils.MarkdownToHtml(project.Description) project.RenderedContent = renderUtils.MarkdownToHtml(project.Description)
} }
numPages := 0 pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)
if total > 0 {
numPages = (int(total) - 1/setting.UI.IssuePagingNum)
}
pager := context.NewPagination(int(total), setting.UI.IssuePagingNum, page, numPages)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -341,7 +341,7 @@ func prepareWorkflowList(ctx *context.Context, workflows []WorkflowInfo) {
ctx.Data["StatusInfoList"] = actions_model.GetStatusInfoList(ctx, ctx.Locale) ctx.Data["StatusInfoList"] = actions_model.GetStatusInfoList(ctx, ctx.Locale)
pager := context.NewPagination(int(total), opts.PageSize, opts.Page, 5) pager := context.NewPagination(total, opts.PageSize, opts.Page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.Data["HasWorkflowsOrRuns"] = len(workflows) > 0 || len(runs) > 0 ctx.Data["HasWorkflowsOrRuns"] = len(workflows) > 0 || len(runs) > 0

View File

@@ -84,7 +84,7 @@ func Branches(ctx *context.Context) {
ctx.Data["CommitStatus"] = commitStatus ctx.Data["CommitStatus"] = commitStatus
ctx.Data["CommitStatuses"] = commitStatuses ctx.Data["CommitStatuses"] = commitStatuses
ctx.Data["DefaultBranchBranch"] = defaultBranch ctx.Data["DefaultBranchBranch"] = defaultBranch
pager := context.NewPagination(int(branchesCount), pageSize, page, 5) pager := context.NewPagination(branchesCount, pageSize, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplBranch) ctx.HTML(http.StatusOK, tplBranch)

View File

@@ -101,7 +101,7 @@ func Commits(ctx *context.Context) {
ctx.Data["Reponame"] = ctx.Repo.Repository.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name
ctx.Data["CommitCount"] = commitsCount ctx.Data["CommitCount"] = commitsCount
pager := context.NewPagination(int(commitsCount), pageSize, page, 5) pager := context.NewPagination(commitsCount, pageSize, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplCommits) ctx.HTML(http.StatusOK, tplCommits)
@@ -170,7 +170,7 @@ func Graph(ctx *context.Context) {
divOnly := ctx.FormBool("div-only") divOnly := ctx.FormBool("div-only")
queryParams := ctx.Req.URL.Query() queryParams := ctx.Req.URL.Query()
queryParams.Del("div-only") queryParams.Del("div-only")
paginator := context.NewPagination(int(graphCommitsCount), setting.UI.GraphMaxCommitNum, page, 5) paginator := context.NewPagination(graphCommitsCount, setting.UI.GraphMaxCommitNum, page, 5)
paginator.AddParamFromQuery(queryParams) paginator.AddParamFromQuery(queryParams)
ctx.Data["Page"] = paginator ctx.Data["Page"] = paginator
if divOnly { if divOnly {
@@ -254,7 +254,7 @@ func FileHistory(ctx *context.Context) {
ctx.Data["FileTreePath"] = ctx.Repo.TreePath ctx.Data["FileTreePath"] = ctx.Repo.TreePath
ctx.Data["CommitCount"] = commitsCount ctx.Data["CommitCount"] = commitsCount
pager := context.NewPagination(int(commitsCount), setting.Git.CommitsRangeSize, page, 5) pager := context.NewPagination(commitsCount, setting.Git.CommitsRangeSize, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplCommits) ctx.HTML(http.StatusOK, tplCommits)

View File

@@ -575,9 +575,9 @@ func prepareIssueFilterAndList(ctx *context.Context, milestoneID, projectID int6
} }
// prepare pager // prepare pager
total := int(issueStats.OpenCount + issueStats.ClosedCount) total := issueStats.OpenCount + issueStats.ClosedCount
if isShowClosed.Has() { if isShowClosed.Has() {
total = util.Iif(isShowClosed.Value(), int(issueStats.ClosedCount), int(issueStats.OpenCount)) total = util.Iif(isShowClosed.Value(), issueStats.ClosedCount, issueStats.OpenCount)
} }
page := max(ctx.FormInt("page"), 1) page := max(ctx.FormInt("page"), 1)
pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5) pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)

View File

@@ -88,7 +88,7 @@ func Milestones(ctx *context.Context) {
ctx.Data["Keyword"] = keyword ctx.Data["Keyword"] = keyword
ctx.Data["IsShowClosed"] = isShowClosed ctx.Data["IsShowClosed"] = isShowClosed
pager := context.NewPagination(int(total), setting.UI.IssuePagingNum, page, 5) pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -64,7 +64,7 @@ func Packages(ctx *context.Context) {
ctx.Data["Total"] = total ctx.Data["Total"] = total
ctx.Data["RepositoryAccessMap"] = map[int64]bool{ctx.Repo.Repository.ID: true} // There is only the current repository ctx.Data["RepositoryAccessMap"] = map[int64]bool{ctx.Repo.Repository.ID: true} // There is only the current repository
pager := context.NewPagination(int(total), setting.UI.PackagesPagingNum, page, 5) pager := context.NewPagination(total, setting.UI.PackagesPagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -66,13 +66,6 @@ func Projects(ctx *context.Context) {
ctx.Data["OpenCount"] = repo.NumOpenProjects ctx.Data["OpenCount"] = repo.NumOpenProjects
ctx.Data["ClosedCount"] = repo.NumClosedProjects ctx.Data["ClosedCount"] = repo.NumClosedProjects
var total int
if !isShowClosed {
total = repo.NumOpenProjects
} else {
total = repo.NumClosedProjects
}
projects, count, err := db.FindAndCount[project_model.Project](ctx, project_model.SearchOptions{ projects, count, err := db.FindAndCount[project_model.Project](ctx, project_model.SearchOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
PageSize: setting.UI.IssuePagingNum, PageSize: setting.UI.IssuePagingNum,
@@ -111,12 +104,7 @@ func Projects(ctx *context.Context) {
ctx.Data["State"] = "open" ctx.Data["State"] = "open"
} }
numPages := 0 pager := context.NewPagination(count, setting.UI.IssuePagingNum, page, 5)
if count > 0 {
numPages = (int(count) - 1/setting.UI.IssuePagingNum)
}
pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, numPages)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -187,7 +187,7 @@ func Releases(ctx *context.Context) {
ctx.Data["Releases"] = releases ctx.Data["Releases"] = releases
numReleases := ctx.Data["NumReleases"].(int64) numReleases := ctx.Data["NumReleases"].(int64)
pager := context.NewPagination(int(numReleases), listOptions.PageSize, listOptions.Page, 5) pager := context.NewPagination(numReleases, listOptions.PageSize, listOptions.Page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplReleasesList) ctx.HTML(http.StatusOK, tplReleasesList)
@@ -239,7 +239,7 @@ func TagsList(ctx *context.Context) {
ctx.Data["Releases"] = releases ctx.Data["Releases"] = releases
ctx.Data["TagCount"] = count ctx.Data["TagCount"] = count
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.Data["PageIsViewCode"] = !ctx.Repo.Repository.UnitEnabled(ctx, unit.TypeReleases) ctx.Data["PageIsViewCode"] = !ctx.Repo.Repository.UnitEnabled(ctx, unit.TypeReleases)

View File

@@ -32,7 +32,7 @@ func Search(ctx *context.Context) {
page = 1 page = 1
} }
var total int var total int64
var searchResults []*code_indexer.Result var searchResults []*code_indexer.Result
var searchResultLanguages []*code_indexer.SearchResultLanguages var searchResultLanguages []*code_indexer.SearchResultLanguages
if setting.Indexer.RepoIndexerEnabled { if setting.Indexer.RepoIndexerEnabled {

View File

@@ -54,7 +54,7 @@ func LFSFiles(ctx *context.Context) {
} }
ctx.Data["Total"] = total ctx.Data["Total"] = total
pager := context.NewPagination(int(total), setting.UI.ExplorePagingNum, page, 5) pager := context.NewPagination(total, setting.UI.ExplorePagingNum, page, 5)
ctx.Data["Title"] = ctx.Tr("repo.settings.lfs") ctx.Data["Title"] = ctx.Tr("repo.settings.lfs")
ctx.Data["PageIsSettingsLFS"] = true ctx.Data["PageIsSettingsLFS"] = true
lfsMetaObjects, err := git_model.GetLFSMetaObjects(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) lfsMetaObjects, err := git_model.GetLFSMetaObjects(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum)
@@ -83,7 +83,7 @@ func LFSLocks(ctx *context.Context) {
} }
ctx.Data["Total"] = total ctx.Data["Total"] = total
pager := context.NewPagination(int(total), setting.UI.ExplorePagingNum, page, 5) pager := context.NewPagination(total, setting.UI.ExplorePagingNum, page, 5)
ctx.Data["Title"] = ctx.Tr("repo.settings.lfs_locks") ctx.Data["Title"] = ctx.Tr("repo.settings.lfs_locks")
ctx.Data["PageIsSettingsLFS"] = true ctx.Data["PageIsSettingsLFS"] = true
lfsLocks, err := git_model.GetLFSLockByRepoID(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum) lfsLocks, err := git_model.GetLFSLockByRepoID(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum)

View File

@@ -345,7 +345,7 @@ func RenderUserCards(ctx *context.Context, total int, getter func(opts db.ListOp
if page <= 0 { if page <= 0 {
page = 1 page = 1
} }
pager := context.NewPagination(total, setting.ItemsPerPage, page, 5) pager := context.NewPagination(int64(total), setting.ItemsPerPage, page, 5)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
items, err := getter(db.ListOptions{ items, err := getter(db.ListOptions{
@@ -403,7 +403,7 @@ func Forks(ctx *context.Context) {
return return
} }
pager := context.NewPagination(int(total), pageSize, page, 5) pager := context.NewPagination(total, pageSize, page, 5)
ctx.Data["ShowRepoOwnerAvatar"] = true ctx.Data["ShowRepoOwnerAvatar"] = true
ctx.Data["ShowRepoOwnerOnList"] = true ctx.Data["ShowRepoOwnerOnList"] = true
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -371,7 +371,7 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry)
return nil, nil return nil, nil
} }
pager := context.NewPagination(int(commitsCount), setting.Git.CommitsRangeSize, page, 5) pager := context.NewPagination(commitsCount, setting.Git.CommitsRangeSize, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -159,7 +159,7 @@ func Runners(ctx *context.Context) {
ctx.Data["RunnerRepoID"] = opts.RepoID ctx.Data["RunnerRepoID"] = opts.RepoID
ctx.Data["SortType"] = opts.Sort ctx.Data["SortType"] = opts.Sort
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
@@ -220,7 +220,7 @@ func RunnersEdit(ctx *context.Context) {
} }
ctx.Data["Tasks"] = tasks ctx.Data["Tasks"] = tasks
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) pager := context.NewPagination(count, opts.PageSize, opts.Page, 5)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, rCtx.RunnerEditTemplate) ctx.HTML(http.StatusOK, rCtx.RunnerEditTemplate)

View File

@@ -59,7 +59,7 @@ func CodeSearch(ctx *context.Context) {
} }
var ( var (
total int total int64
searchResults []*code_indexer.Result searchResults []*code_indexer.Result
searchResultLanguages []*code_indexer.SearchResultLanguages searchResultLanguages []*code_indexer.SearchResultLanguages
) )

View File

@@ -301,15 +301,15 @@ func Milestones(ctx *context.Context) {
return !showRepoIDs.Contains(v) return !showRepoIDs.Contains(v)
}) })
var pagerCount int var pagerCount int64
if isShowClosed { if isShowClosed {
ctx.Data["State"] = "closed" ctx.Data["State"] = "closed"
ctx.Data["Total"] = totalMilestoneStats.ClosedCount ctx.Data["Total"] = totalMilestoneStats.ClosedCount
pagerCount = int(milestoneStats.ClosedCount) pagerCount = milestoneStats.ClosedCount
} else { } else {
ctx.Data["State"] = "open" ctx.Data["State"] = "open"
ctx.Data["Total"] = totalMilestoneStats.OpenCount ctx.Data["Total"] = totalMilestoneStats.OpenCount
pagerCount = int(milestoneStats.OpenCount) pagerCount = milestoneStats.OpenCount
} }
ctx.Data["Milestones"] = milestones ctx.Data["Milestones"] = milestones
@@ -578,11 +578,11 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
} }
// Will be posted to ctx.Data. // Will be posted to ctx.Data.
var shownIssues int var shownIssues int64
if !isShowClosed { if !isShowClosed {
shownIssues = int(issueStats.OpenCount) shownIssues = issueStats.OpenCount
} else { } else {
shownIssues = int(issueStats.ClosedCount) shownIssues = issueStats.ClosedCount
} }
ctx.Data["IsShowClosed"] = isShowClosed ctx.Data["IsShowClosed"] = isShowClosed

View File

@@ -61,11 +61,11 @@ func prepareUserNotificationsData(ctx *context.Context) {
return return
} }
pager := context.NewPagination(int(total), perPage, page, 5) pager := context.NewPagination(total, perPage, page, 5)
if pager.Paginater.Current() < page { if pager.Paginater.Current() < page {
// use the last page if the requested page is more than total pages // use the last page if the requested page is more than total pages
page = pager.Paginater.Current() page = pager.Paginater.Current()
pager = context.NewPagination(int(total), perPage, page, 5) pager = context.NewPagination(total, perPage, page, 5)
} }
statuses := []activities_model.NotificationStatus{queryStatus, activities_model.NotificationStatusPinned} statuses := []activities_model.NotificationStatus{queryStatus, activities_model.NotificationStatusPinned}
@@ -286,7 +286,7 @@ func NotificationSubscriptions(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("notification.subscriptions") ctx.Data["Title"] = ctx.Tr("notification.subscriptions")
// redirect to last page if request page is more than total pages // redirect to last page if request page is more than total pages
pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5) pager := context.NewPagination(count, setting.UI.IssuePagingNum, page, 5)
if pager.Paginater.Current() < page { if pager.Paginater.Current() < page {
ctx.Redirect(fmt.Sprintf("/notifications/subscriptions?page=%d", pager.Paginater.Current())) ctx.Redirect(fmt.Sprintf("/notifications/subscriptions?page=%d", pager.Paginater.Current()))
return return
@@ -370,12 +370,11 @@ func NotificationWatching(ctx *context.Context) {
ctx.ServerError("SearchRepository", err) ctx.ServerError("SearchRepository", err)
return return
} }
total := int(count) ctx.Data["Total"] = count
ctx.Data["Total"] = total
ctx.Data["Repos"] = repos ctx.Data["Repos"] = repos
// redirect to last page if request page is more than total pages // redirect to last page if request page is more than total pages
pager := context.NewPagination(total, setting.UI.User.RepoPagingNum, page, 5) pager := context.NewPagination(count, setting.UI.User.RepoPagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -127,7 +127,7 @@ func ListPackages(ctx *context.Context) {
ctx.Data["IsOrganizationOwner"] = false ctx.Data["IsOrganizationOwner"] = false
} }
} }
pager := context.NewPagination(int(total), setting.UI.PackagesPagingNum, page, 5) pager := context.NewPagination(total, setting.UI.PackagesPagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplPackagesList) ctx.HTML(http.StatusOK, tplPackagesList)
@@ -412,7 +412,7 @@ func ListPackageVersions(ctx *context.Context) {
ctx.Data["Total"] = total ctx.Data["Total"] = total
pager := context.NewPagination(int(total), setting.UI.PackagesPagingNum, page, 5) pager := context.NewPagination(total, setting.UI.PackagesPagingNum, page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager

View File

@@ -102,7 +102,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
var ( var (
repos []*repo_model.Repository repos []*repo_model.Repository
count int64 count int64
total int total int64
curRows int curRows int
orderBy db.SearchOrderBy orderBy db.SearchOrderBy
) )
@@ -157,10 +157,10 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
switch tab { switch tab {
case "followers": case "followers":
ctx.Data["Cards"] = followers ctx.Data["Cards"] = followers
total = int(numFollowers) total = numFollowers
case "following": case "following":
ctx.Data["Cards"] = following ctx.Data["Cards"] = following
total = int(numFollowing) total = numFollowing
case "activity": case "activity":
if setting.Service.EnableUserHeatmap && activities_model.ActivityReadable(ctx.ContextUser, ctx.Doer) { if setting.Service.EnableUserHeatmap && activities_model.ActivityReadable(ctx.ContextUser, ctx.Doer) {
ctx.Data["EnableHeatmap"] = true ctx.Data["EnableHeatmap"] = true
@@ -218,7 +218,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
return return
} }
total = int(count) total = count
case "watching": case "watching":
repos, count, err = repo_model.SearchRepository(ctx, repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
@@ -245,7 +245,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
return return
} }
total = int(count) total = count
case "overview": case "overview":
if bytes, err := profileReadme.GetBlobContent(setting.UI.MaxDisplayFileSize); err != nil { if bytes, err := profileReadme.GetBlobContent(setting.UI.MaxDisplayFileSize); err != nil {
log.Error("failed to GetBlobContent: %v", err) log.Error("failed to GetBlobContent: %v", err)
@@ -273,7 +273,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
return return
} }
ctx.Data["Cards"] = orgs ctx.Data["Cards"] = orgs
total = int(count) total = count
default: // default to "repositories" default: // default to "repositories"
repos, count, err = repo_model.SearchRepository(ctx, repo_model.SearchRepoOptions{ repos, count, err = repo_model.SearchRepository(ctx, repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
@@ -300,7 +300,7 @@ func prepareUserProfileTabData(ctx *context.Context, profileDbRepo *repo_model.R
return return
} }
total = int(count) total = count
} }
ctx.Data["Repos"] = repos ctx.Data["Repos"] = repos
ctx.Data["Total"] = total ctx.Data["Total"] = total

View File

@@ -222,7 +222,7 @@ func Organization(ctx *context.Context) {
} }
ctx.Data["Orgs"] = orgs ctx.Data["Orgs"] = orgs
pager := context.NewPagination(int(total), opts.PageSize, opts.Page, 5) pager := context.NewPagination(total, opts.PageSize, opts.Page, 5)
pager.AddParamFromRequest(ctx.Req) pager.AddParamFromRequest(ctx.Req)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplSettingsOrganization) ctx.HTML(http.StatusOK, tplSettingsOrganization)
@@ -244,13 +244,13 @@ func Repos(ctx *context.Context) {
if opts.Page <= 0 { if opts.Page <= 0 {
opts.Page = 1 opts.Page = 1
} }
start := (opts.Page - 1) * opts.PageSize start := int64((opts.Page - 1) * opts.PageSize)
end := start + opts.PageSize end := start + int64(opts.PageSize)
adoptOrDelete := ctx.IsUserSiteAdmin() || (setting.Repository.AllowAdoptionOfUnadoptedRepositories && setting.Repository.AllowDeleteOfUnadoptedRepositories) adoptOrDelete := ctx.IsUserSiteAdmin() || (setting.Repository.AllowAdoptionOfUnadoptedRepositories && setting.Repository.AllowDeleteOfUnadoptedRepositories)
ctxUser := ctx.Doer ctxUser := ctx.Doer
count := 0 var count int64
if adoptOrDelete { if adoptOrDelete {
repoNames := make([]string, 0, setting.UI.Admin.UserPagingNum) repoNames := make([]string, 0, setting.UI.Admin.UserPagingNum)
@@ -310,12 +310,12 @@ func Repos(ctx *context.Context) {
ctx.Data["Dirs"] = repoNames ctx.Data["Dirs"] = repoNames
ctx.Data["ReposMap"] = repos ctx.Data["ReposMap"] = repos
} else { } else {
repos, count64, err := repo_model.GetUserRepositories(ctx, repo_model.SearchRepoOptions{Actor: ctxUser, Private: true, ListOptions: opts}) repos, reposCount, err := repo_model.GetUserRepositories(ctx, repo_model.SearchRepoOptions{Actor: ctxUser, Private: true, ListOptions: opts})
if err != nil { if err != nil {
ctx.ServerError("GetUserRepositories", err) ctx.ServerError("GetUserRepositories", err)
return return
} }
count = int(count64) count = reposCount
for i := range repos { for i := range repos {
if repos[i].IsFork { if repos[i].IsFork {

View File

@@ -163,7 +163,7 @@ func GetAPIContext(req *http.Request) *APIContext {
return req.Context().Value(apiContextKey).(*APIContext) return req.Context().Value(apiContextKey).(*APIContext)
} }
func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string { func genAPILinks(curURL *url.URL, total int64, pageSize, curPage int) []string {
page := NewPagination(total, pageSize, curPage, 0) page := NewPagination(total, pageSize, curPage, 0)
paginater := page.Paginater paginater := page.Paginater
links := make([]string, 0, 4) links := make([]string, 0, 4)
@@ -204,7 +204,8 @@ func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
} }
// SetLinkHeader sets pagination link header by given total number and page size. // SetLinkHeader sets pagination link header by given total number and page size.
func (ctx *APIContext) SetLinkHeader(total, pageSize int) { // "count" is usually from database result "count int64", so it also uses int64,
func (ctx *APIContext) SetLinkHeader(total int64, pageSize int) {
links := genAPILinks(ctx.Req.URL, total, pageSize, ctx.FormInt("page")) links := genAPILinks(ctx.Req.URL, total, pageSize, ctx.FormInt("page"))
if len(links) > 0 { if len(links) > 0 {

View File

@@ -6,6 +6,7 @@ package context
import ( import (
"fmt" "fmt"
"html/template" "html/template"
"math"
"net/http" "net/http"
"net/url" "net/url"
"slices" "slices"
@@ -22,11 +23,13 @@ type Pagination struct {
} }
// NewPagination creates a new instance of the Pagination struct. // NewPagination creates a new instance of the Pagination struct.
// "total" is usually from database result "count int64", so it also uses int64
// "pagingNum" is "page size" or "limit", "current" is "page" // "pagingNum" is "page size" or "limit", "current" is "page"
// total=-1 means only showing prev/next // total=-1 means only showing prev/next
func NewPagination(total, pagingNum, current, numPages int) *Pagination { func NewPagination(total int64, pagingNum, current, numPages int) *Pagination {
totalInt := int(min(total, int64(math.MaxInt)))
p := &Pagination{} p := &Pagination{}
p.Paginater = paginator.New(total, pagingNum, current, numPages) p.Paginater = paginator.New(totalInt, pagingNum, current, numPages)
return p return p
} }

View File

@@ -18,10 +18,10 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
) )
func GetFeedsForDashboard(ctx context.Context, opts activities_model.GetFeedsOptions) (activities_model.ActionList, int, error) { func GetFeedsForDashboard(ctx context.Context, opts activities_model.GetFeedsOptions) (activities_model.ActionList, int64, error) {
opts.DontCount = opts.RequestedTeam == nil && opts.Date == "" opts.DontCount = opts.RequestedTeam == nil && opts.Date == ""
results, cnt, err := activities_model.GetFeeds(ctx, opts) results, cnt, err := activities_model.GetFeeds(ctx, opts)
return results, util.Iif(opts.DontCount, -1, int(cnt)), err return results, util.Iif(opts.DontCount, -1, cnt), err
} }
// GetFeeds returns actions according to the provided options // GetFeeds returns actions according to the provided options

View File

@@ -240,16 +240,15 @@ func DeleteUnadoptedRepository(ctx context.Context, doer, u *user_model.User, re
type unadoptedRepositories struct { type unadoptedRepositories struct {
repositories []string repositories []string
index int count int64
start int start, end int64
end int
} }
func (unadopted *unadoptedRepositories) add(repository string) { func (unadopted *unadoptedRepositories) add(repository string) {
if unadopted.index >= unadopted.start && unadopted.index < unadopted.end { if unadopted.count >= unadopted.start && unadopted.count < unadopted.end {
unadopted.repositories = append(unadopted.repositories, repository) unadopted.repositories = append(unadopted.repositories, repository)
} }
unadopted.index++ unadopted.count++
} }
func checkUnadoptedRepositories(ctx context.Context, userName string, repoNamesToCheck []string, unadopted *unadoptedRepositories) error { func checkUnadoptedRepositories(ctx context.Context, userName string, repoNamesToCheck []string, unadopted *unadoptedRepositories) error {
@@ -291,7 +290,7 @@ func checkUnadoptedRepositories(ctx context.Context, userName string, repoNamesT
} }
// ListUnadoptedRepositories lists all the unadopted repositories that match the provided query // ListUnadoptedRepositories lists all the unadopted repositories that match the provided query
func ListUnadoptedRepositories(ctx context.Context, query string, opts *db.ListOptions) ([]string, int, error) { func ListUnadoptedRepositories(ctx context.Context, query string, opts *db.ListOptions) ([]string, int64, error) {
globUser, _ := glob.Compile("*") globUser, _ := glob.Compile("*")
globRepo, _ := glob.Compile("*") globRepo, _ := glob.Compile("*")
@@ -311,12 +310,12 @@ func ListUnadoptedRepositories(ctx context.Context, query string, opts *db.ListO
} }
var repoNamesToCheck []string var repoNamesToCheck []string
start := (opts.Page - 1) * opts.PageSize start := int64((opts.Page - 1) * opts.PageSize)
unadopted := &unadoptedRepositories{ unadopted := &unadoptedRepositories{
repositories: make([]string, 0, opts.PageSize), repositories: make([]string, 0, opts.PageSize),
start: start, start: start,
end: start + opts.PageSize, end: start + int64(opts.PageSize),
index: 0, count: 0,
} }
var userName string var userName string
@@ -372,5 +371,5 @@ func ListUnadoptedRepositories(ctx context.Context, query string, opts *db.ListO
return nil, 0, err return nil, 0, err
} }
return unadopted.repositories, unadopted.index, nil return unadopted.repositories, unadopted.count, nil
} }

View File

@@ -20,20 +20,20 @@ import (
) )
func TestCheckUnadoptedRepositories_Add(t *testing.T) { func TestCheckUnadoptedRepositories_Add(t *testing.T) {
start := 10 const start = 10
end := 20 const end = 20
unadopted := &unadoptedRepositories{ unadopted := &unadoptedRepositories{
start: start, start: start,
end: end, end: end,
index: 0, count: 0,
} }
total := 30 const total = 30
for range total { for range total {
unadopted.add("something") unadopted.add("something")
} }
assert.Equal(t, total, unadopted.index) assert.EqualValues(t, total, unadopted.count)
assert.Len(t, unadopted.repositories, end-start) assert.Len(t, unadopted.repositories, end-start)
} }
@@ -64,7 +64,7 @@ func TestCheckUnadoptedRepositories(t *testing.T) {
err = checkUnadoptedRepositories(t.Context(), userName, []string{repoName}, unadopted) err = checkUnadoptedRepositories(t.Context(), userName, []string{repoName}, unadopted)
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, unadopted.repositories) assert.Empty(t, unadopted.repositories)
assert.Equal(t, 0, unadopted.index) assert.Zero(t, unadopted.count)
} }
func TestListUnadoptedRepositories_ListOptions(t *testing.T) { func TestListUnadoptedRepositories_ListOptions(t *testing.T) {
@@ -78,13 +78,13 @@ func TestListUnadoptedRepositories_ListOptions(t *testing.T) {
opts := db.ListOptions{Page: 1, PageSize: 1} opts := db.ListOptions{Page: 1, PageSize: 1}
repoNames, count, err := ListUnadoptedRepositories(t.Context(), "", &opts) repoNames, count, err := ListUnadoptedRepositories(t.Context(), "", &opts)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, count) assert.EqualValues(t, 2, count)
assert.Equal(t, unadoptedList[0], repoNames[0]) assert.Equal(t, unadoptedList[0], repoNames[0])
opts = db.ListOptions{Page: 2, PageSize: 1} opts = db.ListOptions{Page: 2, PageSize: 1}
repoNames, count, err = ListUnadoptedRepositories(t.Context(), "", &opts) repoNames, count, err = ListUnadoptedRepositories(t.Context(), "", &opts)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, count) assert.EqualValues(t, 2, count)
assert.Equal(t, unadoptedList[1], repoNames[0]) assert.Equal(t, unadoptedList[1], repoNames[0])
} }