-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkspaceRepositoryLifecycle.php
More file actions
882 lines (770 loc) · 31.9 KB
/
Copy pathWorkspaceRepositoryLifecycle.php
File metadata and controls
882 lines (770 loc) · 31.9 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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
<?php
/**
* Workspace repository lifecycle operations.
*
* @package DataMachineCode\Workspace
*/
namespace DataMachineCode\Workspace;
use DataMachineCode\Support\CommandSpec;
use DataMachineCode\Support\GitHubRemote;
use DataMachineCode\Support\GitRunner;
use DataMachineCode\Support\ProcessRunner;
defined('ABSPATH') || exit;
if ( ! class_exists(ProcessRunner::class) ) {
require_once dirname(__DIR__) . '/Support/ProcessRunner.php';
}
if ( ! class_exists(CommandSpec::class) ) {
require_once dirname(__DIR__) . '/Support/CommandSpec.php';
}
trait WorkspaceRepositoryLifecycle {
/**
* List repositories in the workspace.
*
* @param string|null $repo Optional primary repository name to include.
* @param string|null $type Optional checkout type filter: primary or worktree.
* @return array{success: bool, repos: array, path: string}|\WP_Error
*/
public function list_repos( ?string $repo = null, ?string $type = null ): array|\WP_Error {
$path = $this->workspace_path;
$visible = $this->require_workspace_visible();
if ( null !== $visible ) {
return $visible;
}
$repo_filter = null !== $repo && '' !== trim($repo) ? $this->parse_handle($repo)['repo'] : null;
$type_filter = null !== $type && '' !== trim($type) ? strtolower(trim($type)) : null;
if ( null !== $type_filter && ! in_array($type_filter, array( 'primary', 'worktree', 'context' ), true) ) {
return new \WP_Error('invalid_workspace_type', 'Workspace list type must be "primary", "worktree", or "context".', array( 'status' => 400 ));
}
if ( ! is_dir($path) ) {
return array(
'success' => true,
'repos' => array(),
'path' => $path,
);
}
$repos = array();
$entries = scandir($path);
if ( 'context' !== $type_filter ) {
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry ) {
continue;
}
// Skip dotfile entries (e.g. internal infra dirs like .locks).
if ( str_starts_with($entry, '.') ) {
continue;
}
$entry_path = $path . '/' . $entry;
if ( ! is_dir($entry_path) ) {
continue;
}
$git_path = $entry_path . '/.git';
$is_git = is_dir($git_path) || is_file($git_path);
$is_wt = is_file($git_path);
// A real primary or worktree always has a .git entry. Non-git
// directories are not repositories and must not be emitted as rows.
if ( ! $is_git ) {
continue;
}
$parsed = $this->parse_handle($entry);
if ( null !== $repo_filter && $parsed['repo'] !== $repo_filter ) {
continue;
}
$is_worktree = $is_wt || $parsed['is_worktree'];
if ( 'primary' === $type_filter && $is_worktree ) {
continue;
}
if ( 'worktree' === $type_filter && ! $is_worktree ) {
continue;
}
$repo_info = array(
'name' => $entry,
'path' => $entry_path,
'git' => $is_git,
'is_worktree' => $is_worktree,
'repo' => $parsed['repo'],
);
if ( $parsed['is_worktree'] ) {
$repo_info['branch_slug'] = $parsed['branch_slug'];
}
// Get git remote if available.
if ( $is_git ) {
$remote = $this->git_get_remote($entry_path);
if ( null !== $remote ) {
$repo_info['remote'] = $remote;
}
$branch = $this->git_get_branch($entry_path);
if ( null !== $branch ) {
$repo_info['branch'] = $branch;
}
if ( ! $is_worktree ) {
$repo_info['primary_freshness'] = $this->build_primary_freshness_report($entry_path, $entry);
}
}
$repos[] = $repo_info;
}
}
if ( null === $type_filter || 'context' === $type_filter ) {
foreach ( WorkspaceAliasResolver::context_repositories() as $alias => $context ) {
if ( null !== $repo_filter && $this->parse_handle( (string) ( $context['target'] ?? $alias ) )['repo'] !== $repo_filter && $alias !== $repo_filter ) {
continue;
}
$target = (string) ( $context['target'] ?? $alias );
$path = $this->workspace_path . '/' . $this->parse_handle($target)['dir_name'];
$repos[] = array(
'name' => $alias,
'path' => is_dir($path) ? $path : null,
'git' => is_dir($path . '/.git') || is_file($path . '/.git'),
'is_worktree' => false,
'is_context' => true,
'repo' => (string) ( $context['repo'] ?? $target ),
'ref' => (string) ( $context['ref'] ?? '' ),
'workspace_policy' => WorkspaceAliasResolver::policy_attestation($alias),
);
}
}
return array(
'success' => true,
'repos' => $repos,
'path' => $path,
);
}
/**
* Clone a git repository into the workspace.
*
* @param string $url Git clone URL.
* @param string|null $name Directory name override (derived from URL if null).
* @param array $options Optional clone options.
* @return array{success: bool, name?: string, path?: string, message?: string}|\WP_Error
*/
public function clone_repo( string $url, ?string $name = null, array $options = array() ): array|\WP_Error {
$visible = $this->require_workspace_visible();
if ( null !== $visible ) {
return $visible;
}
// Validate URL.
if ( empty($url) ) {
return new \WP_Error('missing_url', 'Repository URL is required.', array( 'status' => 400 ));
}
// Derive name from URL if not provided.
if ( null === $name || '' === $name ) {
$name = $this->derive_repo_name($url);
if ( null === $name ) {
return new \WP_Error('invalid_url', sprintf('Could not derive repository name from URL: %s. Use --name to specify.', $url), array( 'status' => 400 ));
}
}
// Reject @-suffixed names — those are reserved for worktrees.
if ( str_contains($name, '@') ) {
return new \WP_Error('invalid_clone_name', 'Repository names cannot contain "@". The "@<branch-slug>" suffix is reserved for worktrees (use "workspace worktree add" instead).', array( 'status' => 400 ));
}
$name = $this->sanitize_name($name);
$repo_path = $this->workspace_path . '/' . $name;
$allow_duplicate_remote = ! empty($options['allow_duplicate_remote']);
// Check if already exists.
if ( is_dir($repo_path) ) {
$existing_remote = file_exists($repo_path . '/.git') ? $this->git_get_remote($repo_path) : null;
if ( null !== $existing_remote && ! $allow_duplicate_remote && $this->normalize_git_remote_url($url) === $this->normalize_git_remote_url($existing_remote) ) {
return $this->clone_remote_exists_error(
$url,
$name,
array(
'name' => $name,
'path' => $repo_path,
'remote' => $existing_remote,
)
);
}
return $this->clone_target_exists_error($name, $repo_path);
}
// Ensure workspace exists.
$ensure = $this->ensure_exists();
if ( is_wp_error($ensure) ) {
return $ensure;
}
$existing_primary = $this->find_primary_by_remote($url, $name);
if ( null !== $existing_primary && ! $allow_duplicate_remote ) {
return $this->clone_remote_exists_error($url, $name, $existing_primary);
}
if ( ! GitRunner::supports_streaming() ) {
return GitRunner::unavailable_error('Clone workspace repository', true);
}
$partial_clone = ! (bool) ( $options['full'] ?? false ) && $this->should_use_partial_clone($url);
$progress_callback = is_callable($options['progress_callback'] ?? null) ? $options['progress_callback'] : null;
$started_at = microtime(true);
$this->emit_clone_progress(
$progress_callback,
'start',
sprintf(
'Cloning %s into %s%s.',
$url,
$repo_path,
$partial_clone ? ' using partial clone (--filter=blob:none)' : ''
),
$started_at
);
$env = $this->build_clone_environment($url, $options);
if ( is_wp_error($env) ) {
return $env;
}
$command = $this->build_clone_command($url, $repo_path, $partial_clone, $env);
if ( is_wp_error($command) ) {
return $command;
}
$result = $this->run_clone_command($command, $progress_callback, $started_at);
if ( is_wp_error($result) ) {
return $this->clone_failed_error($result, $name, $repo_path, $url);
}
// Guarantee the freshly cloned default branch tracks its remote (issue
// #833). `git clone` normally sets this, but some server/git/partial-clone
// configurations leave the default branch with no upstream, which later
// breaks `workspace git pull --allow-primary-refresh`. Establish tracking
// here so primaries are refreshable from the moment they exist.
$this->ensure_default_branch_tracking($repo_path);
$this->emit_workspace_changed('clone', $name, $name, $repo_path);
return array(
'success' => true,
'name' => $name,
'path' => $repo_path,
'message' => sprintf('Cloned %s into workspace as "%s".', $url, $name),
);
}
/**
* Materialize registered remote workspace state through the local lifecycle.
*
* @param array<string,mixed> $remote Registered remote workspace details.
* @param array<string,mixed> $options Local clone/worktree options.
* @return array<string,mixed>|\WP_Error
*/
public function materialize_remote_workspace( array $remote, array $options = array() ): array|\WP_Error {
$repo_name = trim( (string) ( $remote['repo_name'] ?? '' ) );
$url = trim( (string) ( $remote['url'] ?? '' ) );
$branch = trim( (string) ( $remote['branch'] ?? '' ) );
if ( '' === $repo_name || '' === $url ) {
return new \WP_Error('remote_workspace_materialization_invalid', 'Registered remote workspace is missing its repository identity.', array( 'status' => 400 ));
}
$primary = $this->show_repo($repo_name);
if ( is_wp_error($primary) ) {
$primary = $this->clone_repo(
$url,
$repo_name,
array(
'full' => ! empty($options['full']),
'allow_duplicate_remote' => ! empty($options['allow_duplicate_remote']),
)
);
if ( is_wp_error($primary) ) {
return $primary;
}
} elseif ( ! empty($primary['is_worktree']) || $this->normalize_git_remote_url($url) !== $this->normalize_git_remote_url((string) ( $primary['remote'] ?? '' )) ) {
return new \WP_Error('remote_workspace_materialization_primary_conflict', sprintf('Workspace primary "%s" does not match the registered remote %s.', $repo_name, $url), array( 'status' => 409 ));
}
if ( '' === $branch ) {
return array(
'success' => true,
'backend' => 'local_git',
'handle' => $repo_name,
'path' => (string) ( $primary['path'] ?? '' ),
'materialized_primary' => true,
'message' => sprintf('Materialized remote workspace primary "%s".', $repo_name),
);
}
$handle = $repo_name . '@' . $this->slugify_branch($branch);
$existing = $this->show_repo($handle);
if ( ! is_wp_error($existing) ) {
if ( (string) ( $existing['branch'] ?? '' ) !== $branch ) {
return new \WP_Error('remote_workspace_materialization_worktree_conflict', sprintf('Workspace handle "%s" is already checked out to branch "%s".', $handle, (string) ( $existing['branch'] ?? '' )), array( 'status' => 409 ));
}
return array(
'success' => true,
'backend' => 'local_git',
'handle' => $handle,
'path' => (string) ( $existing['path'] ?? '' ),
'branch' => $branch,
'already_materialized' => true,
'message' => sprintf('Remote workspace "%s" is already materialized at %s.', $handle, (string) ( $existing['path'] ?? '' )),
);
}
$remote_branch = $this->run_git((string) ( $primary['path'] ?? '' ), 'ls-remote --heads origin ' . escapeshellarg($branch));
if ( is_wp_error($remote_branch) ) {
return $remote_branch;
}
$from = '' !== trim( (string) ( $remote_branch['output'] ?? '' ) )
? 'origin/' . $branch
: ( '' !== trim( (string) ( $remote['base_ref'] ?? '' ) ) ? (string) $remote['base_ref'] : null );
$result = $this->worktree_add(
$repo_name,
$branch,
$from,
array_key_exists('inject_context', $options) ? (bool) $options['inject_context'] : true,
array_key_exists('bootstrap', $options) ? (bool) $options['bootstrap'] : true,
! empty($options['allow_stale']),
! empty($options['rebase_base']),
! empty($options['force']),
(array) ( $remote['task'] ?? array() ),
! empty($options['allow_unverified_freshness']),
array_key_exists('require_task_tracker', $options) ? (bool) $options['require_task_tracker'] : true
);
if ( is_wp_error($result) ) {
return $result;
}
$result['backend'] = 'local_git';
$result['materialized'] = true;
return $result;
}
/**
* Ensure the primary's currently checked-out default branch tracks origin.
*
* Issue #833: a primary whose default branch has no upstream tracking ref
* reports freshness `no_upstream` and cannot be refreshed via
* `workspace git pull --allow-primary-refresh`. This sets tracking right
* after clone so the primary is refreshable from the start.
*
* Best-effort and non-fatal: a failure to set tracking must not fail an
* otherwise successful clone. No-ops when the branch already tracks, when
* HEAD is detached, or when the remote lacks a same-named branch.
*
* @param string $repo_path Primary checkout path.
* @return void
*/
private function ensure_default_branch_tracking( string $repo_path ): void {
if ( ! is_dir($repo_path . '/.git') ) {
return;
}
$branch = $this->git_get_branch($repo_path);
if ( null === $branch || '' === $branch || 'HEAD' === $branch ) {
return;
}
// Already tracking? Leave it alone.
$upstream = $this->run_git($repo_path, 'rev-parse --abbrev-ref --symbolic-full-name @{upstream}');
if ( ! is_wp_error($upstream) && '' !== trim( (string) ( $upstream['output'] ?? '' )) ) {
return;
}
// Only set tracking when origin has a matching branch.
$remote_branch = $this->run_git($repo_path, 'ls-remote --heads origin ' . escapeshellarg($branch));
if ( is_wp_error($remote_branch) || '' === trim( (string) ( $remote_branch['output'] ?? '' )) ) {
return;
}
// Best-effort: ignore failure so clone success is preserved.
$this->run_git($repo_path, 'branch --set-upstream-to=' . escapeshellarg('origin/' . $branch) . ' ' . escapeshellarg($branch));
}
/**
* Build a git clone command.
*
* @param string $url Git clone URL.
* @param string $repo_path Destination path.
* @param bool $partial_clone Whether to request blobless partial clone.
* @param array<string,string>|null $env Extra process environment.
* @return CommandSpec|\WP_Error Command spec.
*/
private function build_clone_command( string $url, string $repo_path, bool $partial_clone, ?array $env ): CommandSpec|\WP_Error {
$args = array( 'git', 'clone', '--progress' );
if ( $partial_clone ) {
$args[] = '--filter=blob:none';
}
$args[] = $url;
$args[] = $repo_path;
$env = $env ?? getenv();
$env = is_array($env) ? $env : array();
$env['GIT_TERMINAL_PROMPT'] = '0';
return CommandSpec::from_argv($args, array( 'env' => $env ));
}
/**
* Build additional environment values for git clone.
*
* @param string $url Git clone URL.
* @param array $options Optional clone options.
* @return array<string,string>|null|\WP_Error Extra environment values, null for default environment, or error.
*/
private function build_clone_environment( string $url, array $options ): array|null|\WP_Error {
$auth_token_env = isset($options['auth_token_env']) && is_scalar($options['auth_token_env']) ? trim( (string) $options['auth_token_env']) : '';
if ( '' === $auth_token_env ) {
return null;
}
if ( ! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $auth_token_env) ) {
return new \WP_Error('invalid_auth_token_env', 'Clone auth token environment variable name is invalid.', array( 'status' => 400 ));
}
$token = trim( (string) getenv($auth_token_env));
if ( '' === $token ) {
return new \WP_Error('missing_auth_token_env', sprintf('Clone auth token environment variable %s is empty or unavailable.', $auth_token_env), array( 'status' => 400 ));
}
$parts = wp_parse_url($url);
$host = is_array($parts) && isset($parts['host']) ? strtolower( (string) $parts['host']) : '';
if ( '' === $host ) {
return new \WP_Error('unsupported_auth_token_url', 'Clone auth token support requires an HTTPS repository URL.', array( 'status' => 400 ));
}
$env = getenv();
if ( ! is_array($env) ) {
$env = array();
}
$env['GIT_CONFIG_COUNT'] = '1';
$env['GIT_CONFIG_KEY_0'] = sprintf('http.https://%s/.extraheader', $host);
$env['GIT_CONFIG_VALUE_0'] = 'AUTHORIZATION: bearer ' . $token;
return $env;
}
/**
* Remote HTTP(S) and SSH hosts generally support safe blobless clones; local
* paths and file URLs often do not, and are usually test fixtures anyway.
*
* @param string $url Git clone URL.
* @return bool True when a partial clone should be attempted.
*/
private function should_use_partial_clone( string $url ): bool {
return (bool) preg_match('#^(https?://|git@|ssh://)#', $url);
}
/**
* Stream a clone command to an optional progress callback.
*
* @param CommandSpec $command Command spec.
* @param callable|null $progress_callback Optional progress callback.
* @param float $started_at Clone start timestamp.
* @return array{success: true, output: string}|\WP_Error
*/
private function run_clone_command( CommandSpec $command, ?callable $progress_callback, float $started_at ): array|\WP_Error {
$result = ProcessRunner::run(
$command,
array(
'error_code' => 'clone_failed',
'poll_interval_microseconds' => 100000,
'on_output' => function ( string $chunk ) use ( $progress_callback, $started_at ): void {
$this->emit_clone_output($progress_callback, $chunk, $started_at);
},
)
);
if ( is_wp_error($result) ) {
$data = $result->get_error_data();
$exit_code = is_array($data) ? (int) ( $data['exit_code'] ?? 1 ) : 1;
$output = is_array($data) ? (string) ( $data['output'] ?? $result->get_error_message() ) : $result->get_error_message();
return new \WP_Error(
'clone_failed',
sprintf('Git clone failed (exit %d): %s', $exit_code, $output),
array(
'status' => 500,
'output' => $output,
)
);
}
return array(
'success' => true,
'output' => $result['output'],
);
}
/**
* Emit normalized clone output chunks.
*
* @param callable|null $progress_callback Optional progress callback.
* @param string $chunk Raw process output chunk.
* @param float $started_at Clone start timestamp.
*/
private function emit_clone_output( ?callable $progress_callback, string $chunk, float $started_at ): void {
$lines = preg_split('/[\r\n]+/', $chunk);
if ( ! is_array($lines) ) {
return;
}
foreach ( $lines as $line ) {
$line = trim($line);
if ( '' === $line ) {
continue;
}
$this->emit_clone_progress($progress_callback, 'git', $line, $started_at);
}
}
/**
* Emit one structured clone progress message.
*
* @param callable|null $progress_callback Optional progress callback.
* @param string $phase Progress phase.
* @param string $message Progress message.
* @param float $started_at Clone start timestamp.
*/
private function emit_clone_progress( ?callable $progress_callback, string $phase, string $message, float $started_at ): void {
if ( null === $progress_callback ) {
return;
}
$progress_callback(
array(
'phase' => $phase,
'elapsed' => max(0.0, microtime(true) - $started_at),
'message' => $message,
)
);
}
/**
* Build a recovery-focused error when a clone target exists already.
*
* @param string $name Workspace repo name.
* @param string $repo_path Target path.
* @return \WP_Error Error with remediation data.
*/
private function clone_target_exists_error( string $name, string $repo_path ): \WP_Error {
$looks_like_git = is_dir($repo_path . '/.git');
$state = $looks_like_git ? 'existing checkout' : 'partial or non-git directory';
$next_steps = array(
sprintf('Inspect the target: %s', $repo_path),
sprintf('If it is safe to discard, remove it explicitly: wp datamachine-code workspace remove %s', $name),
'Then retry the clone command.',
);
return new \WP_Error(
'repo_exists',
sprintf('Clone target already exists as %s: %s. Next steps: %s', $state, $repo_path, implode(' ', $next_steps)),
array(
'status' => 400,
'path' => $repo_path,
'state' => $state,
'next_steps' => $next_steps,
)
);
}
/**
* Add recovery guidance when the same remote already has a primary checkout.
*
* @param string $url Requested clone URL.
* @param string $name Requested workspace name.
* @param array<string,mixed> $existing Existing primary checkout summary.
* @return \WP_Error Error with remediation data.
*/
private function clone_remote_exists_error( string $url, string $name, array $existing ): \WP_Error {
$existing_name = (string) ( $existing['name'] ?? '' );
$next_steps = array(
sprintf('Reuse existing primary checkout: %s', $existing_name),
sprintf('Refresh it when needed: %s', $this->primary_refresh_command($existing_name)),
sprintf('Then create an isolated branch: wp datamachine-code workspace worktree add %s <branch>', $existing_name),
);
return new \WP_Error(
'repo_remote_exists',
sprintf('A primary checkout for %s already exists as "%s" at %s. Do not clone the same remote as "%s"; refresh/reuse the existing primary instead. Next steps: %s', $url, $existing_name, (string) ( $existing['path'] ?? '' ), $name, implode(' ', $next_steps)),
array(
'status' => 409,
'url' => $url,
'name' => $name,
'existing' => $existing,
'next_steps' => $next_steps,
)
);
}
/**
* Add recovery guidance to git clone failures.
*
* @param \WP_Error $error Clone process error.
* @param string $name Workspace repo name.
* @param string $repo_path Target path.
* @param string $url Git clone URL.
* @return \WP_Error Error with remediation data.
*/
private function clone_failed_error( \WP_Error $error, string $name, string $repo_path, string $url ): \WP_Error {
$next_steps = array(
sprintf('Confirm the repository URL is reachable: %s', $url),
sprintf('Inspect any partial target: %s', $repo_path),
sprintf('If the target is safe to discard, remove it explicitly: wp datamachine-code workspace remove %s', $name),
'Then retry the clone command.',
);
$data = (array) $error->get_error_data();
$data['path'] = $repo_path;
$data['next_steps'] = $next_steps;
$data['partial_path'] = is_dir($repo_path) ? $repo_path : null;
return new \WP_Error(
'clone_failed',
$error->get_error_message() . ' Next steps: ' . implode(' ', $next_steps),
$data
);
}
/**
* Adopt an existing primary checkout already located in the workspace.
*
* There is no persistent primary registry today; primary checkouts are
* discovered by their on-disk directory names. Adoption is therefore a
* non-destructive validation step that makes that convention explicit.
*
* @param string $path Existing checkout path.
* @param string|null $name Workspace name override (derived from basename if null).
* @return array{success: bool, name?: string, path?: string, already_adopted?: bool, message?: string}|\WP_Error
*/
public function adopt_repo( string $path, ?string $name = null ): array|\WP_Error {
$path = rtrim(trim($path), '/');
if ( '' === $path ) {
return new \WP_Error('missing_path', 'Checkout path is required.', array( 'status' => 400 ));
}
if ( ! is_dir($path) || ! is_readable($path) ) {
return new \WP_Error('adopt_path_unreadable', sprintf('Checkout path does not exist or is not readable: %s', $path), array( 'status' => 400 ));
}
$ensure = $this->ensure_exists();
if ( is_wp_error($ensure) ) {
return $ensure;
}
$validation = $this->validate_containment($path, $this->workspace_path);
if ( ! $validation['valid'] ) {
return new \WP_Error('adopt_outside_workspace', 'Only checkouts already under DATAMACHINE_WORKSPACE_PATH can be adopted.', array( 'status' => 400 ));
}
$real_path = $validation['real_path'] ?? '';
if ( '' === $real_path ) {
return new \WP_Error('adopt_path_unresolved', sprintf('Could not resolve checkout path: %s', $path), array( 'status' => 400 ));
}
$git_path = $real_path . '/.git';
if ( is_file($git_path) ) {
return new \WP_Error('adopt_linked_worktree', 'Cannot adopt a linked worktree as a primary checkout. Pass the primary checkout path instead.', array( 'status' => 400 ));
}
if ( ! is_dir($git_path) ) {
return new \WP_Error('adopt_not_git_primary', sprintf('Path is not a git primary checkout: %s', $real_path), array( 'status' => 400 ));
}
if ( null === $name || '' === trim($name) ) {
$name = basename($real_path);
}
if ( str_contains($name, '@') ) {
return new \WP_Error('invalid_adopt_name', 'Repository names cannot contain "@". The "@<branch-slug>" suffix is reserved for worktrees.', array( 'status' => 400 ));
}
$name = $this->sanitize_name($name);
if ( '' === $name ) {
return new \WP_Error('invalid_adopt_name', 'Adopted repository name is empty after sanitization.', array( 'status' => 400 ));
}
$expected_path = $this->workspace_path . '/' . $name;
if ( is_dir($expected_path) ) {
$expected_real = realpath($expected_path);
if ( false !== $expected_real && $expected_real !== $real_path ) {
return new \WP_Error('adopt_name_collision', sprintf('Workspace name "%s" already points at a different directory: %s', $name, $expected_real), array( 'status' => 400 ));
}
} else {
return new \WP_Error('adopt_requires_workspace_path', sprintf('Adoption is non-destructive: %s must already be located at %s. Move or symlink operations are intentionally not performed by v1.', $real_path, $expected_path), array( 'status' => 400 ));
}
$this->emit_workspace_changed('adopt', $name, $name, $real_path);
return array(
'success' => true,
'name' => $name,
'path' => $real_path,
'already_adopted' => true,
'message' => sprintf('Workspace checkout "%s" is already adopted at %s. No filesystem changes were made.', $name, $real_path),
);
}
/**
* Remove a repository from the workspace.
*
* @param string $handle Workspace handle.
* @return array{success: bool, message: string}|\WP_Error
*/
public function remove_repo( string $handle ): array|\WP_Error {
$parsed = $this->parse_handle($handle);
$repo_path = $this->workspace_path . '/' . $parsed['dir_name'];
if ( ! is_dir($repo_path) ) {
return new \WP_Error('repo_not_found', sprintf('Workspace handle "%s" not found.', $parsed['dir_name']), array( 'status' => 404 ));
}
// Safety: ensure path is within workspace.
$validation = $this->validate_containment($repo_path, $this->workspace_path);
if ( ! $validation['valid'] ) {
return new \WP_Error('path_traversal', $validation['message'], array( 'status' => 403 ));
}
// Refuse to remove a primary that still has live worktrees attached.
if ( ! $parsed['is_worktree'] ) {
$worktrees = $this->worktree_list($parsed['repo']);
if ( ! is_wp_error($worktrees) ) {
$linked = array_filter($worktrees['worktrees'], fn( $wt ) => ! empty($wt['is_worktree']));
if ( ! empty($linked) ) {
$slugs = array_map(fn( $wt ) => $wt['branch_slug'] ?? '?', $linked);
return new \WP_Error('has_worktrees', sprintf('Cannot remove primary "%s": linked worktrees exist (%s). Remove them first with "workspace worktree remove".', $parsed['repo'], implode(', ', $slugs)), array( 'status' => 400 ));
}
}
}
$removed = $this->remove_contained_directory_recursive($validation['real_path'], $this->workspace_path, $this->workspace_path);
if ( is_wp_error($removed) ) {
return $removed;
}
// If we removed a worktree directory but didn't go through `git worktree remove`,
// prune the registry on the primary so it doesn't keep stale entries.
if ( $parsed['is_worktree'] ) {
$primary_path = $this->get_primary_path($parsed['repo']);
if ( GitCheckout::exists($primary_path) ) {
WorkspaceMutationLock::with_repo(
$this->workspace_path,
$parsed['repo'],
fn() => $this->run_git($primary_path, 'worktree prune')
);
}
$this->worktree_inventory()->delete($parsed['dir_name']);
}
$this->emit_workspace_changed(
$parsed['is_worktree'] ? 'worktree_remove' : 'remove',
$parsed['repo'],
$parsed['dir_name'],
$repo_path
);
return array(
'success' => true,
'message' => sprintf('Removed "%s" from workspace.', $parsed['dir_name']),
);
}
/**
* Show detailed info about a workspace repo.
*
* @param string $handle Workspace handle.
* @return array{success: bool, name?: string, path?: string, branch?: string, remote?: string, commit?: string, dirty?: int}|\WP_Error
*/
public function show_repo( string $handle ): array|\WP_Error {
$requested_handle = $handle;
$context_policy = null;
$parsed = $this->parse_handle($handle);
$repo_path = $this->workspace_path . '/' . $parsed['dir_name'];
$inspection = WorkspaceTargetInspector::inspect($repo_path, $parsed['dir_name']);
if ( is_wp_error($inspection) ) {
return $inspection;
}
if ( empty($inspection['exists']) ) {
$context_policy = WorkspaceAliasResolver::context_policy_for($handle);
}
if ( null !== $context_policy ) {
$target = (string) ( $context_policy['target'] ?? $handle );
$parsed = $this->parse_handle($target);
$repo_path = $this->workspace_path . '/' . $parsed['dir_name'];
$ref = (string) ( $context_policy['ref'] ?? '' );
$inspection = WorkspaceTargetInspector::inspect($repo_path, $handle);
if ( is_wp_error($inspection) ) {
return $inspection;
}
if ( empty($inspection['exists']) ) {
return array(
'success' => true,
'name' => (string) $context_policy['alias'],
'repo' => (string) ( $context_policy['repo'] ?? $target ),
'is_worktree' => false,
'is_context' => true,
'path' => null,
'branch' => '' !== $ref ? $ref : null,
'remote' => '' !== (string) ( $context_policy['repo'] ?? '' ) ? GitHubRemote::cloneUrl( (string) $context_policy['repo'] ) : null,
'commit' => null,
'dirty' => 0,
'workspace_policy' => WorkspaceAliasResolver::policy_attestation($handle),
);
}
$handle = $target;
}
if ( empty($inspection['exists']) && null === $context_policy ) {
$resolved_handle = $this->resolve_primary_repo_name($handle);
if ( ! is_wp_error($resolved_handle) && $resolved_handle !== $handle ) {
$handle = $resolved_handle;
$parsed = $this->parse_handle($handle);
$repo_path = $this->workspace_path . '/' . $parsed['dir_name'];
$inspection = WorkspaceTargetInspector::inspect($repo_path, $parsed['dir_name']);
if ( is_wp_error($inspection) ) {
return $inspection;
}
}
}
if ( empty($inspection['exists']) ) {
return new \WP_Error('repo_not_found', sprintf('Workspace handle "%s" not found.', $requested_handle), array( 'status' => 404 ));
}
$result = array(
'success' => true,
'name' => null !== $context_policy ? (string) $context_policy['alias'] : $parsed['dir_name'],
'repo' => $parsed['repo'],
'is_worktree' => $parsed['is_worktree'],
'is_context' => null !== $context_policy,
'path' => $repo_path,
'branch' => $inspection['branch'] ?? null,
'remote' => $inspection['remote'] ?? null,
'commit' => $inspection['commit'] ?? null,
'dirty' => (int) ( $inspection['dirty'] ?? 0 ),
'primary_freshness' => ! $parsed['is_worktree'] && is_string($inspection['branch_status'] ?? null)
? $this->build_primary_freshness_report_from_status_output(( string ) $inspection['branch_status'], $parsed['dir_name'])
: null,
);
if ( null !== $context_policy ) {
$result['workspace_policy'] = WorkspaceAliasResolver::policy_attestation($handle);
}
return $result;
}
}