yamlctl 0.1.1 → 0.1.3

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