json-asty 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +4 -2
  2. package/src/json-asty.cli.js +119 -85
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-asty",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Lossless JSON-to-AST Parser and AST-to-JSON Generator",
5
5
  "keywords": [ "json", "ast", "parse", "generate" ],
6
6
  "browser": "lib/json-asty.browser.js",
@@ -23,7 +23,9 @@
23
23
  "asty-astq": "1.13.7",
24
24
  "pegjs-otf": "1.2.20",
25
25
  "pegjs-util": "1.4.21",
26
- "chalk": "4.1.2"
26
+ "chalk": "4.1.2",
27
+ "yargs": "17.7.2",
28
+ "cli-io": "0.9.9"
27
29
  },
28
30
  "devDependencies": {
29
31
  "grunt": "1.6.1",
@@ -23,96 +23,130 @@
23
23
  ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
24
  */
25
25
 
26
- const fs = require("fs")
26
+ /* external requirements */
27
+ const yargs = require("yargs")
28
+ const CLIio = require("cli-io")
27
29
  const JsonAsty = require("..")
28
30
 
29
- /* convert object path to XPath */
30
- const opath2xpath = (opath) => {
31
- let xpath = ""
32
- const segments = opath.split(".")
33
- for (const segment of segments)
34
- xpath += `object / member [ / * [ pos() == 1 && @value == "${segment}" ] ] /`
35
- xpath += " * [ pos() == 2 ]"
36
- return xpath
37
- }
38
-
39
- const get = async (file, path) => {
40
- /* read JSON file */
41
- const json = await fs.promises.readFile(file, { encoding: "utf8" })
42
-
43
- /* parse JSON file */
44
- const ast = JsonAsty.parse(json)
45
-
46
- /* query JSON AST */
47
- const query = opath2xpath(path)
48
- const nodes = ast.query(query)
49
- if (nodes.length === 0)
50
- throw new Error(`path not found (no AST nodes matched): "${path}"`)
51
- if (nodes.length > 1)
52
- throw new Error(`path is ambigous (more than one AST node matched): "${path}"`)
53
- const node = nodes[0]
54
-
55
- /* deliver value */
56
- const value = node.get("value")
57
- process.stdout.write(value + "\n")
58
- }
59
-
60
- const set = async (file, path, type, value) => {
61
- /* read JSON file */
62
- const json = await fs.promises.readFile(file, { encoding: "utf8" })
63
-
64
- /* parse JSON file */
65
- const ast = JsonAsty.parse(json)
66
-
67
- /* query JSON AST */
68
- const query = opath2xpath(path)
69
- const nodes = ast.query(query)
70
- if (nodes.length === 0)
71
- throw new Error(`path not found (no AST nodes matched): "${path}"`)
72
- if (nodes.length > 1)
73
- throw new Error(`path is ambigous (more than one AST node matched): "${path}"`)
74
- const node = nodes[0]
75
-
76
- /* replace value */
77
- if (type === "number")
78
- value = parseInt(value)
79
- else if (type === "boolean")
80
- value = Boolean(value)
81
- const nodeNew = node.create(type).set({ value })
82
- node.parent().del(node).add(nodeNew)
83
-
84
- /* save JSON file */
85
- const jsonNew = JsonAsty.unparse(ast)
86
- await fs.promises.writeFile(file, jsonNew, { encoding: "utf8" })
87
- }
31
+ /* establish CLI environment */
32
+ const cli = new CLIio({
33
+ encoding: "utf8",
34
+ logLevel: "warning",
35
+ logPrefix: "json-asty",
36
+ logTime: false
37
+ })
88
38
 
39
+ /* execute in asynchronous context */
89
40
  ;(async () => {
90
- try {
91
- /* provide usage */
92
- if (process.argv.length <= 2) {
93
- process.stderr.write("json-asty: USAGE: json-asty get <json-file> <object-path>\n")
94
- process.stderr.write("json-asty: USAGE: json-asty set <json-file> <object-path> <type> <value>\n")
95
- process.exit(0)
96
- }
97
-
98
- /* dispatch commands */
99
- if (process.argv[2] === "get") {
100
- if (process.argv.length !== (3 + 2))
101
- throw new Error("invalid number of arguments (expected 2)")
102
- await get(process.argv[3], process.argv[4])
103
- }
104
- else if (process.argv[2] === "set") {
105
- if (process.argv.length !== (3 + 4))
106
- throw new Error("invalid number of arguments (expected 4)")
107
- await set(process.argv[3], process.argv[4], process.argv[5], process.argv[6])
108
- }
109
- else
110
- throw new Error("invalid command (expected 'get' or 'set')")
41
+ /* load my own information */
42
+ const my = require("../package.json")
43
+
44
+ /* command-line option parsing */
45
+ const argv = yargs
46
+ .usage("Usage: $0 [-h] [-V] [-i input-file|-] [-o output-file|-] [-p object-path] [-t field-type] [-v field-value]")
47
+ .help("h").alias("h", "help").default("h", false)
48
+ .describe("h", "show usage help")
49
+ .boolean("V").alias("V", "version").default("V", false)
50
+ .describe("V", "show program version information")
51
+ .string("i").nargs("i", 1).alias("i", "input").default("i", "-")
52
+ .describe("i", "JSON input file (or stdin)")
53
+ .string("o").nargs("o", 1).alias("o", "output").default("o", "-")
54
+ .describe("o", "JSON output file (or stdout)")
55
+ .string("p").nargs("p", 1).alias("p", "path").default("p", "")
56
+ .describe("p", "dot-separated path to object field")
57
+ .string("t").nargs("t", 1).alias("t", "type").default("t", "string")
58
+ .describe("t", "type of object field (boolean, number, string)")
59
+ .string("v").nargs("v", 1).alias("v", "value").default("v", "")
60
+ .describe("v", "value of object field to set")
61
+ .strict()
62
+ .showHelpOnFail(true)
63
+ .demand(0)
64
+ .parse(process.argv.slice(2))
65
+
66
+ /* short-circuit processing of "-V" command-line option */
67
+ if (argv.version) {
68
+ process.stderr.write(my.name + " " + my.version + " <" + my.homepage + ">\n")
69
+ process.stderr.write(my.description + "\n")
70
+ process.stderr.write("Copyright (c) 2018-2023 " + my.author.name + " <" + my.author.url + ">\n")
71
+ process.stderr.write("Licensed under " + my.license + " <http://spdx.org/licenses/" + my.license + ".html>\n")
111
72
  process.exit(0)
112
73
  }
113
- catch (ex) {
114
- process.stderr.write(`json-asty: ERROR: ${ex.toString()}\n`)
115
- process.exit(1)
74
+
75
+ /* sanity check usage */
76
+ if (!argv.path)
77
+ throw new Error("path to object field is required (see option -p|--path)")
78
+
79
+ /* helper function: convert object path to XPath */
80
+ const opath2xpath = (opath) => {
81
+ let xpath = ""
82
+ const segments = opath.split(".")
83
+ for (const segment of segments)
84
+ xpath += `object / member [ / * [ pos() == 1 && @value == "${segment}" ] ] /`
85
+ xpath += " * [ pos() == 2 ]"
86
+ return xpath
87
+ }
88
+
89
+ /* dispatch commands */
90
+ if (!argv.value) {
91
+ /* ==== GET OPERATION ==== */
92
+
93
+ /* read input */
94
+ const json = await cli.input(argv.input)
95
+
96
+ /* parse JSON */
97
+ const ast = JsonAsty.parse(json)
98
+
99
+ /* query JSON AST */
100
+ const query = opath2xpath(argv.path)
101
+ const nodes = ast.query(query)
102
+ if (nodes.length === 0)
103
+ throw new Error(`path not found (no AST nodes matched): "${argv.path}"`)
104
+ if (nodes.length > 1)
105
+ throw new Error(`path is ambigous (more than one AST node matched): "${argv.path}"`)
106
+ const node = nodes[0]
107
+
108
+ /* fetch value */
109
+ const value = node.get("value")
110
+
111
+ /* write output */
112
+ await cli.output(argv.output, `${value}\n`)
113
+ }
114
+ else {
115
+ /* ==== SET OPERATION ==== */
116
+
117
+ /* read input */
118
+ const json = await cli.input(argv.input)
119
+
120
+ /* parse JSON */
121
+ const ast = JsonAsty.parse(json)
122
+
123
+ /* query JSON AST */
124
+ const query = opath2xpath(argv.path)
125
+ const nodes = ast.query(query)
126
+ if (nodes.length === 0)
127
+ throw new Error(`path not found (no AST nodes matched): "${argv.path}"`)
128
+ if (nodes.length > 1)
129
+ throw new Error(`path is ambigous (more than one AST node matched): "${argv.path}"`)
130
+ const node = nodes[0]
131
+
132
+ /* replace value */
133
+ let value = argv.value
134
+ if (argv.type === "number")
135
+ value = parseInt(value)
136
+ else if (argv.type === "boolean")
137
+ value = Boolean(value)
138
+ const nodeNew = node.create(argv.type).set({ value })
139
+ node.parent().del(node).add(nodeNew)
140
+
141
+ /* unparse JSON */
142
+ const jsonNew = JsonAsty.unparse(ast)
143
+
144
+ /* write output */
145
+ await cli.output(argv.output, jsonNew)
116
146
  }
117
- })()
147
+ })().catch((err) => {
148
+ const error = err.toString().replace(/^Error:\s+/, "")
149
+ cli.log("error", error)
150
+ process.exit(1)
151
+ })
118
152