All files / cli/src/commands convert.ts

16.66% Statements 2/12
0% Branches 0/12
50% Functions 1/2
22.22% Lines 2/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33          5x       1x                                              
import { writeFile } from 'node:fs/promises';
import { parseIES, parseLDT, serializeIES, serializeLDT } from '@ies-tools/core';
import { defineCommand } from 'yargs-file-commands';
import { inputOptions, readInput, requireLampSetSelection } from '../options.js';
 
export const command = defineCommand({
  command: 'convert <file>',
  describe: 'Convert between IES, LDT and native JSON locally; existing output files are never overwritten',
  builder: (yargs) =>
    inputOptions(yargs)
      .option('to', {
        type: 'string',
        choices: ['json', 'ies', 'ldt'] as const,
        default: 'json',
        describe: 'Output format',
      })
      .option('output', { type: 'string', alias: 'o', describe: 'Output file; defaults to stdout' }),
  handler: async (argv) => {
    const { text, format, lampSetIndex } = await readInput(argv);
    const native = format === 'ies' ? parseIES(text) : parseLDT(text);
    if ('lampSets' in native && argv.to === 'ies') requireLampSetSelection(native.lampSets.length, lampSetIndex);
    const conversion =
      argv.to === 'json'
        ? { value: `${JSON.stringify(native, null, 2)}\n`, warnings: [] }
        : argv.to === 'ies'
          ? serializeIES(native, { lampSetIndex })
          : serializeLDT(native, { lampSetIndex });
    for (const warning of conversion.warnings) console.error(`warning [${warning.code}]: ${warning.message}`);
    if (argv.output) await writeFile(argv.output, conversion.value, { flag: 'wx' });
    else process.stdout.write(conversion.value);
  },
});