Files
ts-scripts/python-ts/main.ts
2026-01-14 23:53:06 +08:00

85 lines
2.5 KiB
TypeScript

#!/usr/bin/env runts -- --allow-env --allow-run
import {
existsPath,
joinPath,
log,
readFileToString,
resolveFilename,
} from "https://global.hatter.ink/script/get/@12/deno-commons-mod.ts";
const PYTHON_CONFIG_FILE = "~/.config/python-config.json";
const PYTHON_VENV_DEFAULT_BASE_DIR = "~/.venv/";
interface PythonConfig {
default_version?: string;
default_profile?: string;
python_venv_base_path?: string;
versions: Map<string, PythonVersion>;
profiles?: Map<string, PythonVenv>;
}
interface PythonVersion {
version: string;
path: string;
comment?: string;
}
interface PythonVenv {
version: string;
path: string;
comment?: string;
}
async function loadPythonConfig(): Promise<PythonConfig> {
const pythonConfigFile = resolveFilename(PYTHON_CONFIG_FILE);
const pythonConfigJson = await readFileToString(pythonConfigFile);
if (!pythonConfigJson === null) {
throw `Could not read python config file: ${pythonConfigFile}`;
}
return JSON.parse(pythonConfigJson) as PythonConfig;
}
async function newVirtualEnv(pythonVersion: string | null, pythonVenv: string) {
const pythonConfig = await loadPythonConfig();
const selectedPythonVersion = pythonVersion ||
pythonConfig.default_version || null;
if (!selectedPythonVersion) {
throw `No Python version assigned.`;
}
if (!selectedPythonVersion) {
throw `No Python venv assigned.`;
}
const pythonVersionProfile = pythonConfig.versions[pythonVersion];
if (!pythonVersionProfile) {
throw `Python version: ${pythonVersion} not found`;
}
log.success(`Found Python version: ${pythonVersion}`);
const pythonVenvProfile = pythonConfig.profiles[pythonVenv];
if (pythonVenvProfile) {
throw `Python venv already exists: ${pythonVenv}`;
}
const pythonVenvBaseDir = resolveFilename(
pythonConfig.python_venv_base_path || PYTHON_VENV_DEFAULT_BASE_DIR,
);
if (!existsPath(pythonVenvBaseDir)) {
log.info(`Make python venv base dir: ${pythonVenvBaseDir}`);
Deno.mkdirSync(pythonVenvBaseDir);
}
const pythonVenvDir = joinPath(pythonVenvBaseDir, pythonVenv);
if (existsPath(pythonVenvDir)) {
throw `Python venv: ${pythonVenvDir} already exists`;
}
// python3 -m venv myenv
const python3Cmd = joinPath(pythonVersionProfile.path, "bin", "python3");
const pythonVenvArgs = ["-m", "vent", pythonVenvDir];
}
async function main() {
// TODO ...
}
await main();
// TODO ...