diff --git a/src/cli/config.ts b/src/cli/config.ts new file mode 100644 index 0000000..c76475e --- /dev/null +++ b/src/cli/config.ts @@ -0,0 +1,8 @@ +import fs from "fs"; +import yaml from "yaml"; +import { Config } from "@/types/config"; + +export function loadConfig(file: string): Config { + const text = fs.readFileSync(file, 'utf-8'); + return yaml.parse(text) as Config; +} \ No newline at end of file diff --git a/src/cli/index.ts b/src/cli/index.ts new file mode 100644 index 0000000..bca553a --- /dev/null +++ b/src/cli/index.ts @@ -0,0 +1,45 @@ +import { program } from "commander"; +import { CLIOptions } from "@/types/cli"; +import { loadConfig } from "./config"; +import { loadTransactions } from "@/runner"; + +export function run(...args: string[]) { + program + .name("actual-importer") + .version("0.0.1") + .requiredOption("-c, --config ", "sets the path to the YAML file with configuration") + .option("-p, --profile ", "sets the desired profile to invoke") + .option("-x, --set ", "overrides the config option for this specific run (arg: =, i.e. profiles.myprofile.parser=pl.ing", (v: string, prev: string[]) => prev.concat([v]), []) + .argument('', 'CSV file to be imported') + .action(handle) + .parse(args); +} + +function handle(file: string, options: CLIOptions) { + const config = loadConfig(options.config); + + for (const override of options.set) { + const [path, value] = override.split("="); + + const segments = path.trim().split(".") + + let current: any = config; + segments.map(s => s.trim()).forEach((segment: string, idx) => { + if(!current[segment]) { + current[segment] = {}; + } + + if(idx === segments.length - 1) { + current[segment] = JSON.parse(value.trim()); + } + + current = current[segment]; + }); + } + + if (Object.keys(config?.profiles ?? {}).length === 0) { + throw new Error(`No profiles defined in the ${options.config}`); + } + + loadTransactions(file, options.profile ?? config.defaultProfile ?? Object.keys(config.profiles)[0], config); +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index bb1fd39..8949a4c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,3 @@ -#!/usr/bin/env node +import { run } from "./cli"; -console.log("Hello, world!"); \ No newline at end of file +run(...process.argv); \ No newline at end of file diff --git a/src/types/cli.ts b/src/types/cli.ts new file mode 100644 index 0000000..9a1b15e --- /dev/null +++ b/src/types/cli.ts @@ -0,0 +1,5 @@ +export type CLIOptions = { + config: string; + profile?: string; + set: string[]; +}; \ No newline at end of file diff --git a/src/types/config.ts b/src/types/config.ts index 0e59a71..e526024 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -8,5 +8,6 @@ export type ParserConfig = { }; export type Config = { + defaultProfile?: string; profiles: Record; }; \ No newline at end of file