diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..d03956f --- /dev/null +++ b/.clang-format @@ -0,0 +1,27 @@ +# Config file for ClangFormat, a C/C++/... code formatter. + +BasedOnStyle: Chromium +BreakBinaryOperations: RespectPrecedence +BreakConstructorInitializers: AfterColon +AccessModifierOffset: -4 +AlignAfterOpenBracket: BlockIndent +AlignOperands: DontAlign +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortCaseLabelsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: WithoutElse +BinPackArguments: false +BreakBeforeBinaryOperators: NonAssignment +BreakStringLiterals: false +ColumnLimit: 100 +CompactNamespaces: true +IncludeBlocks: Regroup +IndentWidth: 4 +InsertNewlineAtEOF: true +LineEnding: LF +PackConstructorInitializers: Never +QualifierAlignment: Custom +QualifierOrder: ['friend', 'static', 'inline', 'constexpr', 'const', 'volatile', 'restrict', 'type'] +SeparateDefinitionBlocks: Always +SortIncludes: CaseInsensitive +SpacesBeforeTrailingComments: 1 diff --git a/.editorconfig b/.editorconfig index 5e6929a..9a6b0b6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,5 +10,5 @@ indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true -[*.{jsx,yml,yaml}] +[*.{js,jsx,ts,yml,yaml}] indent_size = 2 diff --git a/.gersemirc b/.gersemirc new file mode 100644 index 0000000..25b76ae --- /dev/null +++ b/.gersemirc @@ -0,0 +1,4 @@ +# Config file for gersemi, a CMake code formatter. + +line_length: 100 +warn_about_unknown_commands: false diff --git a/.gitignore b/.gitignore index 3b6a86f..f2c3a8f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ .vs/ +.vscode/ +*.user build/ -*.user \ No newline at end of file +node_modules/ + +package-lock.json +yarn.lock diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..7955488 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,7 @@ +**/*.md + +/build/ +/extras/EsotericSoftwareSpine/src/test/data/jsonFiles/*.json +/lib/ +/rhubarb/lib/ +/website/ diff --git a/.prettierrc.yml b/.prettierrc.yml new file mode 100644 index 0000000..78beda5 --- /dev/null +++ b/.prettierrc.yml @@ -0,0 +1,12 @@ +# Config file for Prettier, a JavaScript/TypeScript/... code formatter. + +tabWidth: 2 +printWidth: 100 +singleQuote: true +arrowParens: avoid +experimentalTernaries: true + +overrides: + - files: '*.jsx' # Adobe JSX, not React + options: + trailingComma: none diff --git a/package.json b/package.json new file mode 100644 index 0000000..f303dd7 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "rhubarb-lip-sync", + "version": "1.14.0", + "description": "Rhubarb Lip Sync", + "repository": "https://github.com/DanielSWolf/rhubarb-lip-sync.git", + "author": "Daniel Wolf ", + "license": "MIT", + "type": "module", + "scripts": { + "check": "tsx scripts/bin/check.ts", + "fix": "tsx scripts/bin/fix.ts" + }, + "dependencies": { + "7zip-bin-full": "^25.1.1", + "@types/fs-extra": "^11.0.4", + "@types/node": "^24.3.0", + "cli-progress": "^3.12.0", + "execa": "^9.6.0", + "fs-extra": "^11.3.1", + "glob": "^11.0.3", + "moize": "^6.1.6", + "prettier": "^3.6.2", + "tsx": "^4.20.4" + }, + "customDependencies": { + "clangFormat": "20@master-796e77c", + "gersemi": "0.22.2", + "uv": "0.8.17" + } +} diff --git a/scripts/bin/check.ts b/scripts/bin/check.ts new file mode 100644 index 0000000..511547e --- /dev/null +++ b/scripts/bin/check.ts @@ -0,0 +1,10 @@ +// Checks whether all code is properly formatted. +// Exits with a non-zero code if any formatting issues are found. + +import { checkCodeFormatting } from '../code-formatting'; + +async function main() { + await checkCodeFormatting(); +} + +main(); diff --git a/scripts/bin/fix.ts b/scripts/bin/fix.ts new file mode 100644 index 0000000..b141a3d --- /dev/null +++ b/scripts/bin/fix.ts @@ -0,0 +1,9 @@ +// Fixes any code formatting issues in the project. + +import { fixCodeFormatting } from '../code-formatting'; + +async function main() { + await fixCodeFormatting(); +} + +main(); diff --git a/scripts/code-formatting.ts b/scripts/code-formatting.ts new file mode 100644 index 0000000..b45b801 --- /dev/null +++ b/scripts/code-formatting.ts @@ -0,0 +1,111 @@ +import { ExternalCli, device, throwError } from './util'; +import { glob } from 'glob'; +import { execa } from 'execa'; +import { repoDir } from './repo-dir'; + +const customDependencies = require('../package.json').customDependencies as Record; + +type Action = 'check' | 'fix'; + +const allRunners = [runClangFormat, runPrettier, runGersemi]; + +/** Checks whether all code in the repo is formatted; throws otherwise. */ +export async function checkCodeFormatting() { + let failed = false; + await Promise.all( + allRunners + .map(runner => runner('check')) + .map(promise => + promise.catch(error => { + console.error(error.message); + failed = true; + }), + ), + ); + if (failed) + throw new Error('Some files are not properly formatted. Run `npm run fix` to fix them.'); +} + +/** Formats all code in the repo. */ +export async function fixCodeFormatting() { + await Promise.all(allRunners.map(runner => runner('fix'))); +} + +/** Runs ClangFormat, a C/C++/... code formatter. */ +async function runClangFormat(action: Action) { + const files = await glob('rhubarb/{src,tests}/**/*.{c,h,cpp,hpp}', { cwd: repoDir, nodir: true }); + await clangFormat.run( + 'clang-format', + [action === 'check' ? '--dry-run' : '-i', '--Werror', ...files], + { cwd: repoDir }, + ); +} + +/** Runs Prettier, a JavaScript/TypeScript/... code formatter. */ +async function runPrettier(action: Action) { + await execa( + 'node', + ['node_modules/prettier/bin/prettier.cjs', action === 'check' ? '--check' : '--write', '.'], + { + cwd: repoDir, + stdio: 'inherit', + }, + ); +} + +/** Runs gersemi, a CMake code formatter. */ +async function runGersemi(action: Action) { + const files = await glob('{,rhubarb/,extras/**/}{CMakeLists.txt,*.cmake}', { + cwd: repoDir, + nodir: true, + }); + await uv.run( + 'uvx', + [ + `gersemi@${customDependencies.gersemi}`, + action === 'check' ? '--check' : '--in-place', + ...files, + ], + { cwd: repoDir }, + ); +} + +const clangFormat = new ExternalCli({ + prettyName: 'ClangFormat', + identifier: 'clang-format', + version: customDependencies.clangFormat, + getDownloadUrl: version => { + const [clangVersion, release] = version.split('@'); + const basename = + { + 'windows-amd64': `clang-format-${clangVersion}_windows-amd64.exe`, + 'windows-arm64': null, + 'macos-amd64': `clang-format-${clangVersion}_macosx-amd64`, + 'macos-arm64': `clang-format-${clangVersion}_macos-arm-arm64`, + 'linux-amd64': `clang-format-${clangVersion}_linux-amd64`, + 'linux-arm64': null, + }[device.platform] ?? + throwError(`No clang-format binary found for platform ${device.platform}.`); + const releasesUrl = 'https://github.com/muttleyxd/clang-tools-static-binaries/releases'; + return `${releasesUrl}/download/${release}/${basename}`; + }, + archiveKind: 'uncompressed', +}); + +const uv = new ExternalCli({ + prettyName: 'uv Python package manager', + identifier: 'uv', + version: customDependencies.uv, + getDownloadUrl: version => { + const basename = { + 'windows-amd64': 'uv-x86_64-pc-windows-msvc.zip', + 'windows-arm64': 'uv-aarch64-pc-windows-msvc.zip', + 'macos-amd64': 'uv-x86_64-apple-darwin.tar.gz', + 'macos-arm64': 'uv-aarch64-apple-darwin.tar.gz', + 'linux-amd64': 'uv-x86_64-unknown-linux-gnu.tar.gz', + 'linux-arm64': 'uv-aarch64-unknown-linux-gnu.tar.gz', + }[device.platform]; + const releasesUrl = 'https://github.com/astral-sh/uv/releases'; + return `${releasesUrl}/download/${version}/${basename}`; + }, +}); diff --git a/scripts/repo-dir.ts b/scripts/repo-dir.ts new file mode 100644 index 0000000..db7133a --- /dev/null +++ b/scripts/repo-dir.ts @@ -0,0 +1,6 @@ +import { resolve as resolvePath, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const fileName = fileURLToPath(import.meta.url); +const dirName = dirname(fileName); +export const repoDir = resolvePath(dirName, '..'); diff --git a/scripts/util/device.ts b/scripts/util/device.ts new file mode 100644 index 0000000..b459995 --- /dev/null +++ b/scripts/util/device.ts @@ -0,0 +1,30 @@ +export type Platform = `${OperatingSystem}-${CpuArchitecture}`; + +export type OperatingSystem = 'windows' | 'macos' | 'linux'; + +export type CpuArchitecture = 'amd64' | 'arm64'; + +export const device = { + platform: getPlatform(), + operatingSystem: getOperatingSystem(), + cpuArchitecture: getCpuArchitecture(), +}; + +function getPlatform(): Platform { + return `${getOperatingSystem()}-${getCpuArchitecture()}`; +} + +function getOperatingSystem(): OperatingSystem { + const platform = process.platform; + if (platform === 'win32') return 'windows'; + if (platform === 'darwin') return 'macos'; + if (platform === 'linux') return 'linux'; + throw new Error(`Unsupported operating system: ${platform}`); +} + +function getCpuArchitecture(): CpuArchitecture { + const arch = process.arch; + if (arch === 'x64') return 'amd64'; + if (arch === 'arm64') return 'arm64'; + throw new Error(`Unsupported architecture: ${arch}`); +} diff --git a/scripts/util/download-and-extract-with-progress.ts b/scripts/util/download-and-extract-with-progress.ts new file mode 100644 index 0000000..9c8b104 --- /dev/null +++ b/scripts/util/download-and-extract-with-progress.ts @@ -0,0 +1,106 @@ +import * as path from 'path'; +import * as os from 'os'; +import fs from 'fs-extra'; +import moize from 'moize'; +import { path7z } from '7zip-bin-full'; +import { execa } from 'execa'; +import { downloadWithProgress } from './download-with-progress'; + +/** + * Downloads an archive from the given URL and extracts it into the given target directory, + * flattening single-child directory hierarchies. + * Shows a progress bar during download. + */ +export const downloadAndExtractWithProgress = moize( + async (url: string, targetDir: string, options: DownloadExtractOptions = {}): Promise => { + const description = options.description ?? 'archive file'; + const tempArchivePath = path.join(os.tmpdir(), encodeURIComponent(url)); + if (!fs.existsSync(tempArchivePath)) { + await downloadWithProgress(url, tempArchivePath, description); + } + + console.log(`Extracting ${description}.`); + const archiveKind = options.archiveKind ?? detectArchiveKindFromUrl(url); + fs.emptyDirSync(targetDir); + await extractArchive(tempArchivePath, archiveKind, targetDir); + + flattenSingleChildDirectories(targetDir); + }, + { maxSize: 1000, isDeepEqual: true }, +); + +export interface DownloadExtractOptions { + /** File description used in progress messages. Default: "archive file" */ + description?: string; + + /** The kind of the archive. If not given, it is inferred from the URL. */ + archiveKind?: ArchiveKind; +} + +const allArchiveKinds = ['tar.gz', 'tgz', 'tar.xz', 'tar.bz2', 'tar', 'zip', '7z'] as const; + +export type ArchiveKind = (typeof allArchiveKinds)[number]; + +function detectArchiveKindFromUrl(url: string): ArchiveKind { + const pathname = decodeURIComponent(new URL(url).pathname.toLowerCase()); + const kind = allArchiveKinds.find(kind => pathname.endsWith(`.${kind}`)); + if (!kind) throw new Error(`Unsupported archive type in URL: ${url}`); + return kind; +} + +/** Extracts the given archive file into the given output directory. */ +async function extractArchive( + archivePath: string, + archiveKind: ArchiveKind, + outputDirectory: string, +): Promise { + // Deactivate symlink security checks in 7-Zip, as they prevent extracting valid archives + // https://sourceforge.net/p/sevenzip/discussion/45797/thread/da14cd780b/#:~:text=Command%20line%20switch-,%2Dsnld20,-can%20be%20used + const allowSymlinks = '-snld20'; + + // Extract single-stage archives + const singleStageKinds = new Set(['tar', 'zip', '7z']); + if (singleStageKinds.has(archiveKind)) { + await execa(path7z, ['x', archivePath, allowSymlinks, '-y', `-o${outputDirectory}`], { + stdio: 'inherit', + }); + return; + } + + // Extract multi-stage archives into a temp dir first + const stageDir = getTempPath('stage'); + try { + await execa(path7z, ['x', archivePath, '-y', `-o${stageDir}`], { stdio: 'inherit' }); + + const entries = await fs.promises.readdir(stageDir, { withFileTypes: true }); + const tar = entries + .filter(e => e.isFile() && e.name.toLowerCase().endsWith('.tar')) + .map(e => path.join(stageDir, e.name))[0]; + if (!tar) throw new Error(`No .tar file found in ${stageDir}.`); + + await execa(path7z, ['x', tar, '-y', allowSymlinks, `-o${outputDirectory}`], { + stdio: 'inherit', + }); + } finally { + await fs.promises.rm(stageDir, { recursive: true, force: true }); + } +} + +function flattenSingleChildDirectories(dir: string): void { + while (true) { + const children = fs.readdirSync(dir, { withFileTypes: true }); + if (children.length !== 1) return; + + const child = children[0]; + if (!child.isDirectory()) return; + + const tmpDir = dir + '.tmp'; + fs.moveSync(path.join(dir, child.name), tmpDir, { overwrite: true }); + fs.removeSync(dir); + fs.moveSync(tmpDir, dir); + } +} + +export function getTempPath(prefix: string): string { + return path.join(os.tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`); +} diff --git a/scripts/util/download-with-progress.ts b/scripts/util/download-with-progress.ts new file mode 100644 index 0000000..ce1b535 --- /dev/null +++ b/scripts/util/download-with-progress.ts @@ -0,0 +1,75 @@ +import { SingleBar, Presets } from 'cli-progress'; +import fs from 'fs-extra'; +import * as http from 'http'; +import * as https from 'https'; +import * as path from 'path'; +import { getTempPath } from './download-and-extract-with-progress'; + +/** Downloads a file to the given path, showing a progress bar. */ +export const downloadWithProgress = ( + url: string, + targetPath: string, + description: string, +): Promise => + new Promise((resolve, reject) => { + const lib = url.startsWith('https:') ? https : http; + const req = lib.get(url, res => { + // Redirects + if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + res.resume(); + const next = new URL(res.headers.location, url).toString(); + downloadWithProgress(next, targetPath, description).then(resolve, reject); + return; + } + if (res.statusCode !== 200) { + reject(new Error(`HTTP ${res.statusCode} for ${url}`)); + res.resume(); + return; + } + + const total = Number(res.headers['content-length'] || 0); + const tempPath = getTempPath('download'); + const out = fs.createWriteStream(tempPath); + + const bar = new SingleBar( + { + format: + total > 0 ? + `Downloading ${description}. [{bar}] {percentage}% | {value}/{total} MB` + : `Downloading ${description}. [{bar}] {value} MB`, + hideCursor: true, + barsize: 20, + formatValue: (value, _, type) => + type === 'percentage' && typeof value === 'number' ? value.toFixed(1) + : type === 'value' || type === 'total' ? (value / 1024 / 1024).toFixed(1) + : String(value), + }, + Presets.shades_classic, + ); + bar.start(total, 0); + + let downloaded = 0; + + res.on('data', (chunk: Buffer) => { + downloaded += chunk.length; + bar.update(downloaded); + }); + + res.pipe(out); + out.on('finish', () => { + out.close(() => { + bar.update(total > 0 ? total : downloaded); + bar.stop(); + fs.ensureDirSync(path.dirname(targetPath)); + fs.moveSync(tempPath, targetPath, { overwrite: true }); + resolve(undefined); + }); + }); + out.on('error', err => { + bar.stop(); + reject(err); + }); + }); + + req.on('error', reject); + }); diff --git a/scripts/util/external-cli.ts b/scripts/util/external-cli.ts new file mode 100644 index 0000000..1f02444 --- /dev/null +++ b/scripts/util/external-cli.ts @@ -0,0 +1,67 @@ +import { execa, Options as ExecaOptions, ResultPromise as ExecaResultPromise } from 'execa'; +import { extname, join as joinPaths } from 'path'; +import os from 'os'; +import fs from 'fs'; +import { ArchiveKind, downloadAndExtractWithProgress } from './download-and-extract-with-progress'; +import { device } from './device'; +import { chmod } from 'fs/promises'; +import { downloadWithProgress } from './download-with-progress'; + +/** An external command-line tool offering one or more commands. */ +export class ExternalCli { + constructor(readonly spec: ExternalCliSpec) {} + + async run( + file: string, + args: string[], + options?: TOptions, + ): Promise> { + const { spec } = this; + const { platform } = device; + const cliPath = joinPaths( + os.tmpdir(), + 'external-clis', + `${spec.identifier}-${spec.version}-${platform}`, + ); + if (!fs.existsSync(cliPath)) { + const url = spec.getDownloadUrl(spec.version); + if (spec.archiveKind === 'uncompressed') { + const extension = extname(decodeURIComponent(new URL(url).pathname)); + const targetPath = joinPaths(cliPath, `${spec.identifier}${extension}`); + await downloadWithProgress(url, targetPath, spec.prettyName); + } else { + await downloadAndExtractWithProgress(url, cliPath, { + description: spec.prettyName, + archiveKind: spec.archiveKind, + }); + } + } + + const binPath = joinPaths(cliPath, spec.binDir ?? '', file); + if (device.operatingSystem !== 'windows') await chmod(binPath, 0o755); // Make executable + return execa(binPath, args, { stdio: 'inherit', ...(options ?? {}) } as TOptions); + } +} + +export interface ExternalCliSpec { + /** The official, pretty name of the tool. */ + prettyName: string; + + /** The kebab-case, identifier-style name of the tool. */ + identifier: string; + + /** The tool version, according to the tool's official versioning. */ + version: string; + + /** + * The path of the bin directory, relative to the archive file. + * Defaults to empty. + */ + binDir?: string; + + /** The kind of the archive. If not given, it is inferred from the URL. */ + archiveKind?: ArchiveKind | 'uncompressed'; + + /** Returns the URL for the portable binary release for the given version and platform. */ + getDownloadUrl: (version: string) => string; +} diff --git a/scripts/util/index.ts b/scripts/util/index.ts new file mode 100644 index 0000000..addb8c5 --- /dev/null +++ b/scripts/util/index.ts @@ -0,0 +1,5 @@ +export * from './device'; +export * from './download-and-extract-with-progress'; +export * from './download-with-progress'; +export * from './external-cli'; +export * from './throw-error'; diff --git a/scripts/util/throw-error.ts b/scripts/util/throw-error.ts new file mode 100644 index 0000000..79ca411 --- /dev/null +++ b/scripts/util/throw-error.ts @@ -0,0 +1,3 @@ +export function throwError(message: string): never { + throw new Error(message); +}