yamlctl 0.1.0 → 0.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.
- package/README.md +92 -40
- package/package.json +1 -1
- package/src/cli.js +268 -100
- package/src/document.js +33 -4
- package/src/explain.js +1 -1
- package/src/resources.js +2 -2
- package/src/rules.js +5 -4
- package/src/schema.js +3 -2
package/README.md
CHANGED
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
[](https://github.com/devpro/yamlctl/actions/workflows/ci.yml)
|
|
4
4
|
[](https://www.npmjs.com/package/yamlctl)
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
Edit YAML files from the command line.
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
and updated by a pipeline from another system: a CMDB, a service catalog, a spreadsheet export.
|
|
8
|
+
## Key
|
|
10
9
|
|
|
11
|
-
- **Kubectl-like**:
|
|
10
|
+
- **Kubectl-like**: the verbs are kubectl's and behave like them, `create`, `apply`, `patch`, `replace`, `delete`, with the resource first, `yamlctl project create checkout_api name="Checkout API"`.
|
|
12
11
|
- **Checked**: a field that does not exist, a value outside its allowed list, or a reference to a missing entry is refused, and the file is left as it was.
|
|
13
|
-
- **Typed by the schema**:
|
|
12
|
+
- **Typed by the schema**: a string stays a file even if it looks like a number.
|
|
14
13
|
- **Careful with the file**: comments, order and every entry not named stay exactly as they were, and a command changing nothing writes nothing.
|
|
15
14
|
- **Nothing to configure**: the schema is the one the file already names for an editor.
|
|
16
15
|
|
|
@@ -54,17 +53,18 @@ KEY NAME
|
|
|
54
53
|
applications Applications
|
|
55
54
|
checkout_api Checkout API
|
|
56
55
|
|
|
57
|
-
$ yamlctl project
|
|
56
|
+
$ yamlctl project create billing_api name="Billing API" parent_project=applications account=005217217997 risk_profile.business_impact=MBI
|
|
58
57
|
projects/billing_api created
|
|
59
58
|
|
|
60
59
|
$ yamlctl project get billing_api
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
60
|
+
billing_api:
|
|
61
|
+
name: Billing API
|
|
62
|
+
parent_project: applications
|
|
63
|
+
account: "005217217997"
|
|
64
|
+
risk_profile:
|
|
65
|
+
business_impact: MBI
|
|
66
|
+
|
|
67
|
+
$ yamlctl project apply billing_api name="Billing API"
|
|
68
68
|
projects/billing_api unchanged
|
|
69
69
|
```
|
|
70
70
|
|
|
@@ -98,14 +98,14 @@ VALUES:
|
|
|
98
98
|
And what does not fit is refused, with the file untouched and a non-zero exit status, so a pipeline stops on it:
|
|
99
99
|
|
|
100
100
|
```text
|
|
101
|
-
$ yamlctl project
|
|
101
|
+
$ yamlctl project patch billing_api risk_profle.business_impact=HBI
|
|
102
102
|
error: risk_profle.business_impact: no such field in projects, run yamlctl project explain to list them
|
|
103
103
|
|
|
104
|
-
$ yamlctl project
|
|
104
|
+
$ yamlctl project patch billing_api risk_profile.business_impact=HIGH
|
|
105
105
|
projects/billing_api.risk_profile.business_impact: must be one of "LBI", "MBI", "HBI"
|
|
106
106
|
error: projects/billing_api not written
|
|
107
107
|
|
|
108
|
-
$ yamlctl project
|
|
108
|
+
$ yamlctl project patch billing_api parent_project=checkout_api
|
|
109
109
|
projects/billing_api: parent_project: checkout_api must have is_folder: true, it has null
|
|
110
110
|
projects/billing_api: parent_project: changing "applications" to "checkout_api" needs --force, moving a project recreates it
|
|
111
111
|
error: projects/billing_api not written
|
|
@@ -117,24 +117,46 @@ error: projects/applications is still named by projects/checkout_api, projects/b
|
|
|
117
117
|
## Commands
|
|
118
118
|
|
|
119
119
|
```text
|
|
120
|
-
yamlctl <resource> list
|
|
121
|
-
yamlctl <resource> get <key
|
|
122
|
-
yamlctl <resource>
|
|
123
|
-
yamlctl <resource>
|
|
124
|
-
yamlctl <resource>
|
|
125
|
-
yamlctl <resource>
|
|
126
|
-
yamlctl <resource>
|
|
127
|
-
yamlctl
|
|
128
|
-
yamlctl
|
|
120
|
+
yamlctl <resource> list the entries, one line each
|
|
121
|
+
yamlctl <resource> get <key>... the entries under their keys, as YAML
|
|
122
|
+
yamlctl <resource> create <key> <field>=<value>... a new entry, refused if the key is taken
|
|
123
|
+
yamlctl <resource> create -f <file> every entry of the file, refused if a key is taken
|
|
124
|
+
yamlctl <resource> apply <key> <field>=<value>... create the entry, or change the fields given and keep the others
|
|
125
|
+
yamlctl <resource> apply -f <file> create each entry of the file, or merge it into the one there
|
|
126
|
+
yamlctl <resource> patch <key> <field>=<value>... change the fields given of an existing entry, keep the others
|
|
127
|
+
yamlctl <resource> replace -f <file> replace each entry of the file whole, refused if one is missing
|
|
128
|
+
yamlctl <resource> delete <key>... remove the entries
|
|
129
|
+
yamlctl <resource> delete -f <file> remove the entries the file names
|
|
130
|
+
yamlctl <resource> explain [field] what the entries hold: fields, types, allowed values
|
|
131
|
+
yamlctl <resource> check the file against its schema
|
|
132
|
+
yamlctl resources every resource in the directory
|
|
133
|
+
yamlctl check every file in the directory against its schema
|
|
129
134
|
```
|
|
130
135
|
|
|
136
|
+
The verbs writing an entry follow kubectl:
|
|
137
|
+
|
|
138
|
+
Verb | Entry missing | Entry present | Input
|
|
139
|
+
----------|-----------------------------------------------|-----------------------------------|-----------------------------
|
|
140
|
+
`create` | created | refused | `<field>=<value>...` or `-f`
|
|
141
|
+
`apply` | created | configured, or unchanged | `<field>=<value>...` or `-f`
|
|
142
|
+
`patch` | refused | patched, or patched (no change) | `<field>=<value>...`
|
|
143
|
+
`replace` | refused | replaced, or replaced (no change) | `-f`
|
|
144
|
+
`delete` | refused, or nothing with `--ignore-not-found` | deleted | `<key>...` or `-f`
|
|
145
|
+
|
|
146
|
+
Whatever the verb, an entry holding what it already held is not written.
|
|
147
|
+
A command writing several entries checks them all against the file as it will be, so one may name another written alongside it, and writes the file once, or not at all when one of them fails.
|
|
148
|
+
|
|
131
149
|
Option | Action
|
|
132
|
-
|
|
150
|
+
------------------------|-------------------------------------------------------------------------------------------------
|
|
133
151
|
`-C, --dir <dir>` | the directory holding the data files, the current one by default
|
|
134
|
-
|
|
135
|
-
`-o, --output <format>` | `yaml
|
|
136
|
-
|
|
152
|
+
`--data-file <file>` | the data file, for a resource the directory does not name on its own
|
|
153
|
+
`-o, --output <format>` | `yaml`, `json` or `name`: the entries, or their resource paths, instead of a table or a sentence
|
|
154
|
+
`-f, --filename <file>` | the entries to create, apply, replace or delete, `-` for standard input
|
|
137
155
|
`--force` | accept a change the schema marks immutable
|
|
156
|
+
`--ignore-not-found` | `delete` succeeds without a word when the entry is not there
|
|
157
|
+
`--prune` | `apply -f` also deletes the entries the file does not hold, within `--prefix` or `--all`
|
|
158
|
+
`--prefix <prefix>` | the keys `--prune` may delete, the ones a sync owns
|
|
159
|
+
`--all` | `--prune` may delete any entry of the map
|
|
138
160
|
`--offline` | read remote schemas from the cache only, never from the network, also `YAMLCTL_OFFLINE=1`
|
|
139
161
|
`--refresh` | fetch remote schemas again even when the cache holds a recent copy
|
|
140
162
|
|
|
@@ -144,12 +166,17 @@ A file holding several maps is listed whole by its own name and reached one map
|
|
|
144
166
|
A **field** inside an object is a path, `risk_profile.business_impact`.
|
|
145
167
|
A list or an object is written as JSON, `account_links='[{"account": "123", "environment": "PRODUCTION"}]'`, and an empty value, `description=`, removes the field.
|
|
146
168
|
|
|
147
|
-
`get`
|
|
169
|
+
A file given with **`-f`** holds entries under their keys, as YAML or JSON, the shape `get` and `list -o yaml` print, so the file itself can be edited and applied back:
|
|
148
170
|
|
|
149
171
|
```bash
|
|
150
|
-
yamlctl project
|
|
172
|
+
yamlctl project list -o yaml > projects.yaml
|
|
173
|
+
# edit projects.yaml
|
|
174
|
+
yamlctl project apply -f projects.yaml
|
|
151
175
|
```
|
|
152
176
|
|
|
177
|
+
`apply -f` merges each entry into the one already there, the way `kubectl apply` does: an object merges into the object it meets, a list replaces the list it meets, a field the file leaves out is kept, and a field set to `null` is removed.
|
|
178
|
+
`replace -f` takes each entry whole instead.
|
|
179
|
+
|
|
153
180
|
## The schema
|
|
154
181
|
|
|
155
182
|
`yamlctl` checks a file against the JSON Schema the file names on its first line, the same comment the [YAML language server](https://github.com/redhat-developer/yaml-language-server) reads, so an editor and `yamlctl` never disagree:
|
|
@@ -192,31 +219,56 @@ Those are declared with `x-yamlctl` on the field, and [docs/schema-extensions.md
|
|
|
192
219
|
}
|
|
193
220
|
```
|
|
194
221
|
|
|
222
|
+
## In a pipeline
|
|
223
|
+
|
|
224
|
+
Data goes to standard output, warnings and errors to standard error, and any refusal exits non-zero, with nothing written.
|
|
225
|
+
`-o` turns what a command prints into data rather than a table or a sentence:
|
|
226
|
+
|
|
227
|
+
```text
|
|
228
|
+
$ yamlctl project apply -f entries.yaml -o name
|
|
229
|
+
projects/app_1042
|
|
230
|
+
projects/app_7
|
|
231
|
+
|
|
232
|
+
$ yamlctl project patch app_7 name=Seven -o json
|
|
233
|
+
{
|
|
234
|
+
"app_7": {
|
|
235
|
+
"name": "Seven",
|
|
236
|
+
"parent_project": "applications",
|
|
237
|
+
"account_links": [
|
|
238
|
+
{
|
|
239
|
+
"account": "1",
|
|
240
|
+
"environment": "PRODUCTION"
|
|
241
|
+
}
|
|
242
|
+
]
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
`-o name` prints the resource path of each entry listed, read or written, `-o json` and `-o yaml` the entries themselves, as written.
|
|
248
|
+
`delete` takes `-o name` only, `resources` all three, and `check` none, since its exit status is the result.
|
|
249
|
+
|
|
195
250
|
## From a source system to a data file
|
|
196
251
|
|
|
197
252
|
A pipeline keeping a data file in step with another system runs four steps, typically on a schedule:
|
|
198
253
|
|
|
199
254
|
1. Export the list from the source system, as JSON.
|
|
200
|
-
2.
|
|
255
|
+
2. Turn it into entries under their keys and `apply -f --prune` them, which also deletes the entries the source no longer holds.
|
|
201
256
|
3. Run `yamlctl check`, then whatever reads the file, `terraform plan` for instance.
|
|
202
257
|
4. Open a merge request with the change, and apply once it is merged.
|
|
203
258
|
|
|
204
259
|
```bash
|
|
205
260
|
# apps.json: [{"id": "1042", "name": "Checkout API", "account": "123456789012"}, ...]
|
|
206
|
-
jq
|
|
207
|
-
|
|
208
|
-
name="$(jq -r .name <<< "$app")" \
|
|
209
|
-
parent_project=applications \
|
|
210
|
-
account_links="$(jq -c '[{account: .account, environment: "PRODUCTION"}]' <<< "$app")"
|
|
211
|
-
done
|
|
261
|
+
jq 'map({key: "app_\(.id)", value: {name, parent_project: "applications", account_links: [{account, environment: "PRODUCTION"}]}}) | from_entries' apps.json > entries.json
|
|
262
|
+
yamlctl project apply -f entries.json --prune --prefix app_
|
|
212
263
|
yamlctl check
|
|
213
264
|
```
|
|
214
265
|
|
|
215
266
|
Three rules keep such a sync safe:
|
|
216
267
|
|
|
217
268
|
- **The key never changes.** It identifies the entry for whatever reads the file, so it comes from an id the source never changes, `app_1042`, never from a name.
|
|
218
|
-
- **A sync owns its entries.** A prefix per source, `app_`, tells its entries from the ones written by hand, and
|
|
219
|
-
- **Idempotent by design.** `
|
|
269
|
+
- **A sync owns its entries.** A prefix per source, `app_`, tells its entries from the ones written by hand, and `--prune --prefix app_` deletes only keys carrying it, refusing a file holding any other key.
|
|
270
|
+
- **Idempotent by design.** `apply -f --prune` of unchanged entries succeeds without writing, so a sync can simply run again.
|
|
271
|
+
A field the source stops sending is kept by the merge, so the sync sends it as `null` to remove it.
|
|
220
272
|
|
|
221
273
|
## License
|
|
222
274
|
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// yamlctl <resource> <verb> [key] [field=value...]
|
|
1
|
+
// yamlctl <resource> <verb> [key] [field=value...] or -f <file>, and the few verbs that take no resource.
|
|
2
2
|
//
|
|
3
3
|
// The grammar is noun then verb, `yamlctl project list`, so every verb a resource has sits beside the others in the help and a new one lands in the same place.
|
|
4
4
|
import { existsSync, readFileSync } from 'node:fs';
|
|
@@ -17,48 +17,71 @@ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.u
|
|
|
17
17
|
export const HELP = `yamlctl reads and edits YAML data files entry by entry, every change checked against the file's JSON Schema.
|
|
18
18
|
|
|
19
19
|
Usage:
|
|
20
|
-
yamlctl <resource> list
|
|
21
|
-
yamlctl <resource> get <key
|
|
22
|
-
yamlctl <resource>
|
|
23
|
-
yamlctl <resource>
|
|
24
|
-
yamlctl <resource>
|
|
25
|
-
yamlctl <resource>
|
|
26
|
-
yamlctl <resource>
|
|
27
|
-
yamlctl
|
|
28
|
-
yamlctl
|
|
20
|
+
yamlctl <resource> list the entries, one line each
|
|
21
|
+
yamlctl <resource> get <key>... the entries under their keys, as YAML
|
|
22
|
+
yamlctl <resource> create <key> <field>=<value>... a new entry, refused if the key is taken
|
|
23
|
+
yamlctl <resource> create -f <file> every entry of the file, refused if a key is taken
|
|
24
|
+
yamlctl <resource> apply <key> <field>=<value>... create the entry, or change the fields given and keep the others
|
|
25
|
+
yamlctl <resource> apply -f <file> create each entry of the file, or merge it into the one there
|
|
26
|
+
yamlctl <resource> patch <key> <field>=<value>... change the fields given of an existing entry, keep the others
|
|
27
|
+
yamlctl <resource> replace -f <file> replace each entry of the file whole, refused if one is missing
|
|
28
|
+
yamlctl <resource> delete <key>... remove the entries
|
|
29
|
+
yamlctl <resource> delete -f <file> remove the entries the file names
|
|
30
|
+
yamlctl <resource> explain [field] what the entries hold: fields, types, allowed values
|
|
31
|
+
yamlctl <resource> check the file against its schema
|
|
32
|
+
yamlctl resources every resource in the directory
|
|
33
|
+
yamlctl check every file in the directory against its schema
|
|
29
34
|
|
|
30
35
|
A resource is a file, project for project.yaml or project.yml, or a map of entries inside one, found in whichever file holds it.
|
|
31
36
|
A field inside an object is a path, risk_profile.business_impact, and a list or an object is written as JSON.
|
|
32
37
|
An empty value, description=, removes the field.
|
|
33
38
|
|
|
39
|
+
A file given with -f holds entries under their keys, the shape get and list -o yaml print, as YAML or JSON.
|
|
40
|
+
apply -f merges each one into the entry already there: an object merges, a list replaces, and null removes the field.
|
|
41
|
+
|
|
34
42
|
The schema is the one the file names on its first line,
|
|
35
43
|
# yaml-language-server: $schema=schemas/project.schema.json
|
|
36
44
|
else schemas/<name>.schema.json, else <name>.schema.json beside the file.
|
|
37
45
|
A remote schema, and every remote $ref, is fetched and cached for a day in ${cacheDir()}.
|
|
38
46
|
|
|
39
47
|
Options:
|
|
40
|
-
-C, --dir <dir>
|
|
41
|
-
|
|
42
|
-
-o, --output <fmt>
|
|
43
|
-
|
|
44
|
-
--force
|
|
45
|
-
--
|
|
46
|
-
--
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
-C, --dir <dir> the directory holding the data files (default: the current directory)
|
|
49
|
+
--data-file <file> the data file, for a resource the directory does not name on its own
|
|
50
|
+
-o, --output <fmt> yaml, json or name, for a pipeline: the entries, or their resource paths, instead of a table or a sentence
|
|
51
|
+
-f, --filename <file> the entries to create, apply, replace or delete, - for standard input
|
|
52
|
+
--force accept a change the schema marks immutable
|
|
53
|
+
--ignore-not-found delete succeeds without a word when the entry is not there
|
|
54
|
+
--prune apply -f also deletes the entries the file does not hold, within --prefix or --all
|
|
55
|
+
--prefix <prefix> the keys --prune may delete, the ones a sync owns
|
|
56
|
+
--all --prune may delete any entry of the map
|
|
57
|
+
--offline read remote schemas from the cache only, never from the network
|
|
58
|
+
--refresh fetch remote schemas again even when the cache holds a recent copy
|
|
59
|
+
-h, --help this help
|
|
60
|
+
-v, --version the version
|
|
49
61
|
|
|
50
62
|
Examples:
|
|
51
|
-
yamlctl project
|
|
63
|
+
yamlctl project create checkout_api name="Checkout API" risk_profile.business_impact=HBI
|
|
64
|
+
yamlctl project patch checkout_api risk_profile.business_impact=MBI
|
|
52
65
|
yamlctl project get checkout_api -o json
|
|
53
|
-
yamlctl project
|
|
66
|
+
yamlctl project list -o yaml > projects.yaml && yamlctl project apply -f projects.yaml
|
|
54
67
|
yamlctl project explain risk_profile
|
|
55
68
|
`;
|
|
56
69
|
|
|
57
70
|
class UsageError extends Error {}
|
|
58
71
|
|
|
72
|
+
// The verbs writing an entry, named and behaving as kubectl's do, so someone who knows one knows the other.
|
|
73
|
+
// `exists` is what the entry must be beforehand, `fields` and `filename` the input each takes, and `done` what the output says.
|
|
74
|
+
const WRITES = {
|
|
75
|
+
create: { exists: false, fields: true, filename: true, done: () => 'created' },
|
|
76
|
+
apply: { exists: null, fields: true, filename: true, done: (existed, changed) => (!existed ? 'created' : changed ? 'configured' : 'unchanged') },
|
|
77
|
+
patch: { exists: true, fields: true, filename: false, done: (existed, changed) => (changed ? 'patched' : 'patched (no change)') },
|
|
78
|
+
replace: { exists: true, fields: false, filename: true, done: (existed, changed) => (changed ? 'replaced' : 'replaced (no change)') },
|
|
79
|
+
};
|
|
80
|
+
const VERBS = 'list, get, create, apply, patch, replace, delete, explain or check';
|
|
81
|
+
|
|
59
82
|
// Options may come anywhere, before or after the resource, so `yamlctl -C data project list` and `yamlctl project list -C data` read the same.
|
|
60
83
|
export function parseArgs(argv) {
|
|
61
|
-
const options = { dir: '.',
|
|
84
|
+
const options = { dir: '.', dataFile: null, output: null, filename: null, force: false, ignoreNotFound: false, prune: false, all: false, prefix: null, offline: false, refresh: false, help: false, version: false };
|
|
62
85
|
const words = [];
|
|
63
86
|
for (let i = 0; i < argv.length; i++) {
|
|
64
87
|
const arg = argv[i];
|
|
@@ -67,10 +90,14 @@ export function parseArgs(argv) {
|
|
|
67
90
|
return argv[++i];
|
|
68
91
|
};
|
|
69
92
|
if (arg === '-C' || arg === '--dir') options.dir = value();
|
|
70
|
-
else if (arg === '-
|
|
93
|
+
else if (arg === '--data-file') options.dataFile = value();
|
|
71
94
|
else if (arg === '-o' || arg === '--output') options.output = value();
|
|
72
|
-
else if (arg === '--
|
|
95
|
+
else if (arg === '-f' || arg === '--filename') options.filename = value();
|
|
73
96
|
else if (arg === '--force') options.force = true;
|
|
97
|
+
else if (arg === '--ignore-not-found') options.ignoreNotFound = true;
|
|
98
|
+
else if (arg === '--prune') options.prune = true;
|
|
99
|
+
else if (arg === '--all') options.all = true;
|
|
100
|
+
else if (arg === '--prefix') options.prefix = value();
|
|
74
101
|
else if (arg === '--offline') options.offline = true;
|
|
75
102
|
else if (arg === '--refresh') options.refresh = true;
|
|
76
103
|
else if (arg === '-h' || arg === '--help') options.help = true;
|
|
@@ -88,7 +115,7 @@ export function parseArgs(argv) {
|
|
|
88
115
|
}
|
|
89
116
|
|
|
90
117
|
// The schemas the command can reach are fetched first, the only step needing the network, so everything after it runs synchronously from what was fetched.
|
|
91
|
-
// Only the files a command could read are looked at: the one -
|
|
118
|
+
// Only the files a command could read are looked at: the one --data-file names, else every data file of the directory.
|
|
92
119
|
export async function main(argv, io = {}) {
|
|
93
120
|
const err = io.err ?? ((text) => process.stderr.write(text));
|
|
94
121
|
const cwd = io.cwd ?? process.cwd();
|
|
@@ -100,7 +127,7 @@ export async function main(argv, io = {}) {
|
|
|
100
127
|
return run(argv, io);
|
|
101
128
|
}
|
|
102
129
|
const { options } = parsed;
|
|
103
|
-
const uris = schemaUris(options.
|
|
130
|
+
const uris = schemaUris(options.dataFile ? [resolve(cwd, options.dataFile)] : safeDataFiles(resolve(cwd, options.dir)));
|
|
104
131
|
if (uris.length) {
|
|
105
132
|
await prefetch(uris, {
|
|
106
133
|
offline: options.offline || env.YAMLCTL_OFFLINE === '1',
|
|
@@ -154,22 +181,24 @@ export function run(argv, { out = (text) => process.stdout.write(text), err = (t
|
|
|
154
181
|
out(HELP);
|
|
155
182
|
return 0;
|
|
156
183
|
}
|
|
184
|
+
checkPrune(options, words[1]);
|
|
157
185
|
const dir = resolve(cwd, options.dir);
|
|
158
|
-
const file = options.
|
|
186
|
+
const file = options.dataFile ? resolve(cwd, options.dataFile) : null;
|
|
159
187
|
const context = { options, dir, file, out, err, stdin, cwd };
|
|
160
188
|
|
|
161
189
|
if (words[0] === 'resources' && words.length === 1) return resources(context);
|
|
162
|
-
if (words[0] === 'check' && words.length === 1) return checkDirectory(context);
|
|
163
|
-
if (words.length < 2) throw new UsageError(`${words[0]} needs a verb:
|
|
190
|
+
if (words[0] === 'check' && words.length === 1) return checkDirectory(needNoOutput(context, 'check'));
|
|
191
|
+
if (words.length < 2) throw new UsageError(`${words[0]} needs a verb: ${VERBS}`);
|
|
164
192
|
|
|
165
193
|
const [name, verb, ...args] = words;
|
|
166
194
|
const target = resolveResource({ dir, name, file });
|
|
167
195
|
// A file naming a schema that cannot be loaded is not written: checking nothing where the file asked for a check is the one outcome worse than stopping.
|
|
168
|
-
if (target.schemaError && (verb
|
|
196
|
+
if (target.schemaError && (Object.hasOwn(WRITES, verb) || verb === 'delete')) throw new Error(`${display(target.file, cwd)} ${target.schemaError}, so it is not written`);
|
|
169
197
|
if (target.schemaError) err(`warning: ${display(target.file, cwd)} ${target.schemaError}, so nothing is checked\n`);
|
|
170
198
|
else if (!target.schema) err(`warning: no schema found for ${display(target.file, cwd)}, so nothing is checked\n`);
|
|
171
|
-
|
|
172
|
-
|
|
199
|
+
if (Object.hasOwn(WRITES, verb)) return write(verb, { ...context, name, target, args });
|
|
200
|
+
const commands = { list, get, delete: remove, explain: (c) => explainCommand(needNoOutput(c, 'explain')), check: (c) => checkResource(needNoOutput(c, 'check')) };
|
|
201
|
+
if (!Object.hasOwn(commands, verb)) throw new UsageError(`unknown verb ${verb}, use ${VERBS}`);
|
|
173
202
|
return commands[verb]({ ...context, name, target, args });
|
|
174
203
|
} catch (e) {
|
|
175
204
|
err(`error: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
@@ -178,6 +207,23 @@ export function run(argv, { out = (text) => process.stdout.write(text), err = (t
|
|
|
178
207
|
}
|
|
179
208
|
}
|
|
180
209
|
|
|
210
|
+
// Pruning deletes what the file does not hold, so it is refused without a scope saying which entries it may delete, as kubectl refuses it without a selector or --all.
|
|
211
|
+
function checkPrune(options, verb) {
|
|
212
|
+
if (!options.prune) {
|
|
213
|
+
if (options.prefix !== null || options.all) throw new UsageError('--prefix and --all work with --prune only');
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (verb !== 'apply' || !options.filename) throw new UsageError('--prune works with apply -f only');
|
|
217
|
+
if (options.prefix !== null && options.all) throw new UsageError('--prune takes --prefix <prefix> or --all, not both');
|
|
218
|
+
if (options.prefix === '') throw new UsageError('--prefix needs a prefix, --all prunes every entry');
|
|
219
|
+
if (options.prefix === null && !options.all) throw new UsageError('--prune needs --prefix <prefix> or --all, the entries it may delete');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function needNoOutput(context, verb) {
|
|
223
|
+
if (context.options.output) throw new UsageError(verb === 'check' ? 'check takes no -o, its exit status is the result' : `${verb} takes no -o`);
|
|
224
|
+
return context;
|
|
225
|
+
}
|
|
226
|
+
|
|
181
227
|
// A path relative to where the command runs, an address as it is.
|
|
182
228
|
const display = (path, cwd) => {
|
|
183
229
|
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) return path;
|
|
@@ -192,13 +238,26 @@ function needMap(target, name) {
|
|
|
192
238
|
throw new Error(`${basename(target.file)} holds several maps, use one as the resource: ${target.maps.map((map) => `yamlctl ${map} ...`).join(', ')}`);
|
|
193
239
|
}
|
|
194
240
|
|
|
195
|
-
function needKey(args, verb) {
|
|
196
|
-
if (!args[0]) throw new UsageError(`${verb} needs the key of an entry`);
|
|
241
|
+
function needKey(args, verb, orFile = false) {
|
|
242
|
+
if (!args[0]) throw new UsageError(`${verb} needs the key of an entry${orFile ? ', or -f <file>' : ''}`);
|
|
197
243
|
return args[0];
|
|
198
244
|
}
|
|
199
245
|
|
|
200
|
-
function
|
|
201
|
-
|
|
246
|
+
function printData(value, format, out) {
|
|
247
|
+
out(format === 'json' ? `${JSON.stringify(value, null, 2)}\n` : stringify(value, { lineWidth: 0 }));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function resources({ dir, options, out, cwd }) {
|
|
251
|
+
const found = listResources(dir);
|
|
252
|
+
if (options.output === 'name') {
|
|
253
|
+
for (const r of found) out(`${r.name}\n`);
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
if (options.output) {
|
|
257
|
+
printData(found.map((r) => ({ ...r, file: display(r.file, cwd), schema: r.schema ? display(r.schema, cwd) : null })), options.output, out);
|
|
258
|
+
return 0;
|
|
259
|
+
}
|
|
260
|
+
const rows = found.map((r) => [r.name, display(r.file, cwd), r.map ?? '-', r.entries ?? '-', r.error ? `error: ${r.error}` : r.schema ? display(r.schema, cwd) : '-']);
|
|
202
261
|
out(table(['RESOURCE', 'FILE', 'MAP', 'ENTRIES', 'SCHEMA'], rows));
|
|
203
262
|
return 0;
|
|
204
263
|
}
|
|
@@ -208,7 +267,7 @@ function list({ target, options, out }) {
|
|
|
208
267
|
const data = target.document.data;
|
|
209
268
|
if (options.output === 'json' || options.output === 'yaml') {
|
|
210
269
|
const value = target.map ? (data[target.map] ?? {}) : Object.fromEntries(maps.map((map) => [map, data[map] ?? {}]));
|
|
211
|
-
|
|
270
|
+
printData(value, options.output, out);
|
|
212
271
|
return 0;
|
|
213
272
|
}
|
|
214
273
|
for (const map of maps) {
|
|
@@ -229,80 +288,174 @@ function list({ target, options, out }) {
|
|
|
229
288
|
|
|
230
289
|
function get({ target, name, args, options, out }) {
|
|
231
290
|
const map = needMap(target, name);
|
|
232
|
-
|
|
291
|
+
needKey(args, 'get');
|
|
233
292
|
const entries = target.document.data[map] ?? {};
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
293
|
+
const found = {};
|
|
294
|
+
for (const key of args) {
|
|
295
|
+
if (!Object.hasOwn(entries, key)) throw new Error(`no entry ${key} in ${map}`);
|
|
296
|
+
found[key] = entries[key];
|
|
297
|
+
}
|
|
298
|
+
// Under their keys, the shape -f reads, so what get prints goes back through apply or replace as it is.
|
|
299
|
+
if (options.output === 'name') for (const key of Object.keys(found)) out(`${map}/${key}\n`);
|
|
300
|
+
else printData(found, options.output === 'json' ? 'json' : 'yaml', out);
|
|
237
301
|
return 0;
|
|
238
302
|
}
|
|
239
303
|
|
|
240
|
-
|
|
304
|
+
const REPLACE_USAGE = 'replace takes -f <file> only, patch takes <key> <field>=<value>...';
|
|
305
|
+
|
|
306
|
+
// Every entry the command writes is checked against the file as it will be, and the file is written once, or not at all when one of them fails.
|
|
307
|
+
function write(verb, context) {
|
|
308
|
+
const { target, name, args, options, out, err, cwd } = context;
|
|
309
|
+
const rules = WRITES[verb];
|
|
241
310
|
const map = needMap(target, name);
|
|
242
|
-
const key = needKey(args, 'set');
|
|
243
|
-
const assignments = args.slice(1);
|
|
244
311
|
const { document, schema } = target;
|
|
245
312
|
const entries = document.data[map] ?? {};
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
if (
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) throw new Error(`${options.from === '-' ? 'standard input' : options.from} does not hold one entry`);
|
|
313
|
+
let changes;
|
|
314
|
+
|
|
315
|
+
if (options.filename) {
|
|
316
|
+
if (!rules.filename) throw new UsageError('patch takes <key> <field>=<value>..., replace takes -f <file>');
|
|
317
|
+
if (args.length) throw new UsageError(verb === 'replace' ? REPLACE_USAGE : `${verb} takes -f <file> without a key`);
|
|
318
|
+
const given = readEntries(options.filename, context);
|
|
319
|
+
changes = Object.entries(given).map(([key, entry]) => ({ key, entry: verb === 'apply' ? mergePatch(entries[key], entry) : entry }));
|
|
254
320
|
} else {
|
|
255
|
-
if (!
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
const path = assignment.slice(0, at);
|
|
262
|
-
const text = assignment.slice(at + 1);
|
|
263
|
-
const segments = path.split('.');
|
|
264
|
-
if (segments.some((segment) => segment === '')) throw new UsageError(`${path} is not a field path`);
|
|
265
|
-
const field = schema ? schema.field(entryPointer, segments) : null;
|
|
266
|
-
if (schema && !field) {
|
|
267
|
-
if (schema.field(entryPointer, segments, { throughLists: true })) throw new Error(`${path}: goes into a list, which is set whole as JSON: ${segments[0]}='[...]'`);
|
|
268
|
-
throw new Error(`${path}: no such field in ${map}, run yamlctl ${name} explain to list them`);
|
|
269
|
-
}
|
|
270
|
-
let parent = entry;
|
|
271
|
-
for (const segment of segments.slice(0, -1)) {
|
|
272
|
-
if (parent[segment] === null || typeof parent[segment] !== 'object' || Array.isArray(parent[segment])) parent[segment] = {};
|
|
273
|
-
parent = parent[segment];
|
|
274
|
-
}
|
|
275
|
-
const last = segments.at(-1);
|
|
276
|
-
if (text === '') {
|
|
277
|
-
delete parent[last];
|
|
278
|
-
continue;
|
|
279
|
-
}
|
|
280
|
-
try {
|
|
281
|
-
parent[last] = field ? typedValue(field.schema, text) : parseLoose(text);
|
|
282
|
-
} catch (e) {
|
|
283
|
-
throw new Error(`${path}: ${e instanceof Error ? e.message : String(e)}`);
|
|
284
|
-
}
|
|
285
|
-
}
|
|
321
|
+
if (!rules.fields) throw new UsageError(REPLACE_USAGE);
|
|
322
|
+
const key = needKey(args, verb, rules.filename);
|
|
323
|
+
const assignments = args.slice(1);
|
|
324
|
+
if (!assignments.length) throw new UsageError(`${verb} needs at least one <field>=<value>${rules.filename ? ', or -f <file>' : ''}`);
|
|
325
|
+
const base = isObject(entries[key]) ? entries[key] : {};
|
|
326
|
+
changes = [{ key, entry: assign(structuredClone(base), assignments, { schema, map, name }) }];
|
|
286
327
|
}
|
|
287
328
|
|
|
329
|
+
for (const { key } of changes) {
|
|
330
|
+
const exists = Object.hasOwn(entries, key);
|
|
331
|
+
if (rules.exists === false && exists) throw new Error(`${map}/${key} already exists, use apply, patch or replace to change it`);
|
|
332
|
+
if (rules.exists === true && !exists) throw new Error(`no entry ${key} in ${map}`);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const next = { ...document.data, [map]: { ...entries } };
|
|
336
|
+
for (const { key, entry } of changes) next[map][key] = entry;
|
|
337
|
+
let pruned = [];
|
|
338
|
+
if (options.prune) {
|
|
339
|
+
const owned = (key) => options.all || key.startsWith(options.prefix);
|
|
340
|
+
const outside = changes.find(({ key }) => !owned(key));
|
|
341
|
+
if (outside) throw new Error(`${options.filename === '-' ? 'standard input' : options.filename} holds ${outside.key}, outside the prefix ${options.prefix} it prunes`);
|
|
342
|
+
pruned = Object.keys(entries).filter((key) => owned(key) && !changes.some((change) => change.key === key));
|
|
343
|
+
for (const key of pruned) delete next[map][key];
|
|
344
|
+
}
|
|
288
345
|
const problems = [];
|
|
289
|
-
|
|
290
|
-
|
|
346
|
+
for (const { key, entry } of changes) {
|
|
347
|
+
if (schema) problems.push(...schema.validate(schema.entryPointer(map), entry, `${map}/${key}`));
|
|
348
|
+
problems.push(...checkSet({ schema, data: next, previous: document.data, map, key, entry, force: options.force }).map((problem) => `${map}/${key}: ${problem}`));
|
|
349
|
+
}
|
|
291
350
|
if (problems.length) {
|
|
292
351
|
for (const problem of problems) err(`${problem}\n`);
|
|
293
|
-
throw new Error(`${map}/${key} not written`);
|
|
352
|
+
throw new Error(`${options.filename ? display(target.file, cwd) : `${map}/${changes[0].key}`} not written`);
|
|
353
|
+
}
|
|
354
|
+
for (const key of pruned) {
|
|
355
|
+
const referencing = referencesTo({ schema, data: next, map, key });
|
|
356
|
+
if (referencing.length) throw new Error(`${map}/${key} is still named by ${referencing.join(', ')}: delete or change them first`);
|
|
294
357
|
}
|
|
295
358
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
359
|
+
const lines = [];
|
|
360
|
+
for (const { key, entry } of changes) {
|
|
361
|
+
const existed = Object.hasOwn(entries, key);
|
|
362
|
+
const changed = !existed || !sameData(entries[key], entry);
|
|
363
|
+
if (changed) setEntry(document, map, key, entry);
|
|
364
|
+
lines.push(`${map}/${key} ${rules.done(existed, changed)}\n`);
|
|
365
|
+
}
|
|
366
|
+
for (const key of pruned) {
|
|
367
|
+
deleteEntry(document, map, key);
|
|
368
|
+
lines.push(`${map}/${key} pruned\n`);
|
|
299
369
|
}
|
|
300
|
-
setEntry(document, map, key, entry);
|
|
301
370
|
writeDocument(document);
|
|
302
|
-
|
|
371
|
+
// A pipeline reads the entries or their paths rather than a sentence, and -o name keeps the entries pruned, since they are part of what was done.
|
|
372
|
+
if (options.output === 'name') for (const key of [...changes.map((change) => change.key), ...pruned]) out(`${map}/${key}\n`);
|
|
373
|
+
else if (options.output) printData(Object.fromEntries(changes.map(({ key, entry }) => [key, entry])), options.output, out);
|
|
374
|
+
else for (const line of lines) out(line);
|
|
303
375
|
return 0;
|
|
304
376
|
}
|
|
305
377
|
|
|
378
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
379
|
+
|
|
380
|
+
// Equal whatever the order of the fields, since an entry read from a file lists them in whatever order its author chose.
|
|
381
|
+
function sameData(a, b) {
|
|
382
|
+
const canonical = (value) => (Array.isArray(value) ? value.map(canonical) : isObject(value) ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])) : value);
|
|
383
|
+
return JSON.stringify(canonical(a ?? null)) === JSON.stringify(canonical(b ?? null));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// A JSON merge patch, RFC 7386, which is what apply -f does to an entry, as kubectl apply does to an object:
|
|
387
|
+
// an object merges into the one it meets, anything else replaces what it meets, a list included, and null removes the field.
|
|
388
|
+
function mergePatch(target, patch) {
|
|
389
|
+
if (!isObject(patch)) return patch;
|
|
390
|
+
const result = isObject(target) ? { ...target } : {};
|
|
391
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
392
|
+
if (value === null) delete result[key];
|
|
393
|
+
else result[key] = mergePatch(result[key], value);
|
|
394
|
+
}
|
|
395
|
+
return result;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// The entries an -f file holds by key, the shape get and list -o yaml print, each one an object.
|
|
399
|
+
function readEntries(filename, { stdin, cwd }) {
|
|
400
|
+
const source = filename === '-' ? 'standard input' : filename;
|
|
401
|
+
let text;
|
|
402
|
+
if (filename === '-') text = stdin();
|
|
403
|
+
else {
|
|
404
|
+
try {
|
|
405
|
+
text = readFileSync(resolve(cwd, filename), 'utf8');
|
|
406
|
+
} catch (e) {
|
|
407
|
+
throw new Error(`cannot read ${filename}: ${e instanceof Error ? e.message : String(e)}`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
let entries;
|
|
411
|
+
try {
|
|
412
|
+
entries = parse(text);
|
|
413
|
+
} catch (e) {
|
|
414
|
+
throw new Error(`${source} is not valid YAML: ${e instanceof Error ? e.message : String(e)}`);
|
|
415
|
+
}
|
|
416
|
+
if (entries === null || entries === undefined) throw new Error(`${source} holds no entries`);
|
|
417
|
+
if (!isObject(entries)) throw new Error(`${source} does not hold entries by key`);
|
|
418
|
+
if (!Object.keys(entries).length) throw new Error(`${source} holds no entries`);
|
|
419
|
+
for (const [key, entry] of Object.entries(entries)) {
|
|
420
|
+
if (!isObject(entry)) throw new Error(`${source}: ${key} is not an entry`);
|
|
421
|
+
}
|
|
422
|
+
return entries;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// The <field>=<value> assignments written into an entry, each value typed by the schema.
|
|
426
|
+
function assign(entry, assignments, { schema, map, name }) {
|
|
427
|
+
const entryPointer = schema?.entryPointer(map);
|
|
428
|
+
for (const assignment of assignments) {
|
|
429
|
+
const at = assignment.indexOf('=');
|
|
430
|
+
if (at < 1) throw new UsageError(`${assignment} is not <field>=<value>`);
|
|
431
|
+
const path = assignment.slice(0, at);
|
|
432
|
+
const text = assignment.slice(at + 1);
|
|
433
|
+
const segments = path.split('.');
|
|
434
|
+
if (segments.some((segment) => segment === '')) throw new UsageError(`${path} is not a field path`);
|
|
435
|
+
const field = schema ? schema.field(entryPointer, segments) : null;
|
|
436
|
+
if (schema && !field) {
|
|
437
|
+
if (schema.field(entryPointer, segments, { throughLists: true })) throw new Error(`${path}: goes into a list, which is set whole as JSON: ${segments[0]}='[...]'`);
|
|
438
|
+
throw new Error(`${path}: no such field in ${map}, run yamlctl ${name} explain to list them`);
|
|
439
|
+
}
|
|
440
|
+
let parent = entry;
|
|
441
|
+
for (const segment of segments.slice(0, -1)) {
|
|
442
|
+
if (!isObject(parent[segment])) parent[segment] = {};
|
|
443
|
+
parent = parent[segment];
|
|
444
|
+
}
|
|
445
|
+
const last = segments.at(-1);
|
|
446
|
+
if (text === '') {
|
|
447
|
+
delete parent[last];
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
parent[last] = field ? typedValue(field.schema, text) : parseLoose(text);
|
|
452
|
+
} catch (e) {
|
|
453
|
+
throw new Error(`${path}: ${e instanceof Error ? e.message : String(e)}`);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return entry;
|
|
457
|
+
}
|
|
458
|
+
|
|
306
459
|
// Without a schema a value is read the way YAML would read it, so a number or a list typed on the command line keeps its type.
|
|
307
460
|
function parseLoose(text) {
|
|
308
461
|
try {
|
|
@@ -312,19 +465,34 @@ function parseLoose(text) {
|
|
|
312
465
|
}
|
|
313
466
|
}
|
|
314
467
|
|
|
315
|
-
function remove(
|
|
468
|
+
function remove(context) {
|
|
469
|
+
const { target, name, args, options, out } = context;
|
|
470
|
+
if (options.output && options.output !== 'name') throw new UsageError('delete takes -o name only');
|
|
316
471
|
const map = needMap(target, name);
|
|
317
|
-
|
|
472
|
+
let keys;
|
|
473
|
+
if (options.filename) {
|
|
474
|
+
if (args.length) throw new UsageError('delete takes -f <file> without a key');
|
|
475
|
+
keys = Object.keys(readEntries(options.filename, context));
|
|
476
|
+
} else {
|
|
477
|
+
needKey(args, 'delete', true);
|
|
478
|
+
keys = [...new Set(args)];
|
|
479
|
+
}
|
|
318
480
|
const { document, schema } = target;
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
481
|
+
const entries = document.data[map] ?? {};
|
|
482
|
+
const present = [];
|
|
483
|
+
for (const key of keys) {
|
|
484
|
+
if (Object.hasOwn(entries, key)) present.push(key);
|
|
485
|
+
else if (!options.ignoreNotFound) throw new Error(`no entry ${key} in ${map}`);
|
|
486
|
+
}
|
|
487
|
+
// Checked against the file as it will be, so an entry deleted along with every entry naming it is not refused.
|
|
488
|
+
const next = { ...document.data, [map]: Object.fromEntries(Object.entries(entries).filter(([key]) => !present.includes(key))) };
|
|
489
|
+
for (const key of present) {
|
|
490
|
+
const referencing = referencesTo({ schema, data: next, map, key });
|
|
491
|
+
if (referencing.length) throw new Error(`${map}/${key} is still named by ${referencing.join(', ')}: delete or change them first`);
|
|
322
492
|
}
|
|
323
|
-
const
|
|
324
|
-
if (referencing.length) throw new Error(`${map}/${key} is still named by ${referencing.join(', ')}: delete or change them first`);
|
|
325
|
-
deleteEntry(document, map, key);
|
|
493
|
+
for (const key of present) deleteEntry(document, map, key);
|
|
326
494
|
writeDocument(document);
|
|
327
|
-
out(`${map}/${key} deleted\n`);
|
|
495
|
+
for (const key of present) out(options.output === 'name' ? `${map}/${key}\n` : `${map}/${key} deleted\n`);
|
|
328
496
|
return 0;
|
|
329
497
|
}
|
|
330
498
|
|
package/src/document.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// A YAML data file read and written in place, so the entries yamlctl does not touch, the comments and the order of the file come back exactly as they were.
|
|
2
2
|
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import { parseDocument } from 'yaml';
|
|
3
|
+
import { isMap, parseDocument } from 'yaml';
|
|
4
4
|
|
|
5
5
|
export function readDocument(file) {
|
|
6
6
|
let text;
|
|
@@ -31,11 +31,40 @@ export function writeDocument(document) {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
export function setEntry(document, map, key, entry) {
|
|
34
|
+
const { doc } = document;
|
|
34
35
|
// An empty map is usually written `{}`, and an entry added to it would stay on that one line, so the map becomes a block first.
|
|
35
|
-
const node =
|
|
36
|
+
const node = doc.get(map, true);
|
|
36
37
|
if (node && typeof node === 'object' && 'flow' in node) node.flow = false;
|
|
37
|
-
if (!node || node.items === undefined)
|
|
38
|
-
|
|
38
|
+
if (!node || node.items === undefined) doc.set(map, doc.createNode({}));
|
|
39
|
+
const current = doc.getIn([map, key], true);
|
|
40
|
+
if (isMap(current)) update(doc, current, entry);
|
|
41
|
+
else doc.setIn([map, key], doc.createNode(entry));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
45
|
+
|
|
46
|
+
// An entry already in the file is changed field by field rather than rebuilt, since a node built anew carries none of the comments written inside the old one.
|
|
47
|
+
// A field keeps its place, a new one goes last, and a value replaced keeps the comments written before and after it.
|
|
48
|
+
function update(doc, node, value) {
|
|
49
|
+
for (const pair of [...node.items]) {
|
|
50
|
+
const key = pair.key?.value ?? pair.key;
|
|
51
|
+
if (!Object.hasOwn(value, key)) node.delete(key);
|
|
52
|
+
}
|
|
53
|
+
for (const [key, next] of Object.entries(value)) {
|
|
54
|
+
const child = node.get(key, true);
|
|
55
|
+
if (isMap(child) && isObject(next)) {
|
|
56
|
+
update(doc, child, next);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (child && typeof child.toJSON === 'function' && JSON.stringify(child.toJSON()) === JSON.stringify(next)) continue;
|
|
60
|
+
const fresh = doc.createNode(next);
|
|
61
|
+
if (child && typeof child === 'object') {
|
|
62
|
+
fresh.commentBefore = child.commentBefore;
|
|
63
|
+
fresh.comment = child.comment;
|
|
64
|
+
fresh.spaceBefore = child.spaceBefore;
|
|
65
|
+
}
|
|
66
|
+
node.set(key, fresh);
|
|
67
|
+
}
|
|
39
68
|
}
|
|
40
69
|
|
|
41
70
|
export function deleteEntry(document, map, key) {
|
package/src/explain.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// `yamlctl <resource> explain [field]`, the schema read back as text, the way `kubectl explain` reads an API.
|
|
2
|
-
// It is what someone writing a pipeline needs before the first `
|
|
2
|
+
// It is what someone writing a pipeline needs before the first `create`: which fields exist, what each holds, and which values it takes.
|
|
3
3
|
import { EXTENSION, escapeKey, types } from './schema.js';
|
|
4
4
|
|
|
5
5
|
export function explain(schema, map, segments) {
|
package/src/resources.js
CHANGED
|
@@ -64,7 +64,7 @@ export function resolveResource({ dir, name, file = null }) {
|
|
|
64
64
|
|
|
65
65
|
const files = dataFiles(dir);
|
|
66
66
|
const byStem = files.filter((path) => stem(path) === name);
|
|
67
|
-
if (byStem.length > 1) throw new Error(`${byStem.map((path) => basename(path)).join(' and ')} both exist, name one with -
|
|
67
|
+
if (byStem.length > 1) throw new Error(`${byStem.map((path) => basename(path)).join(' and ')} both exist, name one with --data-file`);
|
|
68
68
|
if (byStem.length === 1) return single(openFile(byStem[0]));
|
|
69
69
|
|
|
70
70
|
const holding = [];
|
|
@@ -73,7 +73,7 @@ export function resolveResource({ dir, name, file = null }) {
|
|
|
73
73
|
if (opened.maps.includes(name)) holding.push({ ...opened, map: name });
|
|
74
74
|
}
|
|
75
75
|
if (holding.length === 1) return holding[0];
|
|
76
|
-
if (holding.length > 1) throw new Error(`${holding.map((h) => basename(h.file)).join(' and ')} both hold a map ${name}, name one with -
|
|
76
|
+
if (holding.length > 1) throw new Error(`${holding.map((h) => basename(h.file)).join(' and ')} both hold a map ${name}, name one with --data-file`);
|
|
77
77
|
const known = listResources(dir).map((resource) => resource.name);
|
|
78
78
|
throw new Error(`no resource ${name} in ${dir}${known.length ? `, the resources are ${known.join(', ')}` : ', which holds no YAML data file'}`);
|
|
79
79
|
}
|
package/src/rules.js
CHANGED
|
@@ -30,7 +30,8 @@ const effective = (entry, defaults, field) => (entry?.[field] !== undefined && e
|
|
|
30
30
|
const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
31
31
|
|
|
32
32
|
// The reasons an entry about to be written breaks a rule, empty when it does not.
|
|
33
|
-
|
|
33
|
+
// `data` is the file as it will be once written, so an entry may name another written by the same command, and `previous` the file as it is, which an immutable field is compared with.
|
|
34
|
+
export function checkSet({ schema, data, previous = data, map, key, entry, force }) {
|
|
34
35
|
if (!schema) return [];
|
|
35
36
|
const problems = [];
|
|
36
37
|
const defaults = defaultsOf(schema, data, map);
|
|
@@ -47,7 +48,7 @@ export function checkSet({ schema, data, map, key, entry, force }) {
|
|
|
47
48
|
continue;
|
|
48
49
|
}
|
|
49
50
|
if (!Object.hasOwn(targets, name)) {
|
|
50
|
-
problems.push(`${rule.field}: ${name} is not an entry of ${targetMap},
|
|
51
|
+
problems.push(`${rule.field}: ${name} is not an entry of ${targetMap}, create it first`);
|
|
51
52
|
continue;
|
|
52
53
|
}
|
|
53
54
|
const targetDefaults = defaultsOf(schema, data, targetMap);
|
|
@@ -58,8 +59,8 @@ export function checkSet({ schema, data, map, key, entry, force }) {
|
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
if (rule.immutable && Object.hasOwn(
|
|
62
|
-
const before = effective(
|
|
62
|
+
if (rule.immutable && Object.hasOwn(previous[map] ?? {}, key) && !force) {
|
|
63
|
+
const before = effective(previous[map][key], defaultsOf(schema, previous, map), rule.field);
|
|
63
64
|
if (!same(before, value)) {
|
|
64
65
|
const reason = typeof rule.immutable === 'string' ? `, ${rule.immutable}` : '';
|
|
65
66
|
problems.push(`${rule.field}: changing ${JSON.stringify(before)} to ${JSON.stringify(value)} needs --force${reason}`);
|
package/src/schema.js
CHANGED
|
@@ -63,8 +63,9 @@ function pointerKeys(fragment, pointer) {
|
|
|
63
63
|
const isNull = (schema) => schema?.type === 'null' || (Array.isArray(schema?.type) && schema.type.length === 1 && schema.type[0] === 'null');
|
|
64
64
|
|
|
65
65
|
export class Schema {
|
|
66
|
-
// `uri` defaults to an address of its own for a schema built in memory
|
|
67
|
-
|
|
66
|
+
// `uri` defaults to an address of its own for a schema built in memory.
|
|
67
|
+
// It has a path, unlike a `urn:`, since a URL parser following the WHATWG standard refuses to resolve a relative reference against an opaque one, and the reference would then be dropped rather than reported as missing.
|
|
68
|
+
constructor(root, uri = 'yamlctl:/inline') {
|
|
68
69
|
this.root = root;
|
|
69
70
|
this.uri = uri;
|
|
70
71
|
this.path = displayUri(uri);
|