summaryrefslogtreecommitdiff
path: root/bin/json2yaml
blob: 4e92bf87746468513b101c708090edc8bcb5b72b (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env node

/**
 * yaml2json cli program
 */
 
var YAML = require('./yaml.js');

var ArgumentParser = require('argparse').ArgumentParser;
var cli = new ArgumentParser({
    prog:           "json2yaml", 
    version:        require('../package.json').version,
    addHelp:        true
});

cli.addArgument(
    ['-d', '--depth'],
    {
        action: 'store',
        type:   'int', 
        help:   'Set minimum level of depth before generating inline YAML (default: 2).'
    }
);

cli.addArgument(
    ['-i', '--indentation'],
    {
        action: 'store',
        type:   'int', 
        help:   'Number of space characters used to indent code (default: 2).',
    }
);

cli.addArgument(
    ['-s', '--save'],
    {
        help:   'Save output inside YML file(s) with the same name.',
        action: 'storeTrue'
    }
);

cli.addArgument(
    ['-r', '--recursive'],
    {
        help:   'If the input is a directory, also find JSON files in sub-directories recursively.',
        action: 'storeTrue'
    }
);

cli.addArgument(
    ['-w', '--watch'],
    {
        help:   'Watch for changes.',
        action: 'storeTrue'
    }
);

cli.addArgument(['input'], {
    help:   'JSON file or directory containing JSON files.'
});

try {
    var options = cli.parseArgs();
    var path = require('path');
    var fs   = require('fs');
    var glob = require('glob');
    
    var rootPath = process.cwd();
    var parsePath = function(input) {
        var output;
        if (!(input != null)) {
            return rootPath;
        }
        output = path.normalize(input);
        if (output.length === 0) {
            return rootPath;
        }
        if (output.charAt(0) !== '/') {
            output = path.normalize(rootPath + '/./' + output);
        }
        if (output.length > 1 && output.charAt(output.length - 1) === '/') {
            return output.substr(0, output.length - 1);
        }
        return output;
    };

    // Find files
    var findFiles = function(input) {
        var isDirectory = fs.statSync(input).isDirectory();
        var files = [];

        if (!isDirectory) {
            files.push(input);
        }
        else {
            if (options.recursive) {
                files = files.concat(glob.sync(input+'/**/*.json'));
            }
            else {
                files = files.concat(glob.sync(input+'/*.json'));
            }
        }
    
        return files;
    };

    // Convert to JSON
    var convertToYAML = function(input, inline, save, spaces) {
        var yaml;
        if (inline == null) inline = 2;
        if (spaces == null) spaces = 2;
        
        yaml = YAML.stringify(JSON.parse(fs.readFileSync(input)), inline, spaces);
    
        if (!save) {
            // Ouput result
            process.stdout.write(yaml);
        }
        else {
            var output;
            if (input.substring(input.length-5) == '.json') {
                output = input.substr(0, input.length-5) + '.yaml';
            }
            else {
                output = input + '.yaml';
            }
        
            // Write file
            var file = fs.openSync(output, 'w+');
            fs.writeSync(file, yaml);
            fs.closeSync(file);
            process.stdout.write("saved "+output+"\n");
        }
    };

    var input = parsePath(options.input);
    var mtimes = [];

    var runCommand = function() {
        try {
            var files = findFiles(input);
            var len = files.length;

            for (var i = 0; i < len; i++) {
                var file = files[i];
                var stat = fs.statSync(file);
                var time = stat.mtime.getTime();
                if (!stat.isDirectory()) {
                    if (!mtimes[file] || mtimes[file] < time) {
                        mtimes[file] = time;
                        convertToYAML(file, options.depth, options.save, options.indentation);
                    }
                }
            }
        } catch (e) {
            process.stderr.write((e.message ? e.message : e)+"\n");
        }
    };

    if (!options.watch) {
        runCommand();
    } else {
        runCommand();
        setInterval(runCommand, 1000);
    } 
} catch (e) {
    process.stderr.write((e.message ? e.message : e)+"\n");
}