-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtb-registry.mjs
More file actions
703 lines (660 loc) · 30.5 KB
/
Copy pathtb-registry.mjs
File metadata and controls
703 lines (660 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// What a harness run leaves in the user's registry, and putting it back.
//
// Every IDE a harness starts writes to the same HKCU keys as the user's own
// IDE. It records each project it opens under
// `VB and VBA Program Settings\twinBASIC_IDE\ProjectState` (open tabs, watch
// expressions, DEBUG CONSOLE history) and puts it at the top of
// `...\RecentlyOpened`. Measured on 2026-09-23, before this module existed,
// 318 of 424 ProjectState values were harness temp projects, and all 21 slots
// of the recent list were: the user's own recent projects had been pushed out
// of the IDE entirely. An IDE started from an install the association does not
// point at also re-points `.twinproj` at itself, which matters once a harness
// runs private copies of the IDE (WIP.HelpAddin.md, Stage 1 item 2).
//
// The rule is: leave everything as it was found.
//
// * A project the run opened that had no entry before loses the entry. One
// that had an entry -- tbbuild pointed at the user's own project -- gets
// its old state back, and its old place in the recent list. Deleting
// that one would throw away somebody's open tabs and watches.
// * Everything under a folder the harness owns (its own temp work folders)
// is deleted by prefix, which also catches what an earlier run left when
// it died before tidying.
// * The recent list keeps no more copies of a path than it had, and gets
// back the entries that fell off its end while the run's projects were on
// it (restoreProjects says how the IDE does both).
// * The association keys are put back value by value, and only where they
// differ, so an untouched key is never written --- unless they named the
// temp folder when the run began, because then they were another run's
// IDE copy's, and putting them back would point at a deleted folder.
// * The build target the IDE remembers for each project path is deleted for
// every path under those folders, before the run and after it
// (sweepArchitectureMemory says why), and a named project's is put back
// as it was, since a run can switch the target of the project it opens
// (restoreArchitectureMemory).
//
// ONE PROCESS OWNS THIS PER RUN. check_examples starts many tbbuild processes
// at once; each snapshotting and restoring on its own would put back whichever
// state it happened to see, in whichever order the lanes finished. The first
// process to call startTidy sets TB_REGISTRY_OWNER, the children inherit it and
// leave the registry alone, and the owner sweeps once at the end.
//
// The work is done by .NET's registry API through PowerShell, and not by
// reg.exe. reg.exe prints value names in the console code page when its output
// is piped, so a path with a character outside that code page -- an accented
// user name in %TEMP% is enough -- comes back mangled, and a value cannot be
// deleted by a name that no longer matches it. The request goes in on stdin as
// UTF-8 JSON, because a project's saved state can reach 34 KB and an
// environment variable stops at 32 K characters; the answer comes back on
// stdout the same way. Like tb-launch.ps1, it is passed with -EncodedCommand
// rather than run as a file, so no execution policy is involved.
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import path from "node:path";
export const IDE_SETTINGS_KEY = "Software\\VB and VBA Program Settings\\twinBASIC_IDE";
export const ASSOCIATION_KEYS = [
"Software\\Classes\\.twinproj",
"Software\\Classes\\twinBASIC.ProjectFile",
];
// No `${` and no backtick anywhere in this script: it is a JavaScript template
// literal, and either one would end or splice it. A registry path separator is
// $SEP rather than a backslash typed into a path for the same reason: String.raw
// keeps backslashes, but a separator spelled once is harder to get wrong.
//
// Progress is silenced because with its streams redirected PowerShell writes
// progress records to stderr as CLIXML ("Preparing modules for first use"), and
// a failure is answered as {"error": ...} on stdout for the same reason: an
// error on stderr arrives wrapped in that XML, and its first line reads
// "#< CLIXML" rather than anything a person can act on.
const SCRIPT = String.raw`
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$utf8 = New-Object System.Text.UTF8Encoding $false
[Console]::InputEncoding = $utf8
[Console]::OutputEncoding = $utf8
$hk = [Microsoft.Win32.Registry]::CurrentUser
$SEP = [string][char]92
$String = [Microsoft.Win32.RegistryValueKind]::String
function Norm([string]$p) { return $p.Replace('/', $SEP).ToLowerInvariant() }
function Slots($k) {
return @($k.GetValueNames() | Where-Object { $_ -match '^\d+$' } | Sort-Object { [int]$_ })
}
function Lists([string]$root) {
$out = [ordered]@{ projectState = @(); recentlyOpened = @() }
$k = $hk.OpenSubKey($root + $SEP + 'ProjectState')
if ($k) { $out.projectState = @($k.GetValueNames() | Sort-Object); $k.Close() }
$k = $hk.OpenSubKey($root + $SEP + 'RecentlyOpened')
if ($k) {
$out.recentlyOpened = @(@(Slots $k) | ForEach-Object { [string]$k.GetValue($_) })
$k.Close()
}
return $out
}
function SnapProjects([string]$root, $paths) {
$entries = @()
$ps = $hk.OpenSubKey($root + $SEP + 'ProjectState')
$ro = $hk.OpenSubKey($root + $SEP + 'RecentlyOpened')
$recent = @()
if ($ro) { $recent = @(@(Slots $ro) | ForEach-Object { [string]$ro.GetValue($_) } | Where-Object { $_ }) }
foreach ($p in @($paths)) {
if (-not $p) { continue }
$want = Norm $p
$e = [ordered]@{ path = [string]$p; name = $null; state = $null; recentIndex = -1; recentValue = $null }
if ($ps) {
foreach ($n in $ps.GetValueNames()) {
if ((Norm $n) -eq $want) { $e.name = $n; $e.state = [string]$ps.GetValue($n); break }
}
}
for ($i = 0; $i -lt $recent.Count; $i++) {
if ((Norm $recent[$i]) -eq $want) { $e.recentIndex = $i; $e.recentValue = $recent[$i]; break }
}
$entries += $e
}
if ($ps) { $ps.Close() }
if ($ro) { $ro.Close() }
return [ordered]@{ root = $root; entries = $entries; recent = @($recent) }
}
function RestoreProjects($snap, $prefixes, [string]$temp) {
$root = [string]$snap.root
$entries = @($snap.entries)
$exact = @{}
foreach ($e in $entries) { $exact[(Norm ([string]$e.path))] = $e }
$pre = @(@($prefixes) | Where-Object { $_ } | ForEach-Object { Norm ([string]$_) })
$hit = {
param([string]$p)
if (-not $p) { return $false }
$n = Norm $p
if ($exact.ContainsKey($n)) { return $true }
foreach ($x in $pre) { if ($n.StartsWith($x)) { return $true } }
return $false
}
$stateWrites = 0
$recentWrites = 0
$k = $hk.OpenSubKey($root + $SEP + 'ProjectState', $true)
if ($k) {
foreach ($n in $k.GetValueNames()) {
if (-not (& $hit $n)) { continue }
$e = $exact[(Norm $n)]
# An entry that existed before the run keeps its own name and gets its
# old state back; any other spelling of the same path is the run's.
if ($e -and $e.name -and ($n -ceq [string]$e.name)) { continue }
# $false: a concurrent run may have deleted it between the listing and
# here, which once threw and abandoned the whole tidy, recent list and all.
$k.DeleteValue($n, $false); $stateWrites++
}
foreach ($e in $entries) {
if (-not $e.name) { continue }
$name = [string]$e.name
$had = @($k.GetValueNames()) -contains $name
if (-not $had -or ([string]$k.GetValue($name) -cne [string]$e.state)) {
$k.SetValue($name, [string]$e.state, $String); $stateWrites++
}
}
$k.Close()
}
$k = $hk.OpenSubKey($root + $SEP + 'RecentlyOpened', $true)
if ($k) {
$slots = @(Slots $k)
$vals = @($slots | ForEach-Object { [string]$k.GetValue($_) })
$list = New-Object System.Collections.ArrayList
foreach ($v in $vals) { if ($v -and -not (& $hit $v)) { [void]$list.Add($v) } }
$back = @($entries | Where-Object { [int]$_.recentIndex -ge 0 } | Sort-Object { [int]$_.recentIndex })
foreach ($e in $back) {
$list.Insert([Math]::Min([int]$e.recentIndex, $list.Count), [string]$e.recentValue)
}
# The IDE fills a short list's empty slots with copies of its last entry,
# and a full list drops its oldest entry for each project a run opens
# (BUGS-TO-REPORT.md). With the list as it was found in hand, keep no more
# copies of a path than it had, and put back at the end what fell off --
# but not a path in the temp folder, which belongs to some run, and that
# run may have tidied it away since.
if (@($snap.PSObject.Properties.Name) -contains 'recent') {
$count = @{}
foreach ($v in @($snap.recent)) { $n = Norm ([string]$v); if ($n) { $count[$n] = 1 + [int]$count[$n] } }
$have = @{}
$kept = New-Object System.Collections.ArrayList
foreach ($v in $list) {
$n = Norm ([string]$v)
if ([int]$have[$n] -lt [Math]::Max(1, [int]$count[$n])) { [void]$kept.Add($v); $have[$n] = 1 + [int]$have[$n] }
}
$tmp = Norm $temp
foreach ($v in @($snap.recent)) {
$n = Norm ([string]$v)
if (-not $n -or ($tmp -and $n.StartsWith($tmp))) { continue }
if ([int]$have[$n] -lt [int]$count[$n]) { [void]$kept.Add([string]$v); $have[$n] = 1 + [int]$have[$n] }
}
$list = $kept
}
$changed = $false
for ($i = 0; $i -lt $slots.Count; $i++) {
$v = ''
if ($i -lt $list.Count) { $v = [string]$list[$i] }
if ($v -cne $vals[$i]) { $changed = $true }
}
if ($changed) {
for ($i = 0; $i -lt $slots.Count; $i++) {
$v = ''
if ($i -lt $list.Count) { $v = [string]$list[$i] }
if ($v -cne $vals[$i]) { $k.SetValue($slots[$i], $v, $String); $recentWrites++ }
}
}
$k.Close()
}
return [ordered]@{ projectState = $stateWrites; recentlyOpened = $recentWrites }
}
function SnapKey([string]$path) {
$k = $hk.OpenSubKey($path)
if (-not $k) { return $null }
$values = @(foreach ($n in $k.GetValueNames()) {
$kind = $k.GetValueKind($n).ToString()
$data = $k.GetValue($n, $null, 'DoNotExpandEnvironmentNames')
if ($kind -eq 'Binary') { $data = [Convert]::ToBase64String([byte[]]$data) }
[ordered]@{ name = $n; kind = $kind; data = $data }
})
$keys = @(foreach ($s in $k.GetSubKeyNames()) {
[ordered]@{ name = $s; snap = (SnapKey ($path + $SEP + $s)) }
})
$k.Close()
return [ordered]@{ values = $values; keys = $keys }
}
function SameData([string]$kind, $a, $b) {
if ($kind -eq 'MultiString') { return ((@($a) -join [char]0) -ceq (@($b) -join [char]0)) }
return ([string]$a -ceq [string]$b)
}
function RestoreKey([string]$path, $snap) {
# Restoring deletes every value and subkey the snapshot does not list, so a
# path near the root would be a disaster rather than a no-op. The JavaScript
# side refuses one too; this is the check that cannot be bypassed from there.
if (@($path.Split($SEP) | Where-Object { $_ }).Count -lt 3) {
throw ('refusing to restore a key this close to the root: "' + $path + '"')
}
$existing = $hk.OpenSubKey($path)
if ($null -eq $snap) {
if ($existing) { $existing.Close(); $hk.DeleteSubKeyTree($path, $false); $script:changes++ }
return
}
if ($existing) { $existing.Close() } else { $script:changes++ }
$k = $hk.CreateSubKey($path)
$want = @{}
foreach ($v in @($snap.values)) { $want[[string]$v.name] = $true }
foreach ($n in $k.GetValueNames()) {
if (-not $want.ContainsKey($n)) { $k.DeleteValue($n, $false); $script:changes++ }
}
$names = @($k.GetValueNames())
foreach ($v in @($snap.values)) {
$name = [string]$v.name
$kind = [string]$v.kind
$data = $v.data
if ($kind -eq 'Binary') { $data = [Convert]::FromBase64String([string]$v.data) }
elseif ($kind -eq 'MultiString') { $data = [string[]]@($v.data) }
elseif ($kind -eq 'DWord') { $data = [int]$v.data }
elseif ($kind -eq 'QWord') { $data = [long]$v.data }
$same = $false
if ($names -contains $name) {
$curKind = $k.GetValueKind($name).ToString()
$cur = $k.GetValue($name, $null, 'DoNotExpandEnvironmentNames')
$cmp = $data
if ($curKind -eq 'Binary') { $cur = [Convert]::ToBase64String([byte[]]$cur); $cmp = [string]$v.data }
$same = ($curKind -eq $kind) -and (SameData $kind $cur $cmp)
}
if (-not $same) {
$k.SetValue($name, $data, [Microsoft.Win32.RegistryValueKind]$kind); $script:changes++
}
}
$wantKeys = @{}
foreach ($s in @($snap.keys)) { $wantKeys[[string]$s.name] = $true }
foreach ($s in $k.GetSubKeyNames()) {
if (-not $wantKeys.ContainsKey($s)) { $k.DeleteSubKeyTree($s, $false); $script:changes++ }
}
$k.Close()
foreach ($s in @($snap.keys)) { RestoreKey ($path + $SEP + [string]$s.name) $s.snap }
}
function ReadValue([string]$path, [string]$name) {
$out = [ordered]@{ exists = $false; data = $null }
$k = $hk.OpenSubKey($path)
if (-not $k) { return $out }
if (@($k.GetValueNames()) -contains $name) { $out.exists = $true; $out.data = [string]$k.GetValue($name) }
$k.Close()
return $out
}
# Written only if the value still holds what the caller read, so that a value
# an IDE saved in the meantime is never overwritten with an older copy.
function WriteValueIf([string]$path, [string]$name, [string]$expected, [string]$data) {
$k = $hk.OpenSubKey($path, $true)
if (-not $k) { return [ordered]@{ written = $false } }
$same = (@($k.GetValueNames()) -contains $name) -and ([string]$k.GetValue($name) -ceq $expected)
if ($same) { $k.SetValue($name, $data, $String) }
$k.Close()
return [ordered]@{ written = $same }
}
try {
$req = [Console]::In.ReadToEnd() | ConvertFrom-Json
switch ([string]$req.op) {
'lists' { $result = Lists ([string]$req.root) }
'readValue' { $result = ReadValue ([string]$req.key) ([string]$req.name) }
'subkeys' {
$result = @()
$k = $hk.OpenSubKey([string]$req.key)
if ($k) { $result = @($k.GetSubKeyNames() | Sort-Object); $k.Close() }
}
'writeValueIf' {
$result = WriteValueIf ([string]$req.key) ([string]$req.name) ([string]$req.expected) ([string]$req.data)
}
'snapshotProjects' { $result = SnapProjects ([string]$req.root) $req.paths }
'restoreProjects' { $result = RestoreProjects $req.snapshot $req.prefixes ([string]$req.temp) }
'snapshotKeys' {
$result = @(foreach ($p in @($req.keys)) { [ordered]@{ path = [string]$p; snap = (SnapKey ([string]$p)) } })
}
'restoreKeys' {
$script:changes = 0
foreach ($e in @($req.snapshot)) { RestoreKey ([string]$e.path) $e.snap }
$result = [ordered]@{ changes = $script:changes }
}
default { throw ('unknown op: ' + [string]$req.op) }
}
ConvertTo-Json -InputObject ([ordered]@{ result = $result }) -Depth 16 -Compress
} catch {
ConvertTo-Json -InputObject ([ordered]@{ error = $_.Exception.Message }) -Compress
}
`;
const ENCODED = Buffer.from(SCRIPT, "utf16le").toString("base64");
function request(req) {
let out;
try {
out = execFileSync("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", ENCODED], {
input: JSON.stringify(req), encoding: "utf8", windowsHide: true,
stdio: ["pipe", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024,
});
} catch (e) {
// PowerShell itself failed to run the script; the script's own errors come
// back as {"error"} below.
throw new Error(`registry ${req.op} failed: ${e.message.split(/\r?\n/)[0]}`);
}
// A byte-order mark would make JSON.parse refuse the answer; the script asks
// for UTF-8 without one, and this makes sure.
const answer = JSON.parse(out.replace(/^/, ""));
if (answer.error !== undefined) throw new Error(`registry ${req.op} failed: ${answer.error}`);
return answer.result;
}
/** The IDE's project-state names and its recent list, most recent first. */
export function ideLists({ root = IDE_SETTINGS_KEY } = {}) {
return request({ op: "lists", root });
}
/**
* Record what the IDE holds for these projects now, and its whole recent list,
* so restoreProjects can put it back. A project with no entry is recorded as
* having none.
*/
export function snapshotProjects(paths = [], { root = IDE_SETTINGS_KEY } = {}) {
return request({ op: "snapshotProjects", root, paths: paths.map((p) => path.resolve(p)) });
}
/**
* Put the snapshot's projects back as they were, and delete every entry under
* the given folders.
*
* The recent list is put back as the snapshot has it, with whatever else
* happened to it meanwhile kept: a project the user opened stays on top, but
* no path keeps more copies than the snapshot had, and the snapshot's entries
* that fell off the end come back there. Both are the IDE's doing. It fills a
* short list's empty slots with copies of its last entry, so a run that
* started on one entry ended with seventeen copies of it; and a full list
* drops its oldest entry for every project a run opens (BUGS-TO-REPORT.md).
* An entry in the temp folder is not brought back, since it belongs to some
* run, whose own tidy may have removed it meanwhile. A snapshot with no
* `recent`, such as `{ root, entries: [] }`, only deletes.
*
* @param {string[]} [o.prefixes] folders inside the OS temp folder; anything
* else is refused, so that a caller passing the wrong folder cannot sweep
* away the state of the user's real projects
* @returns {{projectState: number, recentlyOpened: number}} values written or deleted
*/
export function restoreProjects(snapshot, { prefixes = [] } = {}) {
return request({ op: "restoreProjects", snapshot, prefixes: prefixes.map(asTempFolder),
temp: path.resolve(tmpdir()) + path.sep });
}
/** The names of a key's subkeys, sorted, and nothing else from under it; empty when there is no such key. */
export function subkeyNames(key) {
return [].concat(request({ op: "subkeys", key }) ?? []);
}
/** Everything under these keys, values and subkeys, for restoreKeys. */
export function snapshotKeys(keys = ASSOCIATION_KEYS) {
for (const k of keys) deepEnough(k);
return request({ op: "snapshotKeys", keys });
}
/** Put the keys back as snapshotted, writing only what differs; returns the number of writes. */
export function restoreKeys(snapshot) {
for (const e of snapshot) deepEnough(e.path);
return request({ op: "restoreKeys", snapshot }).changes;
}
/** Where SaveSetting keeps every application's settings, an add-in's included. */
export const SETTINGS_ROOT = "Software\\VB and VBA Program Settings";
/**
* The key SaveSetting writes an application's settings under. An add-in's
* SaveSetting writes here too, so its settings are shared with any installed
* copy of the same add-in, and a test that changes one changes the user's.
*
* The IDE's own application name is refused. That key holds all of the IDE's
* settings, and the parts of it a run changes are put back value by value by
* startTidy and finishTidy, never as a whole.
*/
export function settingsKey(app) {
const name = String(app ?? "");
if (!name || /[\\/]/.test(name)) throw new Error(`not a SaveSetting application name: "${name}"`);
if (name.toLowerCase() === "twinbasic_ide") {
throw new Error("refusing the IDE's own settings key: the run's tidy puts back the parts of " +
"it the IDE changes, value by value");
}
return `${SETTINGS_ROOT}\\${name}`;
}
/**
* What SaveSetting has stored for an application, as `{ section: { name: value } }`,
* or null when it has stored nothing.
*/
export function savedSettings(app) {
const [entry] = snapshotKeys([settingsKey(app)]);
if (!entry?.snap) return null;
const out = {};
for (const s of [].concat(entry.snap.keys ?? [])) {
out[s.name] = Object.fromEntries([].concat(s.snap?.values ?? []).map((v) => [v.name, v.data]));
}
return out;
}
/**
* Delete what SaveSetting has stored for these applications, so that their
* next GetSetting returns its default. Snapshot the keys first
* (`snapshotKeys(apps.map(settingsKey))`) to put them back afterwards.
*
* @returns {number} the number of writes
*/
export function deleteSettings(apps) {
return restoreKeys(apps.map((a) => ({ path: settingsKey(a), snap: null })));
}
const ARCH_MEMORY = "targetArchitectureMemory";
const norm = (p) => String(p).split("/").join("\\").toLowerCase();
// The build targets the IDE remembers, as an object, or null when there is no
// value or it is not a JSON object -- which is not the harness's to repair.
function readArchitectureMemory(root) {
const now = request({ op: "readValue", key: `${root}\\IDESettings`, name: ARCH_MEMORY });
if (!now.exists) return null;
let memory;
try { memory = JSON.parse(now.data); } catch { return null; }
if (!memory || typeof memory !== "object" || Array.isArray(memory)) return null;
return { data: now.data, memory };
}
// Change the remembered build targets with `edit`, which is handed the object
// and returns how many entries it changed. The object is edited here rather
// than in PowerShell, and written back with JSON.stringify, which is how the
// IDE writes it, so the other entries keep their exact text and order. The
// write is refused if the value changed after it was read -- an IDE switching
// a target of its own meanwhile -- and the edit is then made again on what is
// there now.
function editArchitectureMemory(root, edit) {
for (let attempt = 0; attempt < 3; attempt++) {
const now = readArchitectureMemory(root);
if (!now) return 0;
const changes = edit(now.memory);
if (!changes) return 0;
const w = request({ op: "writeValueIf", key: `${root}\\IDESettings`, name: ARCH_MEMORY,
expected: now.data, data: JSON.stringify(now.memory) });
if (w.written) return changes;
}
throw new Error(`the IDE's ${ARCH_MEMORY} kept changing while it was being tidied`);
}
/**
* Delete the build target the IDE remembers for every project under these
* folders.
*
* The IDE keeps the target it last built each project for, win32 or win64, in
* one IDESettings value holding a JSON object keyed by project path, and a
* project it opens again starts in that target. A harness project's path is
* used run after run -- tbrun's work folder is keyed to its port -- so an
* entry one run leaves, when somebody switches a --keep IDE to win64, sets the
* target of every later run on that path, and nothing says so. On 2026-09-24
* tbrun on ports 9372 and 9373 built 64-bit for that reason.
*
* Entries for any other path are left alone here, the user's own projects
* among them. Opening a project only reads its entry; one is written when the
* target of an open project changes, which `--arch` does and a person can.
* A named project's entry is put back by restoreArchitectureMemory instead.
*
* @param {string[]} prefixes folders inside the OS temp folder, as for restoreProjects
* @param {object} [o]
* @param {string} [o.root] the IDE's settings key
* @returns {number} entries deleted
*/
export function sweepArchitectureMemory(prefixes = [], { root = IDE_SETTINGS_KEY } = {}) {
const pre = prefixes.map((p) => norm(asTempFolder(p)));
if (!pre.length) return 0;
return editArchitectureMemory(root, (memory) => {
const drop = Object.keys(memory).filter((p) => pre.some((x) => norm(p).startsWith(x)));
for (const p of drop) delete memory[p];
return drop.length;
});
}
/**
* Record the build targets the IDE remembers for these projects, for
* restoreArchitectureMemory: every entry whose key names one of them, however
* the key is spelled, with its value. A project with none is recorded as
* having none.
*/
export function snapshotArchitectureMemory(paths = [], { root = IDE_SETTINGS_KEY } = {}) {
const want = paths.map((p) => norm(path.resolve(p)));
const memory = want.length ? readArchitectureMemory(root)?.memory ?? {} : {};
return { root, paths: want, entries: Object.entries(memory).filter(([p]) => want.includes(norm(p))) };
}
/**
* Put back the build targets a snapshot recorded, and delete every other entry
* for the same projects.
*
* A run that switches the target of a project it opens -- tbbuild --arch on
* the user's own project -- leaves the IDE's entry for it, saved under the
* path as the IDE was given it, which need not be spelled as the user's own
* IDE spelled it. So an entry the snapshot has is given its old value in its
* old place, and any other entry for the same project is deleted.
*
* @returns {number} entries written or deleted
*/
export function restoreArchitectureMemory(snap) {
if (!snap?.paths?.length) return 0;
return editArchitectureMemory(snap.root, (memory) => {
let changes = 0;
const had = new Map(snap.entries);
for (const p of Object.keys(memory)) {
if (!snap.paths.includes(norm(p))) continue;
if (!had.has(p)) { delete memory[p]; changes++; }
else if (memory[p] !== had.get(p)) { memory[p] = had.get(p); changes++; }
}
for (const [p, v] of had) if (!(p in memory)) { memory[p] = v; changes++; }
return changes;
});
}
// Restoring a key deletes whatever the snapshot does not list, so a key near
// the root -- `Software`, `Software\Classes` -- would take everything under it.
// Three segments is the shallowest key this has any business restoring.
function deepEnough(key) {
if (String(key ?? "").split("\\").filter(Boolean).length < 3) {
throw new Error(`refusing to snapshot or restore a key this close to the root: "${key}"`);
}
}
// A folder prefix has to end in a separator, or tbrun's %TEMP%\tbrun\9346 would
// also claim %TEMP%\tbrun\93460. And it has to be inside the temp folder, which
// is the only place the harness creates projects.
function asTempFolder(p) {
const r = path.resolve(p);
const tmp = path.resolve(tmpdir());
const rel = path.relative(tmp, r);
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) {
throw new Error(`refusing to sweep project entries outside ${tmp}: "${r}"`);
}
return r.endsWith(path.sep) ? r : r + path.sep;
}
function alive(pid) {
try { process.kill(pid, 0); return true; } catch { return false; }
}
/**
* Take charge of the registry for this run: record what is there, and clear
* out what an earlier run on the same folders left behind.
*
* Returns null when another live process already owns the run -- a tbbuild
* started by check_examples -- because the owner tidies for everybody. An
* owner that is no longer running does not count: a variable left set in a
* shell would otherwise switch tidying off for good.
*
* Never throws. Tidying is hygiene, and failing a compile over it would be
* worse than the leftovers; a failure is said on stderr and the run goes on.
*
* @param {object} [o]
* @param {string[]} [o.paths] projects the run opens that may be the
* user's own, restored rather than deleted
* @param {string[]} [o.prefixes] folders only the harness writes to; every
* entry under them is deleted
* @param {string} [o.root] the IDE's settings key (default IDE_SETTINGS_KEY)
* @param {string[]} [o.keys] the association keys (default ASSOCIATION_KEYS);
* the self-test passes scratch keys for both
*/
export function startTidy({ paths = [], prefixes = [], root = IDE_SETTINGS_KEY,
keys = ASSOCIATION_KEYS } = {}) {
const owner = Number(process.env.TB_REGISTRY_OWNER);
if (owner && owner !== process.pid && alive(owner)) return null;
process.env.TB_REGISTRY_OWNER = String(process.pid);
let tidy;
try {
if (prefixes.length) restoreProjects({ root, entries: [] }, { prefixes });
tidy = { projects: snapshotProjects(paths, { root }), keys: snapshotKeys(keys), prefixes, root };
tidy.keysInTemp = namesTempFolder(tidy.keys);
} catch (e) {
console.error(`warning: the IDE's registry entries will not be tidied after this run: ${e.message}`);
return null;
}
sweepTargets(prefixes, root);
// After the sweep, so a named project inside a swept folder is not given back
// an entry the sweep has just deleted.
tidy.targets = snapshotTargets(paths, root);
return tidy;
}
/**
* Put the registry back as startTidy found it. Call it only once every IDE of
* the run has exited -- shutdownIde waits for that.
*
* @returns {{projectState: number, recentlyOpened: number, association: number,
* architecture: number | null} | null}
*/
export function finishTidy(tidy) {
if (!tidy) return null;
let done;
try {
const p = restoreProjects(tidy.projects, { prefixes: tidy.prefixes });
// An association that named the temp folder when the run began belonged to
// another run's copy of the IDE (tb-ide-copy.mjs), which will be deleted:
// putting it back would point .twinproj files at nothing. It is left as
// the IDEs set it, and the next IDE started from a real install points it
// back at that install.
if (tidy.keysInTemp) {
console.error("note: the .twinproj association pointed into the temp folder when this " +
"run began, at another run's copy of the IDE, so it is left as it is now");
}
done = { ...p, association: tidy.keysInTemp ? null : restoreKeys(tidy.keys) };
} catch (e) {
console.error(`warning: could not tidy the IDE's registry entries after this run: ${e.message}`);
return null;
}
const swept = sweepTargets(tidy.prefixes, tidy.root);
const restored = restoreTargets(tidy.targets);
return { ...done, architecture: swept === null || restored === null ? null : swept + restored };
}
// Whether any value in a key snapshot names a path inside the temp folder.
function namesTempFolder(snapshot) {
const tmp = norm(path.resolve(tmpdir())) + "\\";
const named = (snap) => !!snap && (
[].concat(snap.values ?? []).some((v) => [].concat(v?.data ?? []).some((d) => norm(d).includes(tmp))) ||
[].concat(snap.keys ?? []).some((k) => named(k?.snap)));
return [].concat(snapshot ?? []).some((e) => named(e?.snap));
}
// Each with a warning of its own, so that failing here costs only this part of the tidy.
function sweepTargets(prefixes, root) {
try {
return sweepArchitectureMemory(prefixes, { root });
} catch (e) {
console.error(`warning: could not tidy the build targets the IDE remembers: ${e.message}`);
return null;
}
}
function snapshotTargets(paths, root) {
try {
return snapshotArchitectureMemory(paths, { root });
} catch (e) {
console.error(`warning: the build targets the IDE remembers for this run's projects will ` +
`not be put back: ${e.message}`);
return null;
}
}
// A snapshot that failed was warned about when it was taken; there is nothing to put back.
function restoreTargets(snap) {
if (!snap) return 0;
try {
return restoreArchitectureMemory(snap);
} catch (e) {
console.error(`warning: could not put back the build targets the IDE remembers: ${e.message}`);
return null;
}
}