72 lines
2.4 KiB
TypeScript
72 lines
2.4 KiB
TypeScript
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
import { dirname, join } from "node:path";
|
|
|
|
const root = process.cwd();
|
|
const packageJson = JSON.parse(await readFile(join(root, "package.json"), "utf8")) as { version: string };
|
|
const giteaVersion = packageJson.version;
|
|
const localeNames = ["locale_zh-CN.json"];
|
|
const localLocaleBaseDir = join(root, "options", "locale");
|
|
const remoteLocaleBaseUrl =
|
|
process.env.GITEA_LOCALE_BASE_URL ??
|
|
`https://raw.githubusercontent.com/go-gitea/gitea/v${giteaVersion}/options/locale`;
|
|
const refreshRemote = process.env.GITEA_LOCALE_REFRESH === "1" || process.argv.includes("--remote");
|
|
|
|
async function readJsonFile(path: string): Promise<Record<string, string>> {
|
|
return JSON.parse(await readFile(path, "utf8")) as Record<string, string>;
|
|
}
|
|
|
|
async function writeJsonFile(path: string, data: Record<string, string>) {
|
|
await mkdir(dirname(path), { recursive: true });
|
|
await writeFile(path, `${JSON.stringify(data, null, 2)}\n`);
|
|
}
|
|
|
|
async function fetchOfficialLocale(name: string): Promise<Record<string, string>> {
|
|
const response = await fetch(`${remoteLocaleBaseUrl}/${name}`);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`failed to fetch official locale ${name}: ${response.status} ${response.statusText}`);
|
|
}
|
|
|
|
return (await response.json()) as Record<string, string>;
|
|
}
|
|
|
|
async function readOfficialLocale(name: string): Promise<Record<string, string>> {
|
|
if (!refreshRemote) {
|
|
try {
|
|
return await readJsonFile(join(localLocaleBaseDir, name));
|
|
} catch (error) {
|
|
const code = error instanceof Error && "code" in error ? error.code : undefined;
|
|
|
|
if (code !== "ENOENT") {
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
const official = await fetchOfficialLocale(name);
|
|
await writeJsonFile(join(localLocaleBaseDir, name), official);
|
|
|
|
return official;
|
|
}
|
|
|
|
export async function syncLocales() {
|
|
await Promise.all(
|
|
localeNames.map(async (name) => {
|
|
const official = await readOfficialLocale(name);
|
|
const overrides = await readJsonFile(join(root, "options", "locale-overrides", name));
|
|
const merged = { ...official, ...overrides };
|
|
|
|
await writeJsonFile(join(root, ".gitea", "custom", "options", "locale", name), merged);
|
|
}),
|
|
);
|
|
}
|
|
|
|
if (import.meta.main) {
|
|
await syncLocales();
|
|
console.log(
|
|
refreshRemote
|
|
? `synced ${localeNames.length} locale file from ${remoteLocaleBaseUrl}`
|
|
: `synced ${localeNames.length} locale file from ${localLocaleBaseDir}`,
|
|
);
|
|
}
|