-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorktreeBootstrapper.php
More file actions
619 lines (559 loc) · 19.3 KB
/
Copy pathWorktreeBootstrapper.php
File metadata and controls
619 lines (559 loc) · 19.3 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
<?php
/**
* Worktree Bootstrapper
*
* `git worktree add` intentionally only replays git-tracked state. That leaves
* a new checkout missing anything non-tracked the repo needs before tests or
* builds can run — submodules (tracked but not auto-init'd), `node_modules`,
* Composer vendor dir, etc. Users hit silent failure modes like "vitest can't
* load spec" or "sh: nx: command not found".
*
* This class implements the opt-in `--bootstrap` step: detect what the repo
* declares it needs (via standard lockfiles + `.gitmodules`), run each step,
* and report structured results so callers can surface a clear status line.
*
* Detection is convention-based, not configurable (yet — issue #50 proposes a
* `.datamachine/worktree.yml` follow-up for repo-declared custom steps). Steps
* run in a fixed order:
*
* 1. `git submodule update --init --recursive` if `.gitmodules` exists
* 2. Package-manager install per dependency root, based on lockfile presence:
* pnpm-lock.yaml → pnpm install --frozen-lockfile
* bun.lockb/.lock → bun install --frozen-lockfile
* yarn.lock → yarn install --immutable
* package-lock.json → npm ci
* 3. `composer install --no-interaction --prefer-dist` per dependency root
* if `composer.lock` exists
*
* Dependency roots include the worktree root plus one-level child directories
* with lockfiles. Git submodule roots are excluded: they own independent
* dependency lifecycles. A repository may explicitly opt a submodule in via
* `.datamachine/worktree-bootstrap.json`; see `submodule_dependency_roots`.
*
* Each step is optional. Missing binaries (no `pnpm` on PATH, etc.) downgrade
* to a `skipped` result rather than failing. Command failures are returned as
* structured step results — the worktree itself stays created even if bootstrap
* partially fails, and the CLI surfaces the failing step so the user can
* decide whether to retry manually.
*
* No WordPress dependency so this class is unit-testable via pure PHP smokes.
*
* @package DataMachineCode\Workspace
* @since 0.8.0
*/
namespace DataMachineCode\Workspace;
use DataMachineCode\Support\ProcessRunner;
use DataMachineCode\Support\RuntimeCapabilities;
defined('ABSPATH') || exit;
if ( ! class_exists(ProcessRunner::class) ) {
require_once dirname(__DIR__) . '/Support/ProcessRunner.php';
}
if ( ! class_exists(RuntimeCapabilities::class) ) {
require_once dirname(__DIR__) . '/Support/RuntimeCapabilities.php';
}
final class WorktreeBootstrapper {
/**
* Step kinds in the order they are executed.
*/
public const STEP_SUBMODULES = 'submodules';
public const STEP_PACKAGES = 'packages';
public const STEP_COMPOSER = 'composer';
/**
* Status values reported per step.
*/
public const STATUS_RAN = 'ran'; // Command executed and exited 0.
public const STATUS_SKIPPED = 'skipped'; // No trigger file, or tool unavailable.
public const STATUS_FAILED = 'failed'; // Command executed but exited non-zero.
/**
* Output size cap (bytes) retained per step. Bootstrap installs can emit
* tens of megabytes of log noise; we keep the tail for diagnostics only.
*/
private const OUTPUT_CAP_BYTES = 4096;
/**
* Directories that should never be treated as nested component roots.
*/
private const NESTED_ROOT_EXCLUDE_DIRS = array(
'.git',
'.github',
'.claude',
'.opencode',
'node_modules',
'vendor',
);
/** Repository-owned opt-in contract for submodule dependency roots. */
private const SUBMODULE_BOOTSTRAP_CONFIG = '.datamachine/worktree-bootstrap.json';
/**
* Run all applicable bootstrap steps inside the given worktree.
*
* @param string $worktree_path Absolute path to the worktree root.
* @return array{
* success: bool,
* ran_any: bool,
* skipped_package_roots: array<int, array{relative: string, manager: string, reason: string}>,
* steps: array<int, array{
* step: string,
* status: string,
* reason?: string,
* command?: string,
* exit_code?: int,
* output_tail?: string,
* }>,
* }
*/
public static function bootstrap( string $worktree_path ): array {
$package_discovery = self::discover_package_roots($worktree_path);
$steps = array();
$steps[] = self::run_submodules($worktree_path);
$steps = array_merge($steps, self::run_packages($package_discovery['roots']));
$steps = array_merge($steps, self::run_composer($worktree_path));
$failed = array_filter($steps, fn( $s ) => self::STATUS_FAILED === ( $s['status'] ?? '' ));
$ran_any = (bool) array_filter($steps, fn( $s ) => self::STATUS_RAN === ( $s['status'] ?? '' ));
return array(
'success' => empty($failed),
'ran_any' => $ran_any,
'skipped_package_roots' => $package_discovery['skipped'],
'steps' => $steps,
);
}
/**
* Detect which bootstrap steps WOULD run for a given worktree path, without
* executing anything. Useful for diagnostics and for the smoke test.
*
* @param string $worktree_path Absolute path to the worktree root.
* @return array{
* submodules: bool,
* packages: ?string, // Root package manager slug or null.
* composer: bool,
* package_roots: array<int, array{path: string, relative: string, manager: string}>,
* skipped_package_roots: array<int, array{relative: string, manager: string, reason: string}>,
* composer_roots: array<int, array{path: string, relative: string}>,
* }
*/
public static function detect( string $worktree_path ): array {
$package_discovery = self::discover_package_roots($worktree_path);
$composer_roots = self::discover_composer_roots($worktree_path);
return array(
'submodules' => is_file(rtrim($worktree_path, '/') . '/.gitmodules'),
'packages' => self::detect_package_manager($worktree_path),
'composer' => is_file(rtrim($worktree_path, '/') . '/composer.lock'),
'package_roots' => $package_discovery['roots'],
'skipped_package_roots' => $package_discovery['skipped'],
'composer_roots' => $composer_roots,
);
}
/**
* Pretty-print a bootstrap result as a multi-line human-readable block.
*
* @param array $result Result from {@see self::bootstrap()}.
* @return string
*/
public static function format( array $result ): string {
$steps = is_array($result['steps'] ?? null) ? $result['steps'] : array();
if ( empty($steps) ) {
return 'Bootstrap: no steps attempted.';
}
$lines = array();
foreach ( $steps as $step ) {
$kind = (string) ( $step['step'] ?? '?' );
$target = (string) ( $step['relative'] ?? '' );
$label = '.' === $target || '' === $target ? $kind : sprintf('%s[%s]', $kind, $target);
$status = (string) ( $step['status'] ?? '?' );
$reason = (string) ( $step['reason'] ?? '' );
$cmd = (string) ( $step['command'] ?? '' );
switch ( $status ) {
case self::STATUS_RAN:
$lines[] = sprintf(' ✓ %-18s ran: %s', $label, $cmd);
break;
case self::STATUS_SKIPPED:
$lines[] = sprintf(' - %-18s skipped (%s)', $label, '' !== $reason ? $reason : 'no trigger');
break;
case self::STATUS_FAILED:
$exit = isset($step['exit_code']) ? (int) $step['exit_code'] : -1;
$lines[] = sprintf(' ✗ %-18s FAILED (exit %d): %s', $label, $exit, $cmd);
if ( ! empty($step['output_tail']) ) {
foreach ( explode("\n", (string) $step['output_tail']) as $out_line ) {
$lines[] = ' ' . $out_line;
}
}
break;
default:
$lines[] = sprintf(' ? %-18s %s', $label, $status);
}
}
return implode("\n", $lines);
}
/**
* Run `git submodule update --init --recursive` if `.gitmodules` is present.
*/
private static function run_submodules( string $worktree_path ): array {
if ( ! is_file(rtrim($worktree_path, '/') . '/.gitmodules') ) {
return array(
'step' => self::STEP_SUBMODULES,
'status' => self::STATUS_SKIPPED,
'reason' => 'no .gitmodules',
);
}
if ( ! self::binary_available('git') ) {
return array(
'step' => self::STEP_SUBMODULES,
'status' => self::STATUS_SKIPPED,
'reason' => 'git not on PATH',
);
}
return self::run_command(
self::STEP_SUBMODULES,
$worktree_path,
'git submodule update --init --recursive'
);
}
/**
* Run the detected package manager's install command, if any.
*/
private static function run_packages( array $roots ): array {
if ( empty($roots) ) {
return array(
array(
'step' => self::STEP_PACKAGES,
'status' => self::STATUS_SKIPPED,
'reason' => 'no lockfile',
),
);
}
$steps = array();
foreach ( $roots as $root ) {
$pm = $root['manager'];
if ( ! self::binary_available($pm) ) {
$steps[] = array(
'step' => self::STEP_PACKAGES,
'status' => self::STATUS_SKIPPED,
'reason' => sprintf('%s not on PATH (lockfile present)', $pm),
'relative' => $root['relative'],
);
continue;
}
$command = match ( $pm ) {
'pnpm' => 'pnpm install --frozen-lockfile',
'bun' => 'bun install --frozen-lockfile',
'yarn' => 'yarn install --immutable',
'npm' => 'npm ci',
default => '',
};
if ( '' === $command ) {
$steps[] = array(
'step' => self::STEP_PACKAGES,
'status' => self::STATUS_SKIPPED,
'reason' => sprintf('unsupported package manager %s', $pm),
'relative' => $root['relative'],
);
continue;
}
$steps[] = self::run_command(self::STEP_PACKAGES, $root['path'], $command, $root['relative']);
}
return $steps;
}
/**
* Run `composer install` if `composer.lock` is present.
*/
private static function run_composer( string $worktree_path ): array {
$roots = self::discover_composer_roots($worktree_path);
if ( empty($roots) ) {
return array(
array(
'step' => self::STEP_COMPOSER,
'status' => self::STATUS_SKIPPED,
'reason' => 'no composer.lock',
),
);
}
$steps = array();
foreach ( $roots as $root ) {
if ( ! self::binary_available('composer') ) {
$steps[] = array(
'step' => self::STEP_COMPOSER,
'status' => self::STATUS_SKIPPED,
'reason' => 'composer not on PATH',
'relative' => $root['relative'],
);
continue;
}
$steps[] = self::run_command(
self::STEP_COMPOSER,
$root['path'],
'composer install --no-interaction --prefer-dist',
$root['relative']
);
}
return $steps;
}
/**
* Discover package-manager roots at the repo root and one directory deep.
*
* @return array{roots: array<int, array{path: string, relative: string, manager: string}>, skipped: array<int, array{relative: string, manager: string, reason: string}>}
*/
private static function discover_package_roots( string $worktree_path ): array {
$roots = array();
$skipped = array();
foreach ( self::candidate_dependency_roots($worktree_path) as $candidate ) {
$manager = self::detect_package_manager($candidate['path']);
if ( null === $manager ) {
continue;
}
if ( ! empty($candidate['submodule']) && empty($candidate['submodule_opted_in']) ) {
$skipped[] = array(
'relative' => $candidate['relative'],
'manager' => $manager,
'reason' => 'git submodule dependency root is excluded by default',
);
continue;
}
$roots[] = array(
'path' => $candidate['path'],
'relative' => $candidate['relative'],
'manager' => $manager,
);
}
return array(
'roots' => $roots,
'skipped' => $skipped,
);
}
/**
* Discover Composer roots at the repo root and one directory deep.
*
* @return array<int, array{path: string, relative: string}>
*/
private static function discover_composer_roots( string $worktree_path ): array {
$roots = array();
foreach ( self::candidate_dependency_roots($worktree_path) as $candidate ) {
if ( ! empty($candidate['submodule']) && empty($candidate['submodule_opted_in']) ) {
continue;
}
if ( ! is_file($candidate['path'] . '/composer.lock') ) {
continue;
}
$roots[] = $candidate;
}
return $roots;
}
/**
* Return the repo root plus one-level child directories that may own deps.
*
* @return array<int, array{path: string, relative: string, submodule?: bool, submodule_opted_in?: bool}>
*/
private static function candidate_dependency_roots( string $worktree_path ): array {
$root = rtrim($worktree_path, '/');
$submodules = self::submodule_paths($root);
$opted_in = self::opted_in_submodule_dependency_roots($root);
$candidates = array(
array(
'path' => $root,
'relative' => '.',
),
);
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Unreadable roots are skipped as non-candidates below.
$entries = @scandir($root);
if ( false === $entries ) {
return $candidates;
}
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry || in_array($entry, self::NESTED_ROOT_EXCLUDE_DIRS, true) ) {
continue;
}
$path = $root . '/' . $entry;
if ( ! is_dir($path) || is_link($path) ) {
continue;
}
$candidates[] = array(
'path' => $path,
'relative' => $entry,
'submodule' => isset($submodules[$entry]),
'submodule_opted_in' => isset($opted_in[$entry]),
);
}
return $candidates;
}
/**
* Read declared submodule paths without depending on an initialized checkout.
*
* `.gitmodules` is tracked by the superproject and is available even when a
* submodule's pinned commit cannot be fetched or checked out.
*
* @return array<string, true> Relative submodule paths keyed by path.
*/
private static function submodule_paths( string $worktree_path ): array {
$gitmodules = $worktree_path . '/.gitmodules';
if ( ! is_file($gitmodules) ) {
return array();
}
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Invalid or unreadable declarations simply provide no boundaries.
$sections = @parse_ini_file($gitmodules, true, INI_SCANNER_RAW);
if ( ! is_array($sections) ) {
return array();
}
$paths = array();
foreach ( $sections as $section ) {
$path = is_array($section) ? (string) ($section['path'] ?? '') : '';
$path = trim($path, '/');
if ( '' !== $path && ! str_contains($path, '..') ) {
$paths[$path] = true;
}
}
return $paths;
}
/**
* Read the explicit repository contract for submodules DMC may bootstrap.
*
* @return array<string, true> Relative submodule paths keyed by path.
*/
private static function opted_in_submodule_dependency_roots( string $worktree_path ): array {
$config = $worktree_path . '/' . self::SUBMODULE_BOOTSTRAP_CONFIG;
if ( ! is_file($config) ) {
return array();
}
$decoded = json_decode((string) file_get_contents($config), true);
$declared = is_array($decoded) && is_array($decoded['submodule_dependency_roots'] ?? null)
? $decoded['submodule_dependency_roots']
: array();
$paths = array();
foreach ( $declared as $path ) {
if ( ! is_string($path) ) {
continue;
}
$path = trim($path, '/');
if ( '' !== $path && ! str_contains($path, '..') ) {
$paths[$path] = true;
}
}
return $paths;
}
/**
* Detect the active package manager for a checkout based on lockfile
* presence. Order: pnpm > bun > yarn > npm. A repo with multiple lockfiles
* picks whichever is highest-priority — this matches the convention most
* tooling (corepack, package-manager-detector) uses.
*
* Returns null if no supported lockfile is present, including when
* `package.json` exists alone (no lockfile → we can't run a reproducible
* install, so we skip rather than guess).
*
* @return string|null One of: "pnpm", "bun", "yarn", "npm", or null.
*/
private static function detect_package_manager( string $worktree_path ): ?string {
$root = rtrim($worktree_path, '/');
if ( is_file($root . '/pnpm-lock.yaml') ) {
return 'pnpm';
}
// Bun supports both the binary lockb and the text lock file.
if ( is_file($root . '/bun.lockb') || is_file($root . '/bun.lock') ) {
return 'bun';
}
if ( is_file($root . '/yarn.lock') ) {
return 'yarn';
}
if ( is_file($root . '/package-lock.json') ) {
return 'npm';
}
return null;
}
/**
* Is a binary available on PATH? Uses `command -v` which is portable across
* bash/zsh/dash — `which` is not POSIX.
*/
private static function binary_available( string $binary ): bool {
return RuntimeCapabilities::binary_available($binary, self::augmented_path());
}
/**
* Build a shell env prefix with non-interactive toolchain path fallbacks.
*/
private static function shell_env_prefix(): string {
$path = self::augmented_path();
if ( null === $path ) {
return '';
}
return sprintf('PATH=%s ', escapeshellarg($path));
}
/**
* Add common nvm binary dirs for shells that do not source .zshrc/.bashrc.
*/
private static function augmented_path(): ?string {
$current = getenv('PATH');
$current = is_string($current) ? $current : '';
$extra = self::discover_nvm_bin_dirs();
if ( empty($extra) ) {
return null;
}
$parts = array_filter(explode(PATH_SEPARATOR, $current), static fn( $part ) => '' !== $part);
foreach ( array_reverse($extra) as $dir ) {
if ( ! in_array($dir, $parts, true) ) {
array_unshift($parts, $dir);
}
}
return implode(PATH_SEPARATOR, $parts);
}
/**
* Find installed nvm Node versions without requiring shell startup files.
*
* @return string[] Absolute bin directories, newest-looking first.
*/
private static function discover_nvm_bin_dirs(): array {
$home = getenv('HOME');
if ( ! is_string($home) || '' === $home ) {
return array();
}
$versions_dir = rtrim($home, '/') . '/.nvm/versions/node';
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Missing NVM directories simply mean no NVM bin paths are available.
$entries = @scandir($versions_dir);
if ( false === $entries ) {
return array();
}
$bins = array();
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry ) {
continue;
}
$bin = $versions_dir . '/' . $entry . '/bin';
if ( is_dir($bin) ) {
$bins[] = $bin;
}
}
rsort($bins, SORT_NATURAL);
return $bins;
}
/**
* Execute a command inside the worktree and capture a result envelope.
*
* Note: we do not shell-escape the command itself — these are hard-coded
* invocations, not user input. The `cd` target is escaped.
*/
private static function run_command( string $step, string $worktree_path, string $command, string $relative = '.' ): array {
$result = ProcessRunner::run(
sprintf('%s%s 2>&1', self::shell_env_prefix(), $command),
array(
'cwd' => $worktree_path,
'output_cap_bytes' => self::OUTPUT_CAP_BYTES,
'error_as_result' => true,
)
);
if ( $result instanceof \WP_Error || empty($result['success']) ) {
$data = $result instanceof \WP_Error ? $result->get_error_data() : $result;
$data = is_array($data) ? $data : array();
$message = $result instanceof \WP_Error ? $result->get_error_message() : 'Process command failed.';
return array(
'step' => $step,
'status' => self::STATUS_FAILED,
'relative' => $relative,
'command' => $command,
'exit_code' => (int) ( $data['exit_code'] ?? 1 ),
'output_tail' => (string) ( $data['output'] ?? $message ),
);
}
return array(
'step' => $step,
'status' => self::STATUS_RAN,
'relative' => $relative,
'command' => $command,
'exit_code' => 0,
'output_tail' => $result['output'],
);
}
}