From 76c39f7a6a880d2c239c2ba6811c69366493d620 Mon Sep 17 00:00:00 2001 From: Yoan Blanc Date: Fri, 28 Oct 2016 11:32:42 +0200 Subject: [PATCH] Compatibility with vim-markdownfmt - Add support for reading a file from its path - Add support to write back to a file (-w, --write) Closes #43 --- lib/cli.coffee | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/lib/cli.coffee b/lib/cli.coffee index a8552f5..4c3ebe5 100644 --- a/lib/cli.coffee +++ b/lib/cli.coffee @@ -1,5 +1,6 @@ {ArgumentParser} = require 'argparse' +fs = require 'fs' packageInfo = require '../package' tidyMarkdown = require './' @@ -10,6 +11,16 @@ argparser = new ArgumentParser( version: packageInfo.version ) +argparser.addArgument( + ['path'], + action: 'store', + type: 'string', + help: 'Filename to read (default: STDIN)' + defaultValue: null, + nargs: '?', + required: false +) + argparser.addArgument( ['--no-ensure-first-header-is-h1'] action: 'storeFalse' @@ -20,13 +31,33 @@ argparser.addArgument( dest: 'ensureFirstHeaderIsH1' ) +argparser.addArgument( + ['-w', '--write'] + action: 'storeTrue', + help: 'Write result to (source) file instead of stdout', + dest: 'write' +) + argv = argparser.parseArgs() -process.stdin.setEncoding 'utf8' -process.stdin.on 'readable', -> + +if argv.path is null + input = process.stdin + input.setEncoding 'utf8' +else + input = fs.createReadStream(argv.path, {encoding: 'utf8'}) + +input.on 'readable', -> buffer = '' - while (chunk = process.stdin.read()) isnt null + while (chunk = input.read()) isnt null buffer += chunk + input.close() + + if argv.write + output = fs.createWriteStream(argv.path, {encoding: 'utf8'}) + else + output = process.stdout + if buffer isnt '' - process.stdout.write tidyMarkdown(buffer, argv) + output.write tidyMarkdown(buffer, argv) return