1 | #!/usr/bin/env node
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | var fs = require('fs');
|
10 | var argparse = require('argparse');
|
11 | var yaml = require('..');
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | var cli = new argparse.ArgumentParser({
|
18 | prog: 'js-yaml',
|
19 | add_help: true
|
20 | });
|
21 |
|
22 | cli.add_argument('-v', '--version', {
|
23 | action: 'version',
|
24 | version: require('../package.json').version
|
25 | });
|
26 |
|
27 | cli.add_argument('-c', '--compact', {
|
28 | help: 'Display errors in compact mode',
|
29 | action: 'store_true'
|
30 | });
|
31 |
|
32 |
|
33 |
|
34 | cli.add_argument('-j', '--to-json', {
|
35 | help: argparse.SUPPRESS,
|
36 | dest: 'json',
|
37 | action: 'store_true'
|
38 | });
|
39 |
|
40 | cli.add_argument('-t', '--trace', {
|
41 | help: 'Show stack trace on error',
|
42 | action: 'store_true'
|
43 | });
|
44 |
|
45 | cli.add_argument('file', {
|
46 | help: 'File to read, utf-8 encoded without BOM',
|
47 | nargs: '?',
|
48 | default: '-'
|
49 | });
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | var options = cli.parse_args();
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | function readFile(filename, encoding, callback) {
|
61 | if (options.file === '-') {
|
62 |
|
63 |
|
64 | var chunks = [];
|
65 |
|
66 | process.stdin.on('data', function (chunk) {
|
67 | chunks.push(chunk);
|
68 | });
|
69 |
|
70 | process.stdin.on('end', function () {
|
71 | return callback(null, Buffer.concat(chunks).toString(encoding));
|
72 | });
|
73 | } else {
|
74 | fs.readFile(filename, encoding, callback);
|
75 | }
|
76 | }
|
77 |
|
78 | readFile(options.file, 'utf8', function (error, input) {
|
79 | var output, isYaml;
|
80 |
|
81 | if (error) {
|
82 | if (error.code === 'ENOENT') {
|
83 | console.error('File not found: ' + options.file);
|
84 | process.exit(2);
|
85 | }
|
86 |
|
87 | console.error(
|
88 | options.trace && error.stack ||
|
89 | error.message ||
|
90 | String(error));
|
91 |
|
92 | process.exit(1);
|
93 | }
|
94 |
|
95 | try {
|
96 | output = JSON.parse(input);
|
97 | isYaml = false;
|
98 | } catch (err) {
|
99 | if (err instanceof SyntaxError) {
|
100 | try {
|
101 | output = [];
|
102 | yaml.loadAll(input, function (doc) { output.push(doc); }, {});
|
103 | isYaml = true;
|
104 |
|
105 | if (output.length === 0) output = null;
|
106 | else if (output.length === 1) output = output[0];
|
107 |
|
108 | } catch (e) {
|
109 | if (options.trace && err.stack) console.error(e.stack);
|
110 | else console.error(e.toString(options.compact));
|
111 |
|
112 | process.exit(1);
|
113 | }
|
114 | } else {
|
115 | console.error(
|
116 | options.trace && err.stack ||
|
117 | err.message ||
|
118 | String(err));
|
119 |
|
120 | process.exit(1);
|
121 | }
|
122 | }
|
123 |
|
124 | if (isYaml) console.log(JSON.stringify(output, null, ' '));
|
125 | else console.log(yaml.dump(output));
|
126 | });
|