Skip to content

Commit

Permalink
Use the same codepath in the CLI. Fixes #32
Browse files Browse the repository at this point in the history
  • Loading branch information
schani committed Jul 26, 2017
1 parent 8c2903a commit 17e1836
Showing 1 changed file with 18 additions and 32 deletions.
50 changes: 18 additions & 32 deletions cli/quicktype.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,13 @@ function getRenderer() {
return renderer;
}

function renderString(json) {
let renderer = getRenderer();
return Main.renderJsonString(renderer)(json).value0;
}

function renderJson(json) {
let renderer = getRenderer();
return Main.renderJson(renderer)(json);
}

function work(json) {
let out = renderString(json);
let out = renderJson(json);
if (options.output) {
fs.writeFile(options.output, out, (err) => {
if (err) {
Expand All @@ -103,27 +98,31 @@ function work(json) {
}
}

function usage() {
console.log(getUsage(sections));
}
function workFromStream(stream) {
let source = makeSource();
let assembler = new Assembler();

function parseFile(file) {
fs.readFile(file, 'utf8', (err, json) => {
work(json);
source.output.on("data", function (chunk) {
assembler[chunk.name] && assembler[chunk.name](chunk.value);
});
source.output.on("end", function () {
work(assembler.current);
});

stream.setEncoding('utf8');
stream.pipe(source.input);
stream.resume();
}

function parseUrl(url) {
fetch(url)
.then((data) => data.text())
.then(work);
function usage() {
console.log(getUsage(sections));
}

function parseFileOrUrl(fileOrUrl) {
if (fs.existsSync(fileOrUrl)) {
parseFile(fileOrUrl);
workFromStream(fs.createReadStream(fileOrUrl));
} else {
parseUrl(fileOrUrl);
fetch(fileOrUrl).then(res => workFromStream(res.body));
}
}

Expand All @@ -139,20 +138,7 @@ if (options.output && !options.lang) {
if (options.help) {
usage();
} else if (!options.src || options.src.length === 0) {
let source = makeSource();
let assembler = new Assembler();

source.output.on("data", function (chunk) {
assembler[chunk.name] && assembler[chunk.name](chunk.value);
});
source.output.on("end", function () {
shell.echo(renderJson(assembler.current));
});

process.stdin.pipe(source.input);

process.stdin.resume();
process.stdin.setEncoding('utf8');
workFromStream(process.stdin);
} else if (options.src.length == 1) {
parseFileOrUrl(options.src[0]);
} else {
Expand Down

0 comments on commit 17e1836

Please sign in to comment.