|
| 1 | +import {z} from 'zod'; |
| 2 | + |
| 3 | +const GitTreeItemSchema = z.object({ |
| 4 | + mode: z.string(), |
| 5 | + path: z.string(), |
| 6 | + sha: z.string(), |
| 7 | + size: z.number().optional(), |
| 8 | + type: z.enum(['blob', 'tree', 'commit']), |
| 9 | + url: z.url(), |
| 10 | +}); |
| 11 | + |
| 12 | +const GitTreeResponseSchema = z.object({ |
| 13 | + sha: z.string(), |
| 14 | + tree: z.array(GitTreeItemSchema), |
| 15 | + truncated: z.boolean(), |
| 16 | + url: z.url(), |
| 17 | +}); |
| 18 | + |
| 19 | +export type GitTreeResponse = z.infer<typeof GitTreeResponseSchema>; |
| 20 | + |
| 21 | +/** |
| 22 | + * Maps package names to their relative PKGBUILD paths. |
| 23 | + * @example { "linux-cachyos": "linux-cachyos", "linux-api-headers": "toolchain/linux-api-headers" } |
| 24 | + */ |
| 25 | +export type PkgbuildMap = Record<string, string>; |
| 26 | + |
| 27 | +export async function fetchPkgbuilds( |
| 28 | + params: { |
| 29 | + owner?: string; |
| 30 | + ref?: string; |
| 31 | + repo?: string; |
| 32 | + token?: string; |
| 33 | + } = {} |
| 34 | +): Promise<PkgbuildMap> { |
| 35 | + const { |
| 36 | + owner = 'CachyOS', |
| 37 | + ref = 'master', |
| 38 | + repo = 'CachyOS-PKGBUILDS', |
| 39 | + token = process.env.GITHUB_TOKEN, |
| 40 | + } = params; |
| 41 | + |
| 42 | + const url = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent( |
| 43 | + repo |
| 44 | + )}/git/trees/${encodeURIComponent(ref)}?recursive=1`; |
| 45 | + |
| 46 | + const res = await fetch(url, { |
| 47 | + headers: { |
| 48 | + Accept: 'application/vnd.github+json', |
| 49 | + 'User-Agent': 'CachyOS/public-dashboard', |
| 50 | + 'X-GitHub-Api-Version': '2022-11-28', |
| 51 | + ...(token ? {Authorization: `Bearer ${token}`} : {}), |
| 52 | + }, |
| 53 | + next: {revalidate: 3600}, |
| 54 | + }); |
| 55 | + |
| 56 | + if (!res.ok) { |
| 57 | + const text = await res.text(); |
| 58 | + throw new Error( |
| 59 | + `GitHub API error ${res.status}: ${text || res.statusText}` |
| 60 | + ); |
| 61 | + } |
| 62 | + |
| 63 | + const json = await res.json(); |
| 64 | + const data = GitTreeResponseSchema.parse(json); |
| 65 | + |
| 66 | + return data.tree |
| 67 | + .filter(node => node.path.endsWith('PKGBUILD')) |
| 68 | + .map(node => node.path.replace(/\/PKGBUILD$/, '')) |
| 69 | + .reduce((acc, path) => { |
| 70 | + acc[path.split('/').pop() ?? ''] = path; |
| 71 | + return acc; |
| 72 | + }, {} as PkgbuildMap); |
| 73 | +} |
0 commit comments