This repository has been archived by the owner on Dec 5, 2024. It is now read-only.
forked from 42BV/yml-sorter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·67 lines (61 loc) · 1.61 KB
/
index.js
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
#! /usr/bin/env node
const argv = require("yargs")
.usage("Usage: yml-sorter [options]")
.example(
"yml-sorter --input application-yml",
"Sorts the file application.yml alphabetically."
)
.example(
"yml-sorter --input application-yml --output dragons.yml",
"Sorts and writes the output to dragons.yml"
)
.example(
"yml-sorter --input application-yml --dry-run",
"Writes the output to the terminal"
)
.example(
"yml-sorter --input application-yml --indent 4",
"Indent with 4 spaces"
)
.describe("input", "The yml file which needs to be sorted")
.option("input", {
alias: "i",
})
.describe("output", "The file to wich to write the output")
.option("output", {
alias: "o",
})
.describe("dry-run", "Only outputs the proposed sort to the terminal")
.option("dry-run", {
alias: "d",
default: false
})
.describe("indent", "Indentation width to use (in spaces)")
.option("indent", {
alias: "id",
default: 2
})
.demandOption(["input"])
.help("h")
.alias("h", "help")
.epilog("With love from 42.nl")
.wrap(null).argv;
yaml = require("js-yaml");
fs = require("fs");
// Get document, or throw exception on error
try {
const doc = yaml.safeLoad(fs.readFileSync(argv.input, "utf8"));
const input = yaml.safeDump(doc, { sortKeys: true, indent: argv.indent });
if (argv["dry-run"]) {
console.log(input);
} else {
const output = argv.output ? argv.output : argv.input;
fs.writeFile(output, input, error => {
if (error) {
return console.error(error);
}
});
}
} catch (error) {
console.error(error);
}