picnic-cli/util.ts

46 lines
1.5 KiB
TypeScript

import parseArgs from 'minimist'
import type { ParsedArgs } from 'minimist'
import path from "node:path"
import { userInfo } from "node:os"
export function sum(xs: number[]): number {
return xs.reduce((x, y) => x+y, 0)
}
let writtenHeader = false
export function csvOut(stuff: Record<string, number | string>) {
function escape(x: number | string): string {
if (typeof x === 'number') return "" + x
return x.indexOf(",") !== -1 ? `"${x}"` : x
}
if (!writtenHeader) console.log(Object.keys(stuff).join(','))
writtenHeader = true
console.log(Object.values(stuff).map(escape).join(','))
}
export function jsonOut(stuff: any) {
if (process.stdout.isTTY) console.dir(stuff, { depth: 10 })
else console.log(JSON.stringify(stuff))
}
export function runCommands(commandBuilder: (argv: ParsedArgs) => Record<string, (...args: string[]) => (Promise<void> | void)>) {
const argv = parseArgs(process.argv.slice(2))
const commands = commandBuilder(argv)
if (argv._.length < 1 || !commands[argv._[0]]) {
console.log("Available commands:")
for (const fn of Object.values(commands)) {
const src = fn.toString().split('{')[0]
console.log("-", src)
}
} else if (commands[argv._[0]]) {
commands[argv._[0]](...argv._.slice(1))
}
}
export function getXdgConfigHome() {
return process.env.XDG_CONFIG_HOME
? process.env.XDG_CONFIG_HOME
: process.env.HOME
? path.join(process.env.HOME, ".config")
: path.join(userInfo().homedir, ".config")
}