yamlctl 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bertrand THOMAS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,223 @@
1
+ # yamlctl
2
+
3
+ [![CI](https://github.com/devpro/yamlctl/actions/workflows/ci.yml/badge.svg)](https://github.com/devpro/yamlctl/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/yamlctl)](https://www.npmjs.com/package/yamlctl)
5
+
6
+ `yamlctl` reads and edits YAML data files entry by entry, and checks every change against the file's JSON Schema before writing it.
7
+
8
+ It is made for YAML files that are data rather than code, a list of projects, servers or rules, kept in git and read by Terraform, Ansible or anything else,
9
+ and updated by a pipeline from another system: a CMDB, a service catalog, a spreadsheet export.
10
+
11
+ - **Kubectl-like**: `yamlctl project list`, `yamlctl project get checkout_api`, `yamlctl project set checkout_api name="Checkout API"`.
12
+ - **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**: `005217217997` stays a string where the schema says string, where a plain YAML write would turn it into a number.
14
+ - **Careful with the file**: comments, order and every entry not named stay exactly as they were, and a command changing nothing writes nothing.
15
+ - **Nothing to configure**: the schema is the one the file already names for an editor.
16
+
17
+ ## Install
18
+
19
+ Node.js 20 or later:
20
+
21
+ ```bash
22
+ npm install --global yamlctl
23
+ yamlctl --help
24
+ ```
25
+
26
+ `npx yamlctl <command>` runs it without installing.
27
+
28
+ ## Quick start
29
+
30
+ `examples/` holds a data file and its schema, and every command below runs in it:
31
+
32
+ ```yaml
33
+ # yaml-language-server: $schema=schemas/project.schema.json
34
+ projects_defaults:
35
+ archived: false
36
+ projects:
37
+ applications:
38
+ name: "Applications"
39
+ is_folder: true
40
+ checkout_api:
41
+ name: "Checkout API"
42
+ parent_project: "applications"
43
+ risk_profile:
44
+ business_impact: "HBI"
45
+ ```
46
+
47
+ ```text
48
+ $ yamlctl resources
49
+ RESOURCE FILE MAP ENTRIES SCHEMA
50
+ project project.yaml projects 2 schemas/project.schema.json
51
+
52
+ $ yamlctl project list
53
+ KEY NAME
54
+ applications Applications
55
+ checkout_api Checkout API
56
+
57
+ $ yamlctl project set billing_api name="Billing API" parent_project=applications account=005217217997 risk_profile.business_impact=MBI
58
+ projects/billing_api created
59
+
60
+ $ yamlctl project get billing_api
61
+ name: Billing API
62
+ parent_project: applications
63
+ account: "005217217997"
64
+ risk_profile:
65
+ business_impact: MBI
66
+
67
+ $ yamlctl project set billing_api name="Billing API"
68
+ projects/billing_api unchanged
69
+ ```
70
+
71
+ What the entries hold is read from the schema, the way `kubectl explain` reads an API:
72
+
73
+ ```text
74
+ $ yamlctl project explain
75
+ RESOURCE: projects <object>
76
+
77
+ FIELDS:
78
+ name <string> Display name.
79
+ description <string>
80
+ archived <boolean> An archived project is kept but no longer active.
81
+ is_folder <boolean> A folder holds other projects rather than resources.
82
+ parent_project <string> Key of the folder holding this project.
83
+ account <string> Cloud account number, kept as text so a leading zero survives.
84
+ risk_profile <object>
85
+ account_links <[]object> Cloud accounts whose resources belong to the project.
86
+ tags <object> Free-form labels.
87
+
88
+ $ yamlctl project explain risk_profile.business_impact
89
+ FIELD: risk_profile.business_impact <enum>
90
+
91
+ DESCRIPTION:
92
+ How much the business depends on the project.
93
+
94
+ VALUES:
95
+ "LBI", "MBI", "HBI"
96
+ ```
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:
99
+
100
+ ```text
101
+ $ yamlctl project set billing_api risk_profle.business_impact=HBI
102
+ error: risk_profle.business_impact: no such field in projects, run yamlctl project explain to list them
103
+
104
+ $ yamlctl project set billing_api risk_profile.business_impact=HIGH
105
+ projects/billing_api.risk_profile.business_impact: must be one of "LBI", "MBI", "HBI"
106
+ error: projects/billing_api not written
107
+
108
+ $ yamlctl project set billing_api parent_project=checkout_api
109
+ projects/billing_api: parent_project: checkout_api must have is_folder: true, it has null
110
+ projects/billing_api: parent_project: changing "applications" to "checkout_api" needs --force, moving a project recreates it
111
+ error: projects/billing_api not written
112
+
113
+ $ yamlctl project delete applications
114
+ error: projects/applications is still named by projects/checkout_api, projects/billing_api: delete or change them first
115
+ ```
116
+
117
+ ## Commands
118
+
119
+ ```text
120
+ yamlctl <resource> list the entries, one line each
121
+ yamlctl <resource> get <key> one entry, as YAML
122
+ yamlctl <resource> set <key> <field>=<value>... create the entry, or change the fields given and keep the others
123
+ yamlctl <resource> set <key> --from <file> create or replace the whole entry from a YAML or JSON file, - for standard input
124
+ yamlctl <resource> delete <key> remove the entry
125
+ yamlctl <resource> explain [field] what the entries hold: fields, types, allowed values
126
+ yamlctl <resource> check the file against its schema
127
+ yamlctl resources every resource in the directory
128
+ yamlctl check every file in the directory against its schema
129
+ ```
130
+
131
+ Option | Action
132
+ ------------------------|------------------------------------------------------------------------------------------
133
+ `-C, --dir <dir>` | the directory holding the data files, the current one by default
134
+ `-f, --file <file>` | the data file, for a resource the directory does not name on its own
135
+ `-o, --output <format>` | `yaml` or `json` for `get` and `list`, `name` for `list`
136
+ `--from <file>` | the entry to set, `-` for standard input
137
+ `--force` | accept a change the schema marks immutable
138
+ `--offline` | read remote schemas from the cache only, never from the network, also `YAMLCTL_OFFLINE=1`
139
+ `--refresh` | fetch remote schemas again even when the cache holds a recent copy
140
+
141
+ 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.
142
+ A file holding several maps is listed whole by its own name and reached one map at a time by the map's name.
143
+
144
+ A **field** inside an object is a path, `risk_profile.business_impact`.
145
+ A list or an object is written as JSON, `account_links='[{"account": "123", "environment": "PRODUCTION"}]'`, and an empty value, `description=`, removes the field.
146
+
147
+ `get` prints the entry alone, so an entry is copied with:
148
+
149
+ ```bash
150
+ yamlctl project get checkout_api | yamlctl project set checkout_web --from -
151
+ ```
152
+
153
+ ## The schema
154
+
155
+ `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:
156
+
157
+ ```yaml
158
+ # yaml-language-server: $schema=schemas/project.schema.json
159
+ ```
160
+
161
+ Without that line, it looks for `schemas/<name>.schema.json`, then `<name>.schema.json`, beside the file.
162
+ Without any schema, it still edits the file, checks nothing, and says so.
163
+ A file naming a schema that cannot be loaded is read with a warning and never written, since checking nothing where the file asked for a check is worse than stopping.
164
+
165
+ Drafts 07, 2019-09 and 2020-12 are supported, and a schema can be split across files and addresses: every `$ref` is followed, relative to the document's `$id` when it has one.
166
+
167
+ A schema named by an `https://` address, the ones [SchemaStore](https://www.schemastore.org/) publishes for instance, is fetched along with every remote document its `$ref`s reach:
168
+
169
+ ```text
170
+ $ yamlctl -C .github/workflows check
171
+ .github/workflows/ci.yml: valid
172
+ .github/workflows/pkg.yml: valid
173
+ ```
174
+
175
+ - **Cached**: in `~/.cache/yamlctl`, or `$XDG_CACHE_HOME/yamlctl`, or `YAMLCTL_CACHE_DIR`, and used for a day before it is fetched again, so a pipeline running every few minutes does not download the same schema each time.
176
+ - **Resilient**: a fetch that fails falls back to the cached copy, whatever its age, with a warning.
177
+ - **Offline**: `--offline`, or `YAMLCTL_OFFLINE=1`, reads the cache only, for an air-gapped runner or a reproducible run.
178
+ - **Fresh on demand**: `--refresh` fetches again whatever the cache holds.
179
+
180
+ When an alternative fails, `oneOf` or `anyOf`, only the branch closest to the value is reported, so a job missing `runs-on` is not also told to add `uses`.
181
+
182
+ The maps of entries are found from the schema's shape: a top-level property whose values all follow one object schema, `additionalProperties: {"$ref": "#/definitions/project"}`.
183
+ Nothing has to be added to a schema for `yamlctl` to use it.
184
+
185
+ A few checks look at more than one entry, which JSON Schema cannot express: a reference to another entry, a condition on the entry it names, a field whose change has consequences.
186
+ Those are declared with `x-yamlctl` on the field, and [docs/schema-extensions.md](docs/schema-extensions.md) describes them.
187
+
188
+ ```json
189
+ "parent_project": {
190
+ "type": ["string", "null"],
191
+ "x-yamlctl": { "key-of": ".", "target-must": { "is_folder": true }, "immutable": "moving a project recreates it" }
192
+ }
193
+ ```
194
+
195
+ ## From a source system to a data file
196
+
197
+ A pipeline keeping a data file in step with another system runs four steps, typically on a schedule:
198
+
199
+ 1. Export the list from the source system, as JSON.
200
+ 2. Call `set` once per item, and `delete` for what the source no longer holds.
201
+ 3. Run `yamlctl check`, then whatever reads the file, `terraform plan` for instance.
202
+ 4. Open a merge request with the change, and apply once it is merged.
203
+
204
+ ```bash
205
+ # apps.json: [{"id": "1042", "name": "Checkout API", "account": "123456789012"}, ...]
206
+ jq -c '.[]' apps.json | while read -r app; do
207
+ yamlctl project set "app_$(jq -r .id <<< "$app")" \
208
+ name="$(jq -r .name <<< "$app")" \
209
+ parent_project=applications \
210
+ account_links="$(jq -c '[{account: .account, environment: "PRODUCTION"}]' <<< "$app")"
211
+ done
212
+ yamlctl check
213
+ ```
214
+
215
+ Three rules keep such a sync safe:
216
+
217
+ - **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 the sync only sets and deletes keys carrying it.
219
+ - **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.
220
+
221
+ ## License
222
+
223
+ [MIT](LICENSE)
package/bin/yamlctl.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "yamlctl",
3
+ "version": "0.1.0",
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
+ "keywords": [
6
+ "yaml",
7
+ "json-schema",
8
+ "cli",
9
+ "gitops",
10
+ "configuration",
11
+ "validation"
12
+ ],
13
+ "type": "module",
14
+ "license": "MIT",
15
+ "author": "Bertrand THOMAS",
16
+ "bin": {
17
+ "yamlctl": "bin/yamlctl.js"
18
+ },
19
+ "files": [
20
+ "bin",
21
+ "src",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "engines": {
26
+ "node": ">=20"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/devpro/yamlctl.git"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/devpro/yamlctl/issues"
34
+ },
35
+ "homepage": "https://github.com/devpro/yamlctl#readme",
36
+ "scripts": {
37
+ "test": "node --test test/*.test.js",
38
+ "smoke": "scripts/smoke_pack.sh"
39
+ },
40
+ "dependencies": {
41
+ "ajv": "8.20.0",
42
+ "yaml": "2.9.1"
43
+ }
44
+ }
package/src/cli.js ADDED
@@ -0,0 +1,388 @@
1
+ // yamlctl <resource> <verb> [key] [field=value...], and the few verbs that take no resource.
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.
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { parse, stringify } from 'yaml';
8
+ import { deleteEntry, setEntry, writeDocument } from './document.js';
9
+ import { explain } from './explain.js';
10
+ import { dataFiles, listResources, openFile, resolveResource } from './resources.js';
11
+ import { checkAll, checkSet, referencesTo } from './rules.js';
12
+ import { SCHEMA_LINE, typedValue } from './schema.js';
13
+ import { cacheDir, isRemote, prefetch } from './store.js';
14
+
15
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
16
+
17
+ export const HELP = `yamlctl reads and edits YAML data files entry by entry, every change checked against the file's JSON Schema.
18
+
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.
31
+ A field inside an object is a path, risk_profile.business_impact, and a list or an object is written as JSON.
32
+ An empty value, description=, removes the field.
33
+
34
+ The schema is the one the file names on its first line,
35
+ # yaml-language-server: $schema=schemas/project.schema.json
36
+ else schemas/<name>.schema.json, else <name>.schema.json beside the file.
37
+ A remote schema, and every remote $ref, is fetched and cached for a day in ${cacheDir()}.
38
+
39
+ 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
+
50
+ 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
55
+ `;
56
+
57
+ class UsageError extends Error {}
58
+
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.
60
+ export function parseArgs(argv) {
61
+ const options = { dir: '.', file: null, output: null, from: null, force: false, offline: false, refresh: false, help: false, version: false };
62
+ const words = [];
63
+ for (let i = 0; i < argv.length; i++) {
64
+ const arg = argv[i];
65
+ const value = () => {
66
+ if (i + 1 >= argv.length) throw new UsageError(`${arg} needs a value`);
67
+ return argv[++i];
68
+ };
69
+ if (arg === '-C' || arg === '--dir') options.dir = value();
70
+ else if (arg === '-f' || arg === '--file') options.file = value();
71
+ else if (arg === '-o' || arg === '--output') options.output = value();
72
+ else if (arg === '--from') options.from = value();
73
+ else if (arg === '--force') options.force = true;
74
+ else if (arg === '--offline') options.offline = true;
75
+ else if (arg === '--refresh') options.refresh = true;
76
+ else if (arg === '-h' || arg === '--help') options.help = true;
77
+ else if (arg === '-v' || arg === '--version') options.version = true;
78
+ else if (arg.startsWith('--') && arg.includes('=')) {
79
+ const [flag, ...rest] = arg.split('=');
80
+ argv.splice(i + 1, 0, rest.join('='));
81
+ argv[i] = flag;
82
+ i--;
83
+ } else if (arg.startsWith('-') && arg !== '-' && !arg.includes('=')) throw new UsageError(`unknown option ${arg}`);
84
+ else words.push(arg);
85
+ }
86
+ if (options.output && !['yaml', 'json', 'name'].includes(options.output)) throw new UsageError(`-o takes yaml, json or name, not ${options.output}`);
87
+ return { options, words };
88
+ }
89
+
90
+ // 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.
92
+ export async function main(argv, io = {}) {
93
+ const err = io.err ?? ((text) => process.stderr.write(text));
94
+ const cwd = io.cwd ?? process.cwd();
95
+ const env = io.env ?? process.env;
96
+ let parsed;
97
+ try {
98
+ parsed = parseArgs([...argv]);
99
+ } catch {
100
+ return run(argv, io);
101
+ }
102
+ const { options } = parsed;
103
+ const uris = schemaUris(options.file ? [resolve(cwd, options.file)] : safeDataFiles(resolve(cwd, options.dir)));
104
+ if (uris.length) {
105
+ await prefetch(uris, {
106
+ offline: options.offline || env.YAMLCTL_OFFLINE === '1',
107
+ refresh: options.refresh,
108
+ env,
109
+ warn: (text) => err(`warning: ${text}\n`),
110
+ fetchImpl: io.fetch ?? globalThis.fetch,
111
+ });
112
+ }
113
+ return run(argv, io);
114
+ }
115
+
116
+ function safeDataFiles(dir) {
117
+ try {
118
+ return dataFiles(dir);
119
+ } catch {
120
+ return [];
121
+ }
122
+ }
123
+
124
+ // The schema each file names, as the URI the store fetches or reads, a local one included since its own `$ref`s may lead onto the network.
125
+ function schemaUris(files) {
126
+ const uris = new Set();
127
+ for (const file of files) {
128
+ let text;
129
+ try {
130
+ text = readFileSync(file, 'utf8');
131
+ } catch {
132
+ continue;
133
+ }
134
+ const named = text.match(SCHEMA_LINE)?.[1];
135
+ if (!named) continue;
136
+ if (isRemote(named)) uris.add(named);
137
+ else if (!/^[a-z][a-z0-9+.-]*:/i.test(named)) {
138
+ const path = isAbsolute(named) ? named : join(dirname(file), named);
139
+ if (existsSync(path)) uris.add(pathToFileURL(path).href);
140
+ }
141
+ }
142
+ return [...uris];
143
+ }
144
+
145
+ // Everything a command prints goes through `out` and `err`, and the return value is the exit status, so a test runs a command without a child process.
146
+ export function run(argv, { out = (text) => process.stdout.write(text), err = (text) => process.stderr.write(text), stdin = () => readFileSync(0, 'utf8'), cwd = process.cwd() } = {}) {
147
+ try {
148
+ const { options, words } = parseArgs([...argv]);
149
+ if (options.version) {
150
+ out(`${VERSION}\n`);
151
+ return 0;
152
+ }
153
+ if (options.help || !words.length || words[0] === 'help') {
154
+ out(HELP);
155
+ return 0;
156
+ }
157
+ const dir = resolve(cwd, options.dir);
158
+ const file = options.file ? resolve(cwd, options.file) : null;
159
+ const context = { options, dir, file, out, err, stdin, cwd };
160
+
161
+ 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`);
164
+
165
+ const [name, verb, ...args] = words;
166
+ const target = resolveResource({ dir, name, file });
167
+ // 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`);
169
+ if (target.schemaError) err(`warning: ${display(target.file, cwd)} ${target.schemaError}, so nothing is checked\n`);
170
+ 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`);
173
+ return commands[verb]({ ...context, name, target, args });
174
+ } catch (e) {
175
+ err(`error: ${e instanceof Error ? e.message : String(e)}\n`);
176
+ if (e instanceof UsageError) err(`Run yamlctl --help for the usage.\n`);
177
+ return 1;
178
+ }
179
+ }
180
+
181
+ // A path relative to where the command runs, an address as it is.
182
+ const display = (path, cwd) => {
183
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) return path;
184
+ const rel = relative(cwd, path);
185
+ return rel.startsWith('..') ? path : rel || basename(path);
186
+ };
187
+
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(', ')}`);
193
+ }
194
+
195
+ function needKey(args, verb) {
196
+ if (!args[0]) throw new UsageError(`${verb} needs the key of an entry`);
197
+ return args[0];
198
+ }
199
+
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));
203
+ return 0;
204
+ }
205
+
206
+ function list({ target, options, out }) {
207
+ const maps = target.map ? [target.map] : target.maps;
208
+ const data = target.document.data;
209
+ 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 }));
212
+ return 0;
213
+ }
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`);
226
+ }
227
+ return 0;
228
+ }
229
+
230
+ function get({ target, name, args, options, out }) {
231
+ const map = needMap(target, name);
232
+ const key = needKey(args, 'get');
233
+ 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 }));
237
+ return 0;
238
+ }
239
+
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);
244
+ const { document, schema } = target;
245
+ 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`);
254
+ } 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
+ }
286
+ }
287
+
288
+ 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}`));
291
+ if (problems.length) {
292
+ for (const problem of problems) err(`${problem}\n`);
293
+ throw new Error(`${map}/${key} not written`);
294
+ }
295
+
296
+ if (exists && JSON.stringify(entries[key]) === JSON.stringify(entry)) {
297
+ out(`${map}/${key} unchanged\n`);
298
+ return 0;
299
+ }
300
+ setEntry(document, map, key, entry);
301
+ writeDocument(document);
302
+ out(`${map}/${key} ${exists ? 'updated' : 'created'}\n`);
303
+ return 0;
304
+ }
305
+
306
+ // 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
+ function parseLoose(text) {
308
+ try {
309
+ return parse(text);
310
+ } catch {
311
+ return text;
312
+ }
313
+ }
314
+
315
+ function remove({ target, name, args, out }) {
316
+ const map = needMap(target, name);
317
+ const key = needKey(args, 'delete');
318
+ 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;
322
+ }
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);
326
+ writeDocument(document);
327
+ out(`${map}/${key} deleted\n`);
328
+ return 0;
329
+ }
330
+
331
+ function explainCommand({ target, name, args, out }) {
332
+ const map = needMap(target, name);
333
+ if (!target.schema) throw new Error(`${basename(target.file)} has no schema to explain`);
334
+ out(explain(target.schema, map, args[0] ? args[0].split('.') : []));
335
+ return 0;
336
+ }
337
+
338
+ function problemsOf(opened) {
339
+ if (!opened.schema) return [];
340
+ const data = opened.document.data;
341
+ const problems = opened.schema.validate('#', data, basename(opened.file));
342
+ problems.push(...checkAll({ schema: opened.schema, data }).map((problem) => `${basename(opened.file)}: ${problem}`));
343
+ return problems;
344
+ }
345
+
346
+ function report(opened, { out, err, cwd }) {
347
+ const where = display(opened.file, cwd);
348
+ if (opened.schemaError) {
349
+ err(`${where} ${opened.schemaError}\n`);
350
+ return false;
351
+ }
352
+ if (!opened.schema) {
353
+ out(`${where}: no schema, not checked\n`);
354
+ return true;
355
+ }
356
+ const problems = problemsOf(opened);
357
+ for (const problem of problems) err(`${problem}\n`);
358
+ const entries = opened.maps.reduce((total, map) => total + Object.keys(opened.document.data[map] ?? {}).length, 0);
359
+ if (!problems.length) out(opened.maps.length ? `${where}: ${entries} ${entries === 1 ? 'entry' : 'entries'}, valid\n` : `${where}: valid\n`);
360
+ return !problems.length;
361
+ }
362
+
363
+ function checkResource(context) {
364
+ return report(context.target, context) ? 0 : 1;
365
+ }
366
+
367
+ function checkDirectory(context) {
368
+ let ok = true;
369
+ const files = context.file ? [context.file] : dataFiles(context.dir);
370
+ for (const path of files) {
371
+ let opened;
372
+ try {
373
+ opened = openFile(path);
374
+ } catch (e) {
375
+ context.err(`${display(path, context.cwd)}: ${e instanceof Error ? e.message : String(e)}\n`);
376
+ ok = false;
377
+ continue;
378
+ }
379
+ if (!report(opened, context)) ok = false;
380
+ }
381
+ return ok ? 0 : 1;
382
+ }
383
+
384
+ function table(header, rows, indent = '') {
385
+ const widths = header.map((title, i) => Math.max(title.length, ...rows.map((row) => String(row[i]).length)));
386
+ const line = (cells) => `${indent}${cells.map((cell, i) => (i === cells.length - 1 ? String(cell) : String(cell).padEnd(widths[i]))).join(' ')}`.trimEnd();
387
+ return `${[header, ...rows].map(line).join('\n')}\n`;
388
+ }