better code: reuse

Massimo Melina committed Jan 21, 2025 at 19:47 UTC 6f198d7612a5b01c5d2d47749818d54f2078138b
2 files changed +17 -21
src/github.ts
+6 -4
@@ -188,16 +188,18 @@ async function apiGithub(uri: string) {
188 })
189 }
190
191 -async function *apiGithubPaginated<T=any>(uri: string) {
191 +export async function *apiGithubPaginated<T=any>(uri: string) {
192 + uri += uri.includes('?') ? '&' : '?'
193 const PAGE_SIZE = 100
194 let page = 1
195 let n = 0
196 try {
197 while (1) {
197 - const res = await apiGithub(uri + `&page=${page++}&per_page=${PAGE_SIZE}`)
198 - for (const x of res.items)
198 + const res = await apiGithub(uri + `page=${page++}&per_page=${PAGE_SIZE}`)
199 + const a = res.items || res // "search/repositories" returns an object, while "releases" returns simply an array
200 + for (const x of a)
201 yield x as T
200 - const now = res.items.length
202 + const now = a.length
203 n += now
204 if (!now || n >= res.total_count) break
205 }
src/update.ts
+11 -17
@@ -1,6 +1,6 @@
1 // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
2
3 -import { getProjectInfo, getRepoInfo } from './github'
3 +import { apiGithubPaginated, getProjectInfo, getRepoInfo } from './github'
4 import { ARGS_FILE, HFS_REPO, IS_BINARY, IS_WINDOWS, RUNNING_BETA } from './const'
5 import { dirname, join } from 'path'
6 import { spawn, spawnSync } from 'child_process'
@@ -70,22 +70,16 @@ export async function getUpdates(strict=false) {
70
71 async function getBetas() {
72 if (!updateToBeta.get() && !RUNNING_BETA) return []
73 - let page = 1
74 - const ret = []
75 - while (1) {
76 - const per = 100
77 - const res: Release[] = await getRepoInfo(HFS_REPO + `/releases?per_page=${per}&page=${page++}`)
78 - if (!res.length) break
79 - const curV = currentVersion.getScalar()
80 - for (const x of res) {
81 - if (!x.prerelease || x.name.endsWith('-ignore')) continue
82 - const v = x.versionScalar = versionToScalar(x.name)
83 - if (v < stable.versionScalar) // we don't consider betas before stable
84 - return ret
85 - if (v === curV) continue // skip current
86 - x.isNewer = v > curV // make easy to know what's newer
87 - ret.push(x)
88 - }
73 + const ret: Release[] = []
74 + const curV = currentVersion.getScalar()
75 + for await (const x of apiGithubPaginated(`repos/${HFS_REPO}/releases`)) {
76 + if (!x.prerelease || x.name.endsWith('-ignore')) continue
77 + const v = x.versionScalar = versionToScalar(x.name)
78 + if (v < stable.versionScalar) // we don't consider betas before stable
79 + return ret
80 + if (v === curV) continue // skip current
81 + x.isNewer = v > curV // make easy to know what's newer
82 + ret.push(x)
83 }
84 return ret
85 }