Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: CI

on:
push:
branches: [main, master]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 22]
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.DS_Store
*.tgz
coverage/
.nyc_output/
dist/
.idea/
.vscode/
21 changes: 21 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Contributing

## Setup

- Use Node 20 or newer
- Install dependencies with the package manager
- Run the test script from package.json

## Guidelines

- Keep the CLI ESM-only (type module).
- Prefer small, focused changes with tests for round-trips and edge cases.
- Do not add company names or personal contacts in committed files.
- Match existing style: errors on stderr, exit code 1 on failure, UTF-8 I/O.

## Pull requests

1. Fork and branch from main.
2. Add or update tests under test/.
3. Ensure the test script passes.
4. Open a PR with a short summary of the change and why.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 rmkr-dev

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
57 changes: 57 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 46 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "data-transform-cli",
"version": "0.1.0",
"description": "Streaming-friendly CLI for YAML ↔ JSON ↔ CSV transforms for pipelines and shell use",
"type": "module",
"bin": {
"data-transform": "./src/cli.js"
},
"main": "./src/index.js",
"exports": {
".": "./src/index.js"
},
"files": [
"src",
"LICENSE",
"README.md"
],
"scripts": {
"test": "node --test test/*.test.js",
"start": "node src/cli.js"
},
"engines": {
"node": ">=20"
},
"keywords": [
"cli",
"yaml",
"json",
"csv",
"transform",
"pipeline"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "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/rmkr-dev/data-transform-cli.git"
},
"bugs": {
"url": "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/rmkr-dev/data-transform-cli/issues"
},
"homepage": "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/rmkr-dev/data-transform-cli#readme",
"dependencies": {
"commander": "^12.1.0",
"js-yaml": "^4.1.0"
}
}
146 changes: 146 additions & 0 deletions src/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
#!/usr/bin/env node
import { readFileSync, writeFileSync } from 'node:fs';
import { stdin as stdinStream } from 'node:process';
import { Command } from 'commander';
import {
convert,
detectFormat,
inferFormat,
parse,
serialize,
} from './convert.js';

const program = new Command();

program
.name('data-transform')
.description('YAML ↔ JSON ↔ CSV transforms for pipelines and shell use')
.version('0.1.0');

/**
* Read all of stdin as UTF-8 text.
* @returns {Promise<string>}
*/
function readStdin() {
return new Promise((resolve, reject) => {
const chunks = [];
stdinStream.setEncoding('utf8');
stdinStream.on('data', (c) => chunks.push(c));
stdinStream.on('end', () => resolve(chunks.join('')));
stdinStream.on('error', reject);
});
}

/**
* Load input from file path or stdin when path is "-" / omitted.
* @param {string | undefined} file
* @returns {Promise<{ text: string, name?: string }>}
*/
async function loadInput(file) {
if (!file || file === '-') {
if (stdinStream.isTTY) {
throw new Error('No input file and stdin is a TTY. Pass a file or pipe data.');
}
return { text: await readStdin(), name: undefined };
}
return { text: readFileSync(file, 'utf8'), name: file };
}

/**
* Resolve source format from flag, filename, or content.
* @param {string} text
* @param {string | undefined} name
* @param {string | undefined} fromFlag
*/
function resolveFrom(text, name, fromFlag) {
if (fromFlag) return fromFlag;
return detectFormat(name) ?? inferFormat(text);
}

/**
* Write output to file or stdout.
* @param {string} out
* @param {string | undefined} outputPath
*/
function writeOutput(out, outputPath) {
if (outputPath && outputPath !== '-') {
writeFileSync(outputPath, out, 'utf8');
} else {
process.stdout.write(out);
}
}

/**
* Shared options for transform commands.
* @param {Command} cmd
*/
function addIOOptions(cmd) {
return cmd
.argument('[file]', 'input file (default: stdin)')
.option('-o, --output <file>', 'write to file instead of stdout')
.option('-f, --from <format>', 'input format: json | yaml | csv');
}

function makeTransformCommand(name, description, toFormat) {
const cmd = program.command(name).description(description);
addIOOptions(cmd);
if (toFormat === 'json') {
cmd.option('--minify', 'emit compact JSON', false);
}
cmd.action(async (file, opts) => {
try {
const { text, name } = await loadInput(file);
const from = resolveFrom(text, name, opts.from);
const out = convert(text, from, toFormat, {
pretty: !opts.minify,
minify: Boolean(opts.minify),
});
writeOutput(out, opts.output);
} catch (err) {
console.error(`error: ${err.message}`);
process.exitCode = 1;
}
});
}

makeTransformCommand('to-json', 'Convert input to JSON', 'json');
makeTransformCommand('to-yaml', 'Convert input to YAML', 'yaml');
makeTransformCommand('to-csv', 'Convert input to CSV (array of objects/rows)', 'csv');

program
.command('pretty')
.description('Pretty-print JSON (or convert to pretty JSON)')
.argument('[file]', 'input file (default: stdin)')
.option('-o, --output <file>', 'write to file instead of stdout')
.option('-f, --from <format>', 'input format: json | yaml | csv')
.action(async (file, opts) => {
try {
const { text, name } = await loadInput(file);
const from = resolveFrom(text, name, opts.from);
const data = parse(text, from);
writeOutput(serialize(data, 'json', { pretty: true }), opts.output);
} catch (err) {
console.error(`error: ${err.message}`);
process.exitCode = 1;
}
});

program
.command('minify')
.description('Minify JSON (or convert to compact JSON)')
.argument('[file]', 'input file (default: stdin)')
.option('-o, --output <file>', 'write to file instead of stdout')
.option('-f, --from <format>', 'input format: json | yaml | csv')
.action(async (file, opts) => {
try {
const { text, name } = await loadInput(file);
const from = resolveFrom(text, name, opts.from);
const data = parse(text, from);
writeOutput(serialize(data, 'json', { minify: true }), opts.output);
} catch (err) {
console.error(`error: ${err.message}`);
process.exitCode = 1;
}
});

program.parseAsync(process.argv);
Loading
Loading