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 +21 -0
- package/README.md +223 -0
- package/bin/yamlctl.js +4 -0
- package/package.json +44 -0
- package/src/cli.js +388 -0
- package/src/document.js +43 -0
- package/src/explain.js +61 -0
- package/src/resources.js +107 -0
- package/src/rules.js +102 -0
- package/src/schema.js +364 -0
- package/src/store.js +173 -0
package/src/document.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { parseDocument } from 'yaml';
|
|
4
|
+
|
|
5
|
+
export function readDocument(file) {
|
|
6
|
+
let text;
|
|
7
|
+
try {
|
|
8
|
+
text = readFileSync(file, 'utf8');
|
|
9
|
+
} catch (e) {
|
|
10
|
+
throw new Error(`cannot read ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
11
|
+
}
|
|
12
|
+
const doc = parseDocument(text);
|
|
13
|
+
if (doc.errors.length) throw new Error(`${file} is not valid YAML: ${doc.errors[0].message}`);
|
|
14
|
+
const data = doc.toJS() ?? {};
|
|
15
|
+
if (typeof data !== 'object' || Array.isArray(data)) throw new Error(`${file} does not hold a mapping at its top level`);
|
|
16
|
+
return { file, text, doc, data };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// A string a new value holds is double quoted, because unquoted YAML reads `no` as a boolean and `0123` as a number, and a value written by a tool has to read back as the same value.
|
|
20
|
+
// No line is folded, since folding a long description would change lines nobody edited.
|
|
21
|
+
export function render(doc) {
|
|
22
|
+
return doc.toString({ lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE', defaultKeyType: 'PLAIN' });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Written only when something changed, so running the same command twice leaves the file, and its modification time, alone.
|
|
26
|
+
export function writeDocument(document) {
|
|
27
|
+
const next = render(document.doc);
|
|
28
|
+
if (next === document.text) return false;
|
|
29
|
+
writeFileSync(document.file, next);
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function setEntry(document, map, key, entry) {
|
|
34
|
+
// 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
|
+
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));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function deleteEntry(document, map, key) {
|
|
42
|
+
document.doc.deleteIn([map, key]);
|
|
43
|
+
}
|
package/src/explain.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
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.
|
|
3
|
+
import { EXTENSION, escapeKey, types } from './schema.js';
|
|
4
|
+
|
|
5
|
+
export function explain(schema, map, segments) {
|
|
6
|
+
const base = schema.entryPointer(map);
|
|
7
|
+
const here = segments.length ? schema.field(base, segments, { throughLists: true }) : schema.unwrap(base);
|
|
8
|
+
if (!here) throw new Error(`${map} has no field ${segments.join('.')}`);
|
|
9
|
+
const { schema: node, pointer } = here;
|
|
10
|
+
const lines = [];
|
|
11
|
+
|
|
12
|
+
lines.push(`${segments.length ? `FIELD: ${segments.join('.')}` : `RESOURCE: ${map}`} <${describeType(schema, pointer, node)}>`);
|
|
13
|
+
if (node.description) lines.push('', 'DESCRIPTION:', ...node.description.split('\n').map((line) => ` ${line}`));
|
|
14
|
+
const values = node.enum ?? node.items?.enum;
|
|
15
|
+
if (values) lines.push('', 'VALUES:', ` ${values.filter((v) => v !== null).map((v) => JSON.stringify(v)).join(', ')}`);
|
|
16
|
+
if (node.default !== undefined) lines.push('', `DEFAULT: ${JSON.stringify(node.default)}`);
|
|
17
|
+
const rules = node[EXTENSION];
|
|
18
|
+
if (rules && typeof rules === 'object') lines.push('', 'RULES:', ...Object.entries(rules).map(([name, value]) => ` ${name}: ${typeof value === 'string' ? value : JSON.stringify(value)}`));
|
|
19
|
+
|
|
20
|
+
const fields = fieldsOf(schema, pointer, node);
|
|
21
|
+
if (fields.length) {
|
|
22
|
+
const required = new Set(fieldsParent(schema, pointer, node).required ?? []);
|
|
23
|
+
const rows = fields.map(([name, childPointer]) => {
|
|
24
|
+
const { schema: child, pointer: resolved } = schema.unwrap(childPointer);
|
|
25
|
+
return [name, `<${describeType(schema, resolved, child)}>${required.has(name) ? ' required' : ''}`, (child.description ?? '').split('\n')[0]];
|
|
26
|
+
});
|
|
27
|
+
const nameWidth = Math.max(...rows.map(([name]) => name.length));
|
|
28
|
+
const typeWidth = Math.max(...rows.map(([, type]) => type.length));
|
|
29
|
+
lines.push('', 'FIELDS:');
|
|
30
|
+
for (const [name, type, summary] of rows) lines.push(` ${name.padEnd(nameWidth)} ${summary ? `${type.padEnd(typeWidth)} ${summary}` : type}`);
|
|
31
|
+
}
|
|
32
|
+
return `${lines.join('\n')}\n`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The object whose properties are listed: the node itself, or the items of a list of objects.
|
|
36
|
+
function fieldsParent(schema, pointer, node) {
|
|
37
|
+
if (node.properties) return node;
|
|
38
|
+
if (node.items) return schema.unwrap(`${pointer}/items`).schema;
|
|
39
|
+
return node;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function fieldsOf(schema, pointer, node) {
|
|
43
|
+
if (node.properties) return Object.keys(node.properties).map((name) => [name, `${pointer}/properties/${escapeKey(name)}`]);
|
|
44
|
+
if (node.items) {
|
|
45
|
+
const items = schema.unwrap(`${pointer}/items`);
|
|
46
|
+
if (items.schema.properties) return Object.keys(items.schema.properties).map((name) => [name, `${items.pointer}/properties/${escapeKey(name)}`]);
|
|
47
|
+
}
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function describeType(schema, pointer, node) {
|
|
52
|
+
const kinds = types(node).filter((type) => type !== 'null');
|
|
53
|
+
if (kinds.includes('array') && node.items) {
|
|
54
|
+
const items = schema.unwrap(`${pointer}/items`).schema;
|
|
55
|
+
if (items.properties) return '[]object';
|
|
56
|
+
if (items.enum) return '[]enum';
|
|
57
|
+
return `[]${types(items).filter((type) => type !== 'null')[0] ?? 'any'}`;
|
|
58
|
+
}
|
|
59
|
+
if (node.enum) return 'enum';
|
|
60
|
+
return kinds.join('|') || 'any';
|
|
61
|
+
}
|
package/src/resources.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// What a resource name on the command line points at: a file and the map of entries inside it.
|
|
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.
|
|
4
|
+
import { existsSync, readdirSync, statSync } from 'node:fs';
|
|
5
|
+
import { basename, join } from 'node:path';
|
|
6
|
+
import { readDocument } from './document.js';
|
|
7
|
+
import { Schema, displayUri, findSchema } from './schema.js';
|
|
8
|
+
import { documentAt, hasDocument } from './store.js';
|
|
9
|
+
|
|
10
|
+
export const YAML = /\.ya?ml$/;
|
|
11
|
+
|
|
12
|
+
// One data file with its schema, if it has one, and the maps of entries it holds.
|
|
13
|
+
// `schemaError` is set when the file names a schema that cannot be loaded, which a command reading the file warns about and a command writing it refuses on.
|
|
14
|
+
export function openFile(file) {
|
|
15
|
+
const document = readDocument(file);
|
|
16
|
+
const found = findSchema(file, document.text);
|
|
17
|
+
let schema = null;
|
|
18
|
+
let schemaError = null;
|
|
19
|
+
if (found.unsupported) {
|
|
20
|
+
schemaError = `names ${found.uri}, and only file and http(s) schemas are read`;
|
|
21
|
+
} else if (found.uri && (hasDocument(found.uri) || !found.uri.startsWith('file:'))) {
|
|
22
|
+
try {
|
|
23
|
+
schema = new Schema(documentAt(found.uri), found.uri);
|
|
24
|
+
} catch (e) {
|
|
25
|
+
schemaError = `names a schema that cannot be used: ${e instanceof Error ? e.message : String(e)}`;
|
|
26
|
+
}
|
|
27
|
+
} else if (found.named) {
|
|
28
|
+
schemaError = `names ${displayUri(found.uri)}, which does not exist`;
|
|
29
|
+
}
|
|
30
|
+
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 };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Without a schema, a map of entries is a mapping whose every value is itself a mapping, or empty: `servers: {web: {...}, db: {...}}`.
|
|
35
|
+
// Defaults beside it, `servers_defaults: {port: 80}`, hold a scalar and are left out by the same rule.
|
|
36
|
+
function mapsWithoutSchema(data) {
|
|
37
|
+
return Object.keys(data).filter((key) => {
|
|
38
|
+
const value = data[key];
|
|
39
|
+
if (value === null) return false;
|
|
40
|
+
if (typeof value !== 'object' || Array.isArray(value)) return false;
|
|
41
|
+
return Object.values(value).every((entry) => entry === null || (typeof entry === 'object' && !Array.isArray(entry)));
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function dataFiles(dir) {
|
|
46
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new Error(`${dir} is not a directory`);
|
|
47
|
+
return readdirSync(dir)
|
|
48
|
+
.filter((name) => YAML.test(name))
|
|
49
|
+
.sort()
|
|
50
|
+
.map((name) => join(dir, name));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const stem = (file) => basename(file).replace(YAML, '');
|
|
54
|
+
|
|
55
|
+
// 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
|
+
export function resolveResource({ dir, name, file = null }) {
|
|
58
|
+
if (file) {
|
|
59
|
+
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 };
|
|
62
|
+
throw new Error(`${file} holds no map ${name}, only ${opened.maps.join(', ') || 'none'}`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
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
|
+
const holding = [];
|
|
71
|
+
for (const path of files) {
|
|
72
|
+
const opened = openFile(path);
|
|
73
|
+
if (opened.maps.includes(name)) holding.push({ ...opened, map: name });
|
|
74
|
+
}
|
|
75
|
+
if (holding.length === 1) return holding[0];
|
|
76
|
+
if (holding.length > 1) throw new Error(`${holding.map((h) => basename(h.file)).join(' and ')} both hold a map ${name}, name one with -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 };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Every name the command line accepts, the way `kubectl api-resources` lists them.
|
|
86
|
+
export function listResources(dir) {
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const path of dataFiles(dir)) {
|
|
89
|
+
let opened;
|
|
90
|
+
try {
|
|
91
|
+
opened = openFile(path);
|
|
92
|
+
} catch (e) {
|
|
93
|
+
out.push({ name: stem(path), file: path, map: null, entries: null, schema: null, error: e instanceof Error ? e.message : String(e) });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
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 });
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const count = (opened, map) => Object.keys(opened.document.data[map] ?? {}).length;
|
package/src/rules.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// The checks JSON Schema cannot express because they look at more than one entry, each declared on a field with `x-yamlctl`:
|
|
2
|
+
//
|
|
3
|
+
// key-of the value names an entry of a map in the same file, "." for the map the field belongs to
|
|
4
|
+
// target-must the entry it names has these values, read with that map's defaults applied
|
|
5
|
+
// immutable changing the value on an existing entry needs --force, and the text says why
|
|
6
|
+
//
|
|
7
|
+
// A map declares `x-yamlctl.defaults`, the sibling property its entries inherit from, which is where a field left out of an entry is read from.
|
|
8
|
+
// docs/schema-extensions.md is the reference for all of them.
|
|
9
|
+
import { EXTENSION } from './schema.js';
|
|
10
|
+
|
|
11
|
+
// The fields of one entry that carry rules, top level only, since a reference between entries is a property of the entry rather than of something nested in it.
|
|
12
|
+
export function fieldRules(schema, map) {
|
|
13
|
+
const { schema: entry } = schema.unwrap(schema.entryPointer(map));
|
|
14
|
+
const rules = [];
|
|
15
|
+
for (const [field, property] of Object.entries(entry?.properties ?? {})) {
|
|
16
|
+
const declared = property?.[EXTENSION];
|
|
17
|
+
if (declared && typeof declared === 'object') rules.push({ field, ...declared });
|
|
18
|
+
}
|
|
19
|
+
return rules;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function defaultsOf(schema, data, map) {
|
|
23
|
+
const sibling = schema?.mapOptions(map).defaults;
|
|
24
|
+
const value = sibling ? data[sibling] : null;
|
|
25
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const effective = (entry, defaults, field) => (entry?.[field] !== undefined && entry?.[field] !== null ? entry[field] : (defaults[field] ?? null));
|
|
29
|
+
|
|
30
|
+
const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
31
|
+
|
|
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 }) {
|
|
34
|
+
if (!schema) return [];
|
|
35
|
+
const problems = [];
|
|
36
|
+
const defaults = defaultsOf(schema, data, map);
|
|
37
|
+
for (const rule of fieldRules(schema, map)) {
|
|
38
|
+
const value = effective(entry, defaults, rule.field);
|
|
39
|
+
|
|
40
|
+
if (rule['key-of'] && value !== null) {
|
|
41
|
+
const targetMap = rule['key-of'] === '.' ? map : rule['key-of'];
|
|
42
|
+
const targets = data[targetMap] ?? {};
|
|
43
|
+
const names = Array.isArray(value) ? value : [value];
|
|
44
|
+
for (const name of names) {
|
|
45
|
+
if (targetMap === map && name === key) {
|
|
46
|
+
problems.push(`${rule.field}: ${key} cannot name itself`);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (!Object.hasOwn(targets, name)) {
|
|
50
|
+
problems.push(`${rule.field}: ${name} is not an entry of ${targetMap}, set it first`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const targetDefaults = defaultsOf(schema, data, targetMap);
|
|
54
|
+
for (const [field, expected] of Object.entries(rule['target-must'] ?? {})) {
|
|
55
|
+
const actual = effective(targets[name], targetDefaults, field);
|
|
56
|
+
if (!same(actual, expected)) problems.push(`${rule.field}: ${name} must have ${field}: ${JSON.stringify(expected)}, it has ${JSON.stringify(actual)}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (rule.immutable && Object.hasOwn(data[map] ?? {}, key) && !force) {
|
|
62
|
+
const before = effective(data[map][key], defaults, rule.field);
|
|
63
|
+
if (!same(before, value)) {
|
|
64
|
+
const reason = typeof rule.immutable === 'string' ? `, ${rule.immutable}` : '';
|
|
65
|
+
problems.push(`${rule.field}: changing ${JSON.stringify(before)} to ${JSON.stringify(value)} needs --force${reason}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return problems;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// The entries still naming one about to be deleted, since deleting it would leave each of them pointing at nothing.
|
|
73
|
+
export function referencesTo({ schema, data, map, key }) {
|
|
74
|
+
if (!schema) return [];
|
|
75
|
+
const found = [];
|
|
76
|
+
for (const other of schema.entryMaps()) {
|
|
77
|
+
const defaults = defaultsOf(schema, data, other);
|
|
78
|
+
for (const rule of fieldRules(schema, other)) {
|
|
79
|
+
if (!rule['key-of']) continue;
|
|
80
|
+
const targetMap = rule['key-of'] === '.' ? other : rule['key-of'];
|
|
81
|
+
if (targetMap !== map) continue;
|
|
82
|
+
for (const [name, entry] of Object.entries(data[other] ?? {})) {
|
|
83
|
+
if (other === map && name === key) continue;
|
|
84
|
+
const value = effective(entry, defaults, rule.field);
|
|
85
|
+
if ((Array.isArray(value) ? value : [value]).includes(key)) found.push(`${other}/${name}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return found;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Every entry of a file against the rules, for `check`, which reads a file someone may have edited by hand.
|
|
93
|
+
export function checkAll({ schema, data }) {
|
|
94
|
+
if (!schema) return [];
|
|
95
|
+
const problems = [];
|
|
96
|
+
for (const map of schema.entryMaps()) {
|
|
97
|
+
for (const [key, entry] of Object.entries(data[map] ?? {})) {
|
|
98
|
+
for (const problem of checkSet({ schema, data, map, key, entry, force: true })) problems.push(`${map}/${key}: ${problem}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return problems;
|
|
102
|
+
}
|