|
| 1 | +import type { DirEntry, GitProvider } from './types'; |
| 2 | +import { parseRepoUrl } from '../repositoryUrlValidation'; |
| 3 | + |
| 4 | +export class GitHubProvider implements GitProvider { |
| 5 | + async listDirectory(repoUrl: string, path: string, branch: string): Promise<DirEntry[]> { |
| 6 | + const { owner, repo } = parseRepoUrl(repoUrl); |
| 7 | + const apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${encodeURIComponent(branch)}`; |
| 8 | + const headers: Record<string, string> = { |
| 9 | + Accept: 'application/vnd.github.v3+json', |
| 10 | + 'User-Agent': 'PVEScripts-Local/1.0', |
| 11 | + }; |
| 12 | + const token = process.env.GITHUB_TOKEN; |
| 13 | + if (token) headers.Authorization = `token ${token}`; |
| 14 | + |
| 15 | + const response = await fetch(apiUrl, { headers }); |
| 16 | + if (!response.ok) { |
| 17 | + if (response.status === 403) { |
| 18 | + const err = new Error( |
| 19 | + `GitHub API rate limit exceeded. Consider setting GITHUB_TOKEN. Status: ${response.status} ${response.statusText}` |
| 20 | + ); |
| 21 | + (err as Error & { name: string }).name = 'RateLimitError'; |
| 22 | + throw err; |
| 23 | + } |
| 24 | + throw new Error(`GitHub API error: ${response.status} ${response.statusText}`); |
| 25 | + } |
| 26 | + |
| 27 | + const data = (await response.json()) as { type: string; name: string; path: string }[]; |
| 28 | + if (!Array.isArray(data)) { |
| 29 | + throw new Error('GitHub API returned unexpected response'); |
| 30 | + } |
| 31 | + return data.map((item) => ({ |
| 32 | + name: item.name, |
| 33 | + path: item.path, |
| 34 | + type: item.type === 'dir' ? ('dir' as const) : ('file' as const), |
| 35 | + })); |
| 36 | + } |
| 37 | + |
| 38 | + async downloadRawFile(repoUrl: string, filePath: string, branch: string): Promise<string> { |
| 39 | + const { owner, repo } = parseRepoUrl(repoUrl); |
| 40 | + const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(branch)}/${filePath}`; |
| 41 | + const headers: Record<string, string> = { |
| 42 | + 'User-Agent': 'PVEScripts-Local/1.0', |
| 43 | + }; |
| 44 | + const token = process.env.GITHUB_TOKEN; |
| 45 | + if (token) headers.Authorization = `token ${token}`; |
| 46 | + |
| 47 | + const response = await fetch(rawUrl, { headers }); |
| 48 | + if (!response.ok) { |
| 49 | + if (response.status === 403) { |
| 50 | + const err = new Error( |
| 51 | + `GitHub rate limit exceeded while downloading ${filePath}. Consider setting GITHUB_TOKEN.` |
| 52 | + ); |
| 53 | + (err as Error & { name: string }).name = 'RateLimitError'; |
| 54 | + throw err; |
| 55 | + } |
| 56 | + throw new Error(`Failed to download ${filePath}: ${response.status} ${response.statusText}`); |
| 57 | + } |
| 58 | + return response.text(); |
| 59 | + } |
| 60 | +} |
0 commit comments