3 var esformatter = require('../lib/esformatter');
4 var fs = require('fs');
5 var optimist = require('optimist');
6 var stdin = require('stdin');
7 var merge = require('mout/object/merge');
8 var options = require('./options');
15 .usage('esformatter [OPTIONS] [FILES]')
16 .alias('c', 'config').describe('c', 'Path to custom configuration file.')
17 .alias('p', 'preset').describe('p', 'Set style guide preset ("jquery", "default").')
18 .alias('h', 'help').describe('h', 'Display help and usage details.')
19 .alias('v', 'version').describe('v', 'Display the current version.')
20 .describe('plugins', 'Comma separated list of plugins.')
21 .boolean('i').describe('i', 'Edit input files in place.')
22 .string(['config', 'preset', 'indent.value', 'lineBreak.value', 'whiteSpace.value', 'plugins'])
23 .boolean(['help', 'version'])
27 exports.parse = function(str) {
28 var argv = optimist.parse(str);
31 argv.plugins = argv.plugins.split(',');
38 exports.run = function(argv) {
45 console.log('esformatter v' + require('../package.json').version);
59 stdin(function(source) {
60 formatToConsole(source, getConfig(null, argv));
63 files.forEach(function(file) {
64 formatToSelf(file, getConfig(file, argv));
67 files.forEach(function(file) {
68 formatToConsole(getSource(file), getConfig(file, argv));
74 function getSource(file) {
76 return fs.readFileSync(file).toString();
78 console.error('Can\'t read source file: "' + file + '"\nException: ' + ex.message);
84 function getConfig(filePath, argv) {
85 // if user sets the "preset" we don't load any other config file
86 // we assume the "preset" overrides any user settings
87 if (argv.preset || argv.root) {
91 // we only load ".esformatter" or "package.json" file if user did not
92 // provide a config file as argument, that way we allow user to override
94 var config = argv.config ?
95 options.loadAndParseConfig(argv.config) :
96 options.getRc(filePath);
98 // we always merge the argv to allow user to override the default settings
99 return merge(config, argv);
103 function formatToConsole(source, config) {
104 var result = esformatter.format(source, config);
105 // do not use console.log since it adds a line break at the end
106 process.stdout.write(result);
109 function formatToSelf(file, config) {
110 fs.writeFileSync(file, esformatter.format(getSource(file), config));