@rulecad/cad 0.7.68 → 0.7.69
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/CHANGELOG.md +17 -0
- package/bin/cad.mjs +28 -24
- package/lib/edit.mjs +53 -13
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,23 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
|
|
|
5
5
|
its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the screw by thread
|
|
6
6
|
and head, the parts it passes through and the part it ends in.
|
|
7
7
|
|
|
8
|
+
## 0.7.69: --dry-run never writes
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- `--dry-run` never writes. It was a flag every command accepted, and four that did not handle it wrote the file
|
|
13
|
+
anyway: `cad set <project>/<object>` (an object's variables), `cad add fasten --from-fits`, `cad frame --expand` and
|
|
14
|
+
`cad frame --size --write`. Each now runs every check and writes nothing on a dry run, saying what it would write;
|
|
15
|
+
with `--json` it answers `written: false, dryRun: true`. Any other command given `--dry-run` (`cad measured`,
|
|
16
|
+
`cad check`, `cad export` and the rest) refuses it by name and runs nothing, listing the commands that take one.
|
|
17
|
+
`setVariables(ref, changes, { dryRun })` and `fastenFromFitsEdit(ref, found, { dryRun })` in `lib/edit.mjs` take it
|
|
18
|
+
too, and `setVariables` now checks the edit before it writes, so a refused one never touches the file.
|
|
19
|
+
- `cad new <project>/<object>` takes `--dry-run` and `--json` as the other edits do. Before, a dry run made the
|
|
20
|
+
object's files anyway, and `--json` printed a line of words. Now a dry run writes nothing and says what it would make;
|
|
21
|
+
`--json` answers `{ command, file, written, dryRun, made, changes, findings }`; an object already there is refused
|
|
22
|
+
as `object.exists` and a bad name as `edit.name`. A project made for a new object is made as `cad new <project>`
|
|
23
|
+
makes one, with its `$schema`. A program can call it as `newObject(ref, { dryRun })` from `lib/edit.mjs`.
|
|
24
|
+
|
|
8
25
|
## 0.7.68: the actuator printed in place (#162)
|
|
9
26
|
|
|
10
27
|
### Added
|
package/bin/cad.mjs
CHANGED
|
@@ -20,7 +20,7 @@ import { schemaFindings } from '../lib/schema.mjs';
|
|
|
20
20
|
import { readJson } from '../lib/host.mjs';
|
|
21
21
|
import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
|
|
22
22
|
import { evaluate } from '../lib/rules.mjs';
|
|
23
|
-
import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue, parseSetting, newProject, setProject, newAssembly, setInAssembly, removeFromAssembly, moveInAssembly } from '../lib/edit.mjs';
|
|
23
|
+
import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue, parseSetting, newProject, setProject, newAssembly, newObject, setInAssembly, removeFromAssembly, moveInAssembly } from '../lib/edit.mjs';
|
|
24
24
|
import { setAt } from '../lib/jsonedit.mjs';
|
|
25
25
|
import { threemf, slotOf } from '../lib/threemf.mjs';
|
|
26
26
|
import { liveView } from '../lib/live.mjs';
|
|
@@ -57,7 +57,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
57
57
|
cad rules draft <name> --from <file.pdf> the figures in a datasheet's text, into rules/<name>.json for you to name and check (all kind estimate)
|
|
58
58
|
cad rules draft profile|slot|slot_nut <name> every field a beam's profile, a slot family or a slot nut has, to fill from its sheet
|
|
59
59
|
cad values <project>/<object> [names…] the object's variables, resolved [--json]
|
|
60
|
-
cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one]
|
|
60
|
+
cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one] [--dry-run]
|
|
61
61
|
cad set <project>/<assembly> <address>=<value> … change an assembly's fields: an entry's by its id or place (x1.at=[0,0,20],
|
|
62
62
|
joins.3.kind=bracket), or its own (title=…, frame.join.fitting=printed, frame.inside=[300,300,400]);
|
|
63
63
|
a value is JSON, a [list, of, names] or text
|
|
@@ -69,7 +69,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
69
69
|
cad remove <project>/<assembly> <id | list.n | id.field> take an entry or a field out; refused, naming them, while other
|
|
70
70
|
entries name it, unless --with-refs takes them out too
|
|
71
71
|
Every edit (new, set, add, move, remove): checked against the schema and what it could break before it is written,
|
|
72
|
-
refused by name with nothing written; --dry-run shows it without writing
|
|
72
|
+
refused by name with nothing written; --dry-run shows it without writing (also add fasten --from-fits, frame --expand and
|
|
73
|
+
frame --size --write; any other command refuses --dry-run); --json says what changed, and the checks
|
|
73
74
|
cad add fasten <project>/<assembly> --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2
|
|
74
75
|
a screwed joint (or --holes bracket.body for the part's own holes) [--nut [hex|square|lock]]
|
|
75
76
|
[--washer] [--length 12] [--torque 0.5] [--note …]
|
|
@@ -115,9 +116,9 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
115
116
|
cad kit <project>/<assembly> the folder to build it from without the model, in exports/: README.md (checks, what to buy and print, cut list, drilling, the build step by step), buy.csv, the plates' 3MFs, the jigs, each beam's sheet [--pictures] [--json]
|
|
116
117
|
cad list <project>/<assembly> what it takes to build: bought parts by set, the beams' cut list and bars to buy, every screw, nut and insert in packs, wire, printed parts in grams
|
|
117
118
|
cad frame <project>/<assembly> a generated frame ("frame": { "kind": "box", "inside": [..] }): its size, its beams by length, its joins and ends
|
|
118
|
-
--expand: written into the assembly as its beams, joins and end fittings, to edit by hand [--json]
|
|
119
|
+
--expand: written into the assembly as its beams, joins and end fittings, to edit by hand [--json] [--dry-run]
|
|
119
120
|
--size: any frame's beams, by group, each given the lightest profile from frame.size.profiles that meets
|
|
120
|
-
its limits, as a table naming the limit that set each; --write writes the profiles in [--json]
|
|
121
|
+
its limits, as a table naming the limit that set each; --write writes the profiles in [--json] [--dry-run]
|
|
121
122
|
cad beams <project>/<assembly> a cut-and-drill sheet for each mark of beam (beams that are the same share one), to scale, written to exports/ [--json]
|
|
122
123
|
--jigs: the jigs its beams take, as a plate in exports/ (a drill guide per distinct hole across a beam, a tap
|
|
123
124
|
guide per tapped end, a cut-length stop per length, a squaring corner per square join), each marked with its beam [--preview]
|
|
@@ -168,6 +169,10 @@ const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-s
|
|
|
168
169
|
'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
|
|
169
170
|
'kind', 'fitting', // cad add join
|
|
170
171
|
'title', 'description', 'printer', 'frame', 'inside', 'outside', 'join', 'feet', 'caps', 'with-refs', 'mass', 'joint']; // cad new, cad remove, cad add load
|
|
172
|
+
// The commands that take --dry-run (each checks its edit and writes nothing); any other is refused with it, as a flag
|
|
173
|
+
// it passed over would let the command write
|
|
174
|
+
const takesDryRun = (cmd) => ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) || (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
|
|
175
|
+
const DRY_RUNS = 'the commands that take one are cad new, set, add, remove, move, release, frame --expand and frame --size --write';
|
|
171
176
|
// What a command takes, where that isn't <project>/<object>
|
|
172
177
|
const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …, <project>/<assembly> <address>=<value> …, or <project> field=value …',
|
|
173
178
|
remove: '<project>/<assembly> <id | list.n | id.field> [--with-refs] [--dry-run]', move: '<project>/<assembly> <id> --at x,y,z | --to <address> [--rotate x,y,z] [--dry-run]',
|
|
@@ -427,23 +432,12 @@ async function main() {
|
|
|
427
432
|
const odd = args.find((a) => a.startsWith('--') && !OPTIONS.includes(a.slice(2)));
|
|
428
433
|
if (odd) { const guess = near(odd.slice(2), OPTIONS); throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`); }
|
|
429
434
|
if (configError) throw configError;
|
|
435
|
+
if (opt('dry-run') && !takesDryRun(cmd)) throw new Error(`cad ${cmd}${opt('size') ? ' --size' : ''} takes no --dry-run, so nothing is run: ${DRY_RUNS}`);
|
|
430
436
|
|
|
431
437
|
if (cmd === 'new' && (opt('assembly') || !String(ref || '').includes('/'))) return newCommand(ref ?? (typeof opt('assembly') === 'string' ? opt('assembly') : undefined));
|
|
432
|
-
if (cmd === 'new') {
|
|
433
|
-
const [project, name] = String(ref
|
|
434
|
-
|
|
435
|
-
const dir = paths.project(project), objects = path.join(dir, 'objects');
|
|
436
|
-
fs.mkdirSync(objects, { recursive: true });
|
|
437
|
-
const pj = path.join(dir, 'project.json');
|
|
438
|
-
const p = fs.existsSync(pj) ? JSON.parse(fs.readFileSync(pj, 'utf8')) : { name: project, description: '', material: 'PLA', objects: [] };
|
|
439
|
-
for (const ext of ['js', 'json']) {
|
|
440
|
-
const to = path.join(objects, `${name}.${ext}`);
|
|
441
|
-
if (fs.existsSync(to)) throw new Error(`${path.relative(WS, to)} already exists`);
|
|
442
|
-
fs.writeFileSync(to, fs.readFileSync(path.join(TOOL, 'templates', `object.${ext}`), 'utf8').replaceAll('NAME', name));
|
|
443
|
-
}
|
|
444
|
-
if (!p.objects.includes(name)) p.objects.push(name);
|
|
445
|
-
fs.writeFileSync(pj, JSON.stringify(p, null, 2) + '\n');
|
|
446
|
-
return console.log(`made projects/${project}/objects/${name}.{js,json}`);
|
|
438
|
+
if (cmd === 'new') { // an object, from the template; --dry-run and --json as the other edits
|
|
439
|
+
const r = newObject(ref, { dryRun: !!opt('dry-run') }), [project, name] = String(ref).split('/');
|
|
440
|
+
return edited(r, 'new', {}, `${r.dryRun ? 'would make' : 'made'} projects/${project}/objects/${name}.{js,json}`);
|
|
447
441
|
}
|
|
448
442
|
|
|
449
443
|
if (cmd === 'rules' && ['check', 'draw', 'draft'].includes(ref)) return ruleSheets(ref, pos.slice(2));
|
|
@@ -631,9 +625,9 @@ async function editVariables(ref) {
|
|
|
631
625
|
const extra = Object.fromEntries(['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]));
|
|
632
626
|
if (pairs.length > 1 && (extra.rule || extra.label)) throw new Error(`--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`);
|
|
633
627
|
const changes = Object.fromEntries(pairs.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }]; }));
|
|
634
|
-
const r = await setVariables(ref, changes, { create: !!opt('new') });
|
|
628
|
+
const r = await setVariables(ref, changes, { create: !!opt('new'), dryRun: !!opt('dry-run') });
|
|
635
629
|
if (opt('json')) return console.log(JSON.stringify(r));
|
|
636
|
-
console.log(`set ${r.changed.join(', ')} in ${
|
|
630
|
+
console.log(`${r.dryRun ? `dry run, nothing written: would set` : 'set'} ${r.changed.join(', ')} in ${rel(r.file)}`);
|
|
637
631
|
}
|
|
638
632
|
|
|
639
633
|
// cad add fit|joint|item|loop|pose|fasten|join <project>/<assembly> --key value …: add to an assembly, keeping its layout
|
|
@@ -654,9 +648,10 @@ async function editAssembly(what, ref) {
|
|
|
654
648
|
else if (what === 'loop') entry = text(['a', 'b', 'label']);
|
|
655
649
|
else if (what === 'fasten' && opt('from-fits')) { // a holes fit and a fit that fastens, put as one fasten
|
|
656
650
|
const s = await buildAssembly(ref), { fastenFromFits } = await import('../lib/fasten.mjs');
|
|
657
|
-
const r = fastenFromFitsEdit(ref, fastenFromFits(s), { screw: typeof opt('screw') === 'string' ? opt('screw') : undefined });
|
|
651
|
+
const r = fastenFromFitsEdit(ref, fastenFromFits(s), { screw: typeof opt('screw') === 'string' ? opt('screw') : undefined, dryRun: !!opt('dry-run') });
|
|
658
652
|
if (opt('json')) return console.log(JSON.stringify(r));
|
|
659
|
-
|
|
653
|
+
if (r.dryRun) console.log('dry run, nothing written:');
|
|
654
|
+
for (const x of r.added) console.log(`${r.dryRun ? 'would add' : 'added'} a fasten to ${rel(r.file)} in place of its holes fit and its fit that fastens: ${JSON.stringify(x)}`);
|
|
660
655
|
return console.log(`check its screws: cad check ${ref}`);
|
|
661
656
|
}
|
|
662
657
|
else if (what === 'fasten') { // --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2 | --holes bracket.body [--nut [hex] --washer --length 12 --torque 0.5 --note …]
|
|
@@ -1201,6 +1196,11 @@ async function frameCommand(ref) {
|
|
|
1201
1196
|
const rows = r.rows, out = { assembly: ref, ok: r.ok, total: r.total, drawn: r.drawn, tried: r.tried, search: r.search, groups: rows, limits: r.limits };
|
|
1202
1197
|
if (opt('write')) {
|
|
1203
1198
|
if (!r.ok) throw new Error(`${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`);
|
|
1199
|
+
if (opt('dry-run')) { // the sizing and the check above, nothing written
|
|
1200
|
+
if (opt('json')) return console.log(JSON.stringify({ ...out, file: rel(file), written: false, dryRun: true }, null, 2));
|
|
1201
|
+
console.log(sizingText(r).join('\n'));
|
|
1202
|
+
return console.log(`dry run, nothing written: would write ${rel(file)}`);
|
|
1203
|
+
}
|
|
1204
1204
|
fs.writeFileSync(file, `${JSON.stringify(writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r), null, 2)}\n`);
|
|
1205
1205
|
if (opt('json')) return console.log(JSON.stringify({ ...out, file: path.relative(WS, file) }, null, 2));
|
|
1206
1206
|
console.log(sizingText(r).join('\n'));
|
|
@@ -1211,6 +1211,10 @@ async function frameCommand(ref) {
|
|
|
1211
1211
|
}
|
|
1212
1212
|
if (raw.frame?.kind == null) throw new Error(`${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`);
|
|
1213
1213
|
const s = await buildAssembly(ref), m = s.generated, out = expandFrame(raw, s.num).a;
|
|
1214
|
+
if (opt('expand') && opt('dry-run')) {
|
|
1215
|
+
if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: rel(file), written: false, dryRun: true, frame: m, expanded: out }, null, 2));
|
|
1216
|
+
return console.log(`dry run, nothing written: would write ${rel(file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings`);
|
|
1217
|
+
}
|
|
1214
1218
|
if (opt('expand')) {
|
|
1215
1219
|
fs.writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`);
|
|
1216
1220
|
if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
|
package/lib/edit.mjs
CHANGED
|
@@ -16,21 +16,22 @@ import { plasticNamed } from './fittings.mjs';
|
|
|
16
16
|
// A value from the command line: a number if it is one, otherwise an expression (or a name) as text
|
|
17
17
|
export const parseValue = (s) => (s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s));
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
// The edited text, parsed and held to its schema: refused by name, nothing written
|
|
20
|
+
function checked(file, text, kind) {
|
|
20
21
|
let json;
|
|
21
22
|
try { json = JSON.parse(text); } catch (e) { throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file }); }
|
|
22
23
|
const problems = validate(json, schema(kind));
|
|
23
24
|
if (problems.length) throw new CadError('schema', `${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
|
|
24
|
-
fs.writeFileSync(file, text);
|
|
25
25
|
return json;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
29
|
* Set variables of an object: { name: value }, each with optional unit, rule, label; new ones only with create.
|
|
30
30
|
* @param {string} ref project/object @param {Record<string, { value?: any, unit?: string, rule?: string, label?: string }>} changes
|
|
31
|
-
*
|
|
31
|
+
* Every check runs before anything is written; dryRun runs them all and writes nothing.
|
|
32
|
+
* @param {{ create?: boolean, dryRun?: boolean }} [options] @returns {Promise<{ file: string, changed: string[], written: boolean, dryRun?: true }>}
|
|
32
33
|
*/
|
|
33
|
-
export async function setVariables(ref, changes, { create = false } = {}) {
|
|
34
|
+
export async function setVariables(ref, changes, { create = false, dryRun = false } = {}) {
|
|
34
35
|
const d = locate(ref), before = fs.readFileSync(d.json, 'utf8');
|
|
35
36
|
let text = before;
|
|
36
37
|
for (const [name, c] of Object.entries(changes)) {
|
|
@@ -40,8 +41,8 @@ export async function setVariables(ref, changes, { create = false } = {}) {
|
|
|
40
41
|
if (!exists) { text = setAt(text, ['variables', name], { value: c.value, ...(c.unit !== undefined ? { unit: c.unit } : {}), rule: c.rule, ...(c.label ? { label: c.label } : {}) }); continue; }
|
|
41
42
|
for (const k of ['value', 'unit', 'rule', 'label']) if (c[k] !== undefined) text = setAt(text, ['variables', name, k], c[k]);
|
|
42
43
|
}
|
|
43
|
-
const json =
|
|
44
|
-
try { // the variables must still resolve: an unknown name or a loop
|
|
44
|
+
const json = checked(d.json, text, 'object');
|
|
45
|
+
try { // the variables must still resolve: an unknown name or a loop is refused (the edit changes no uses, so the sets are the file's own)
|
|
45
46
|
const { values } = resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
|
|
46
47
|
// and each changed value must lie within the variable's own range, where it has one (a tweak's min and max)
|
|
47
48
|
for (const name of Object.keys(changes)) {
|
|
@@ -50,8 +51,10 @@ export async function setVariables(ref, changes, { create = false } = {}) {
|
|
|
50
51
|
const lo = typeof t.min === 'number' ? t.min : -Infinity, hi = typeof t.max === 'number' ? t.max : Infinity;
|
|
51
52
|
if (v < lo || v > hi) throw new CadError('edit.range', `${name} = ${v} is outside its range, ${t.min ?? '…'} to ${t.max ?? '…'} (change the range first if it should go there)`, { file: d.json, path: `variables.${name}` });
|
|
52
53
|
}
|
|
53
|
-
} catch (e) {
|
|
54
|
-
|
|
54
|
+
} catch (e) { throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` }); }
|
|
55
|
+
const written = !dryRun && text !== before;
|
|
56
|
+
if (written) fs.writeFileSync(d.json, text);
|
|
57
|
+
return { file: d.json, changed: Object.keys(changes), written, ...(dryRun ? { dryRun: true } : {}) };
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
const assemblyFile = (ref) => {
|
|
@@ -92,10 +95,11 @@ export function addToAssembly(ref, what, entry, { dryRun = false } = {}) {
|
|
|
92
95
|
* Put a fasten in place of each holes fit and the fit that fastens the same two items (as lib/fasten.mjs's fastenFromFits
|
|
93
96
|
* finds them): the holes fit goes, the fit that fastens goes too, or keeps its gap range (min, max) with "fastens",
|
|
94
97
|
* "fastener" and "count" taken off, and the fasten is added. A screw given replaces the one found.
|
|
95
|
-
*
|
|
96
|
-
* @
|
|
98
|
+
* dryRun checks it all and writes nothing.
|
|
99
|
+
* @param {string} ref project/assembly @param {{ fasten: object, holes: number, fastens: number }[]} found @param {{ screw?: string, dryRun?: boolean }} [options]
|
|
100
|
+
* @returns {{ file: string, added: object[], written: boolean, dryRun?: true }}
|
|
97
101
|
*/
|
|
98
|
-
export function fastenFromFitsEdit(ref, found, { screw } = {}) {
|
|
102
|
+
export function fastenFromFitsEdit(ref, found, { screw, dryRun = false } = {}) {
|
|
99
103
|
const file = assemblyFile(ref);
|
|
100
104
|
if (!found.length) throw new CadError('edit.nothing', `${ref} has no holes fit with a fit that fastens the same two items (and no fasten for them yet): nothing to put a fasten in place of`, { file });
|
|
101
105
|
let text = fs.readFileSync(file, 'utf8');
|
|
@@ -109,8 +113,9 @@ export function fastenFromFitsEdit(ref, found, { screw } = {}) {
|
|
|
109
113
|
if (getAt(text, ['fasten']) === undefined) text = setAt(text, ['fasten'], []);
|
|
110
114
|
const added = found.map((g) => ({ ...g.fasten, ...(screw ? { screw } : {}) }));
|
|
111
115
|
for (const x of added) text = appendAt(text, ['fasten'], x);
|
|
112
|
-
|
|
113
|
-
|
|
116
|
+
checked(file, text, 'assembly');
|
|
117
|
+
if (!dryRun) fs.writeFileSync(file, text);
|
|
118
|
+
return { file, added, written: !dryRun, ...(dryRun ? { dryRun: true } : {}) };
|
|
114
119
|
}
|
|
115
120
|
|
|
116
121
|
// ---------- the workspace's own files: projects and assemblies, made, changed, moved and removed ----------
|
|
@@ -552,6 +557,41 @@ export function setProject(project, changes, { dryRun = false } = {}) {
|
|
|
552
557
|
return finish({ file, before, text, kind: 'project', changes: done, dryRun, findings: projectFindings(JSON.parse(text), project) });
|
|
553
558
|
}
|
|
554
559
|
|
|
560
|
+
/**
|
|
561
|
+
* Make an object from the kit's template: projects/<project>/objects/<name>.js and .json, listed in its project's
|
|
562
|
+
* objects; its project is made first where there is none (PLA, as cad new <project> makes one). With dryRun it writes
|
|
563
|
+
* nothing and says what it would make, in the shape the other edits answer in. Refused by name: a name not in lower
|
|
564
|
+
* case with dashes, an object already there.
|
|
565
|
+
* @param {string} ref project/object @param {{ dryRun?: boolean }} [options]
|
|
566
|
+
*/
|
|
567
|
+
export function newObject(ref, { dryRun = false } = {}) {
|
|
568
|
+
const [project, name] = String(ref || '').split('/');
|
|
569
|
+
if (!NAME.test(project || '') || !NAME.test(name || '')) throw new CadError('edit.name', `an object is <project>/<name>, each lower case with dashes (got ${JSON.stringify(ref)})`);
|
|
570
|
+
const objects = path.join(paths.project(project), 'objects'), pj = projectFile(project);
|
|
571
|
+
const files = ['js', 'json'].map((ext) => path.join(objects, `${name}.${ext}`));
|
|
572
|
+
const there = files.find((f) => fs.existsSync(f));
|
|
573
|
+
if (there) throw new CadError('object.exists', `projects/${project}/objects/${path.basename(there)} is already there: change its variables with cad set ${ref} name=value`, { file: there });
|
|
574
|
+
const texts = ['js', 'json'].map((ext) => fs.readFileSync(new URL(`../templates/object.${ext}`, import.meta.url), 'utf8').replaceAll('NAME', name));
|
|
575
|
+
const object = JSON.parse(texts[1]);
|
|
576
|
+
const problems = validate(object, schema('object'));
|
|
577
|
+
if (problems.length) throw new CadError('schema', `not made: ${name}.json: ${problems[0].path}: ${problems[0].message}`, { file: files[1], path: problems[0].path });
|
|
578
|
+
// its project: made where there is none, else the object added to its list (keeping the file's layout)
|
|
579
|
+
const made = fs.existsSync(pj) ? null : newProject(project, { dryRun: true });
|
|
580
|
+
const before = made ? '' : fs.readFileSync(pj, 'utf8');
|
|
581
|
+
let text = made ? laidOut(made.changes[0].after) : before, listed = [];
|
|
582
|
+
const own = JSON.parse(text);
|
|
583
|
+
if (!Array.isArray(own.objects)) { text = setAt(text, ['objects'], [name]); listed = [{ op: 'add', path: 'objects.0', after: name }]; }
|
|
584
|
+
else if (!own.objects.includes(name)) { text = appendAt(text, ['objects'], name); listed = [{ op: 'add', path: `objects.${own.objects.length}`, after: name }]; }
|
|
585
|
+
const changes = [...(made ? made.changes : []), ...files.map((f, i) => ({ op: 'make', path: `projects/${project}/objects/${path.basename(f)}`, ...(i === 1 ? { after: object } : {}) })), ...listed];
|
|
586
|
+
const findings = [...(made ? made.findings.filter((f) => f.code !== 'schema') : []), { level: 'pass', text: 'matches the object schema', code: 'schema' }];
|
|
587
|
+
if (!dryRun) {
|
|
588
|
+
fs.mkdirSync(objects, { recursive: true });
|
|
589
|
+
files.forEach((f, i) => fs.writeFileSync(f, texts[i]));
|
|
590
|
+
if (text !== before) fs.writeFileSync(pj, text);
|
|
591
|
+
}
|
|
592
|
+
return { file: files[1], written: !dryRun, ...(dryRun ? { dryRun: true } : {}), made: [...(made ? [pj] : []), ...files], changes, findings };
|
|
593
|
+
}
|
|
594
|
+
|
|
555
595
|
/**
|
|
556
596
|
* Make an assembly: projects/<project>/assemblies/<name>.json, empty (items: []) or a generated frame, checked as it
|
|
557
597
|
* is made; its project is made first where there is none, with the material and printer given for it (checked as cad new
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.69",
|
|
4
4
|
"description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|