|
| 1 | +import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs' |
| 2 | +import {homedir} from 'node:os' |
| 3 | +import {join} from 'node:path' |
| 4 | + |
| 5 | +import type {Profile} from './types.js' |
| 6 | + |
| 7 | +export function getProfilesDir(): string { |
| 8 | + const home = process.env.HOME || homedir() |
| 9 | + return join(home, '.config', 'translation-ai-cli', 'profiles') |
| 10 | +} |
| 11 | + |
| 12 | +export function ensureProfilesDir(): void { |
| 13 | + const dir = getProfilesDir() |
| 14 | + if (!existsSync(dir)) { |
| 15 | + mkdirSync(dir, {recursive: true}) |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +export function getProfilePath(name: string): string { |
| 20 | + return join(getProfilesDir(), `${name}.json`) |
| 21 | +} |
| 22 | + |
| 23 | +export function saveProfile(profile: Profile): void { |
| 24 | + ensureProfilesDir() |
| 25 | + const path = getProfilePath(profile.name) |
| 26 | + writeFileSync(path, JSON.stringify(profile, null, 2), { |
| 27 | + encoding: 'utf8', |
| 28 | + mode: 0o600, // only owner can read/write |
| 29 | + }) |
| 30 | +} |
| 31 | + |
| 32 | +export function loadProfile(name: string): Profile { |
| 33 | + const path = getProfilePath(name) |
| 34 | + if (!existsSync(path)) { |
| 35 | + throw new Error(`Profile "${name}" does not exist`) |
| 36 | + } |
| 37 | + |
| 38 | + const content = readFileSync(path, 'utf8') |
| 39 | + return JSON.parse(content) as Profile |
| 40 | +} |
| 41 | + |
| 42 | +export function listProfiles(): string[] { |
| 43 | + const dir = getProfilesDir() |
| 44 | + if (!existsSync(dir)) { |
| 45 | + return [] |
| 46 | + } |
| 47 | + |
| 48 | + return readdirSync(dir) |
| 49 | + .filter((file) => file.endsWith('.json')) |
| 50 | + .map((file) => file.replace(/\.json$/, '')) |
| 51 | +} |
| 52 | + |
| 53 | +export function deleteProfile(name: string): void { |
| 54 | + const path = getProfilePath(name) |
| 55 | + if (!existsSync(path)) { |
| 56 | + throw new Error(`Profile "${name}" does not exist`) |
| 57 | + } |
| 58 | + |
| 59 | + rmSync(path) |
| 60 | +} |
| 61 | + |
| 62 | +export function profileExists(name: string): boolean { |
| 63 | + return existsSync(getProfilePath(name)) |
| 64 | +} |
0 commit comments