File: cli.js

package info (click to toggle)
node-jison-lex 0.3.4-3
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 192 kB
  • sloc: makefile: 9; sh: 2
file content (86 lines) | stat: -rwxr-xr-x 2,104 bytes parent folder | download | duplicates (2)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env node

var version = require('./package.json').version;

var path = require('path');
var fs = require('fs');
var lexParser = require('lex-parser');
var RegExpLexer = require('./regexp-lexer.js');


var opts = require("nomnom")
  .script('jison-lex')
  .option('file', {
    flag: true,
    position: 0,
    help: 'file containing a lexical grammar'
  })
  .option('outfile', {
    abbr: 'o',
    metavar: 'FILE',
    help: 'Filename and base module name of the generated parser'
  })
  .option('module-type', {
    abbr: 't',
    default: 'commonjs',
    metavar: 'TYPE',
    help: 'The type of module to generate (commonjs, js)'
  })
  .option('version', {
    abbr: 'V',
    flag: true,
    help: 'print version and exit',
    callback: function() {
       return version;
    }
  });

exports.main = function (opts) {
    if (opts.file) {
        var raw = fs.readFileSync(path.normalize(opts.file), 'utf8'),
            name = path.basename((opts.outfile||opts.file)).replace(/\..*$/g,'');

        fs.writeFileSync(opts.outfile||(name + '.js'), processGrammar(raw, name));
    } else {
        readin(function (raw) {
            console.log(processGrammar(raw));
        });
    }
};

function processGrammar (file, name) {
    var grammar;
    try {
        grammar = lexParser.parse(file);
    } catch (e) {
        try {
            grammar = JSON.parse(file);
        } catch (e2) {
            throw e;
        }
    }

    var settings = grammar.options || {};
    if (!settings.moduleType) settings.moduleType = opts['module-type'];
    if (!settings.moduleName && name) settings.moduleName = name.replace(/-\w/g, function (match){ return match.charAt(1).toUpperCase(); });

    grammar.options = settings;

    return RegExpLexer.generate(grammar);
}

function readin (cb) {
    var stdin = process.openStdin(),
        data = '';

    stdin.setEncoding('utf8');
    stdin.addListener('data', function (chunk) {
        data += chunk;
    });
    stdin.addListener('end', function () {
        cb(data);
    });
}

if (require.main === module)
    exports.main(opts.parse());