/** * 从 GitHub 拉 Termux 的 terminal-emulator / terminal-view 源码树(Apache-2.0)。 * raw.githubusercontent 在本机不通,所以走 api.github.com 的 raw 模式。 * * 用法: node scripts/fetch-termux-terminal.mjs */ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const REF = 'v0.118.3'; const REPO = 'termux/termux-app'; /** 目标:把这些模块的 src 全量拷到 app/src/main/ 下(java + res) */ const MODULES = [ { name: 'terminal-emulator', destJava: 'app/src/main/java', wantRes: false }, { name: 'terminal-view', destJava: 'app/src/main/java', wantRes: true }, ]; async function api(url, raw = false) { for (let i = 1; i <= 4; i += 1) { try { const res = await fetch(url, { headers: { 'User-Agent': 'node', Accept: raw ? 'application/vnd.github.raw' : 'application/vnd.github+json', }, signal: AbortSignal.timeout(60000), }); if (res.status === 404) return null; if (!res.ok) throw new Error(`HTTP ${res.status}`); return raw ? await res.text() : await res.json(); } catch (err) { console.log(` 重试 ${i}/4:${err.message}`); await new Promise((r) => setTimeout(r, 1500 * i)); } } throw new Error(`拉取失败:${url}`); } async function listDir(dirPath) { const url = `https://api.github.com/repos/${REPO}/contents/${dirPath}?ref=${REF}`; return (await api(url)) || []; } async function fetchFile(filePath) { const url = `https://api.github.com/repos/${REPO}/contents/${filePath}?ref=${REF}`; return api(url, true); } async function walk(srcDir, outDir, stats) { const entries = await listDir(srcDir); for (const entry of entries) { if (entry.type === 'dir') { await walk(entry.path, path.join(outDir, entry.name), stats); } else if (entry.type === 'file') { const text = await fetchFile(entry.path); fs.mkdirSync(outDir, { recursive: true }); fs.writeFileSync(path.join(outDir, entry.name), text, 'utf8'); stats.files += 1; stats.bytes += Buffer.byteLength(text); console.log(` + ${entry.path} (${(Buffer.byteLength(text) / 1024).toFixed(1)} KB)`); } } } const stats = { files: 0, bytes: 0 }; for (const mod of MODULES) { console.log(`\n=== ${mod.name} ===`); await walk(`${mod.name}/src/main/java`, path.join(repo, 'android', mod.destJava), stats); if (mod.wantRes) { await walk(`${mod.name}/src/main/res`, path.join(repo, 'android', 'app/src/main/res-extra'), stats); } } console.log(`\n完成:${stats.files} 个文件,共 ${(stats.bytes / 1024).toFixed(0)} KB`);