-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkspaceCoreUtilities.php
More file actions
1208 lines (1063 loc) · 41.3 KB
/
Copy pathWorkspaceCoreUtilities.php
File metadata and controls
1208 lines (1063 loc) · 41.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
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Core workspace path, security, and git utility helpers.
*
* @package DataMachineCode\Workspace
*/
namespace DataMachineCode\Workspace;
use DataMachine\Core\FilesRepository\FilesystemHelper;
use DataMachineCode\Support\GitRunner;
use DataMachineCode\Support\PathSecurity;
use DataMachineCode\Storage\WorktreeInventoryRepository;
defined('ABSPATH') || exit;
require_once __DIR__ . '/WorkspaceHandle.php';
trait WorkspaceCoreUtilities {
/**
* Worktree inventory repository factory.
*/
private function worktree_inventory(): WorktreeInventoryRepository {
if ( ! class_exists(WorktreeInventoryRepository::class) ) {
include_once dirname(__DIR__) . '/Storage/WorktreeInventoryRepository.php';
}
return new WorktreeInventoryRepository();
}
/**
* Resolve the workspace directory path.
*
* Priority:
* 1. DATAMACHINE_WORKSPACE_PATH constant (if defined)
* 2. /var/lib/datamachine/workspace (if writable — typical on VPS)
* 3. $HOME/.datamachine/workspace (local/macOS fallback)
* 4. sys_get_temp_dir()/datamachine/workspace (ephemeral CI/Playground fallback)
* 5. Empty string (no workspace available)
*
* @return string Workspace path or empty string if unavailable.
*/
private static function resolve_workspace_directory(): string {
if ( defined('DATAMACHINE_WORKSPACE_PATH') ) {
return rtrim(DATAMACHINE_WORKSPACE_PATH, '/');
}
$system_path = '/var/lib/datamachine/workspace';
$system_base = dirname($system_path);
$fs = FilesystemHelper::get();
$base_writable = $fs
? $fs->is_writable($system_base)
: is_writable($system_base); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
$parent_writable = ! $base_writable && ! file_exists($system_base) && (
$fs
? $fs->is_writable(dirname($system_base))
: is_writable(dirname($system_base)) // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
);
if ( $base_writable || $parent_writable ) {
return $system_path;
}
// Local/macOS fallback: $HOME/.datamachine/workspace.
// Matches the path setup.sh uses in --local mode.
$home = getenv('HOME');
if ( false !== $home && '' !== $home ) {
$home_path = rtrim($home, '/') . '/.datamachine/workspace';
$home_base = dirname($home_path);
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( is_dir($home_base) && is_writable($home_base) ) {
return $home_path;
}
// Base doesn't exist yet — check if $HOME/.datamachine can be created.
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( ! file_exists($home_base) && is_writable(dirname($home_base)) ) {
return $home_path;
}
}
$temp_path = rtrim(sys_get_temp_dir(), '/') . '/datamachine/workspace';
$temp_base = dirname($temp_path);
$web_root = defined('ABSPATH') ? realpath(ABSPATH) : false;
$temp_root = realpath(sys_get_temp_dir());
if ( false !== $temp_root
&& ( false === $web_root || 0 !== strpos($temp_root . '/', rtrim($web_root, '/') . '/') )
) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( is_dir($temp_base) && is_writable($temp_base) ) {
return $temp_path;
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
if ( ! file_exists($temp_base) && is_writable(dirname($temp_base)) ) {
return $temp_path;
}
}
return '';
}
/**
* Get the workspace base path.
*
* @return string
*/
public function get_path(): string {
return $this->workspace_path;
}
/**
* Inspect whether the configured workspace root is visible to PHP.
*
* @return array{path: string, configured: bool, is_dir: bool, is_readable: bool, scandir: string, readable: bool}
*/
public function inspect_workspace_path(): array {
$path = $this->workspace_path;
$is_dir = '' !== $path && is_dir($path);
$is_readable = '' !== $path && is_readable($path); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_readable
$entries = ( $is_dir && $is_readable ) ? scandir($path) : false;
return array(
'path' => $path,
'configured' => defined('DATAMACHINE_WORKSPACE_PATH'),
'is_dir' => $is_dir,
'is_readable' => $is_readable,
'scandir' => false === $entries ? 'failed' : 'ok',
'readable' => $is_dir && false !== $entries,
);
}
/**
* Require the configured workspace root to be visible before substrate checks.
*
* @return \WP_Error|null
*/
private function require_workspace_visible(): ?\WP_Error {
$diagnostic = $this->inspect_workspace_path();
if ( '' === $diagnostic['path'] ) {
return new \WP_Error(
'workspace_unavailable',
'Workspace unavailable: no writable path outside the web root. Define DATAMACHINE_WORKSPACE_PATH in wp-config.php, ensure /var/lib/datamachine/ is writable, ensure $HOME is set, or ensure the system temporary directory is writable.',
$this->workspace_visibility_error_data($diagnostic)
);
}
if ( ! $diagnostic['is_dir'] ) {
if ( empty($diagnostic['configured']) ) {
return null;
}
return new \WP_Error(
'workspace_path_invisible',
$this->format_workspace_visibility_message($diagnostic),
$this->workspace_visibility_error_data($diagnostic)
);
}
if ( ! $diagnostic['readable'] ) {
return new \WP_Error(
'workspace_path_unreadable',
$this->format_workspace_visibility_message($diagnostic),
$this->workspace_visibility_error_data($diagnostic)
);
}
return null;
}
/**
* Build error data for workspace visibility failures.
*
* @param array<string,mixed> $diagnostic Path visibility details.
* @return array{status: int, workspace: array<string,mixed>}
*/
private function workspace_visibility_error_data( array $diagnostic ): array {
return array(
'status' => 500,
'workspace' => $diagnostic,
);
}
/**
* Format a workspace visibility diagnostic for CLI/API callers.
*
* @param array<string,mixed> $diagnostic Path visibility details.
* @return string
*/
private function format_workspace_visibility_message( array $diagnostic ): string {
return sprintf(
'Workspace path is not accessible from PHP: %s (is_dir=%s, is_readable=%s, scandir=%s). If this is a Studio/local host path, ensure the path is mounted into the PHP runtime or update DATAMACHINE_WORKSPACE_PATH to a PHP-visible workspace.',
(string) ( $diagnostic['path'] ?? '' ),
! empty($diagnostic['is_dir']) ? 'true' : 'false',
! empty($diagnostic['is_readable']) ? 'true' : 'false',
(string) ( $diagnostic['scandir'] ?? 'failed' )
);
}
/**
* Get the full path to a workspace handle.
*
* Handles can be either a primary checkout (`<repo>`) or a worktree
* (`<repo>@<branch-slug>`). The directory name on disk equals the handle.
*
* @param string $handle Workspace handle (`<repo>` or `<repo>@<branch-slug>`).
* @return string Full filesystem path.
*/
public function get_repo_path( string $handle ): string {
$parsed = $this->parse_handle($handle);
return $this->workspace_path . '/' . $parsed['dir_name'];
}
/**
* Parse a workspace handle into its components.
*
* Accepts either:
* - `<repo>` → primary checkout
* - `<repo>@<slug>` → worktree (slug = slugified branch name)
*
* @param string $handle Workspace handle.
* @return array{repo: string, branch_slug: string|null, is_worktree: bool, dir_name: string}
*/
public function parse_handle( string $handle ): array {
return WorkspaceHandle::parse($handle)->to_array();
}
/**
* Normalize an optional worktree cleanup/reconciliation scope.
*
* @param string|null $scope Optional primary repo or worktree handle.
* @return array{argument: string, repo: string, handle: string|null}|null|\WP_Error
*/
protected function normalize_worktree_operation_scope( ?string $scope ): array|null|\WP_Error {
$scope = null === $scope ? '' : trim($scope);
if ( '' === $scope ) {
return null;
}
$parsed = $this->parse_handle($scope);
if ( '' === $parsed['repo'] || '' === $parsed['dir_name'] ) {
return new \WP_Error('invalid_worktree_scope', sprintf('Worktree cleanup scope "%s" must be a primary repo or worktree handle.', $scope), array( 'status' => 400 ));
}
return array(
'argument' => $scope,
'repo' => $parsed['repo'],
'handle' => $parsed['is_worktree'] ? $parsed['dir_name'] : null,
);
}
/**
* Whether an inventory/worktree row matches a normalized operation scope.
*
* @param array<string,mixed> $row Inventory or evidence row.
* @param array{argument: string, repo: string, handle: string|null}|null $scope Optional normalized scope.
* @return bool
*/
protected function worktree_row_matches_operation_scope( array $row, ?array $scope ): bool {
if ( null === $scope ) {
return true;
}
$handle = (string) ( $row['handle'] ?? $row['name'] ?? '' );
if ( null !== $scope['handle'] ) {
return $handle === $scope['handle'];
}
$repo = (string) ( $row['repo'] ?? '' );
if ( '' === $repo && '' !== $handle ) {
$repo = $this->parse_handle($handle)['repo'];
}
return $repo === $scope['repo'];
}
/**
* Build the positional CLI scope segment for continuation commands.
*
* @param array{argument: string, repo: string, handle: string|null}|null $scope Optional normalized scope.
* @return string
*/
protected function worktree_operation_scope_cli_arg( ?array $scope ): string {
if ( null === $scope ) {
return '';
}
$argument = (string) $scope['argument'];
return ' ' . ( preg_match('/^[A-Za-z0-9._@-]+$/', $argument) ? $argument : escapeshellarg($argument) );
}
/**
* Require file-operation callers to name a workspace handle explicitly.
*
* @param string $handle Workspace handle from ability input.
* @return array{repo: string, branch_slug: string|null, is_worktree: bool, dir_name: string}|\WP_Error
*/
public function require_explicit_workspace_handle( string $handle ): array|\WP_Error {
$handle = trim($handle);
if ( '' === $handle ) {
return new \WP_Error(
'missing_workspace_handle',
'Workspace file operations require an explicit repo/worktree handle; workspace-root access is not allowed.',
array( 'status' => 400 )
);
}
$parsed = $this->parse_handle($handle);
if ( '' === $parsed['dir_name'] || '' === $parsed['repo'] ) {
return new \WP_Error(
'invalid_workspace_handle',
'Workspace file operations require a valid repo/worktree handle; workspace-root access is not allowed.',
array( 'status' => 400 )
);
}
return $parsed;
}
/**
* Enforce the default read-only policy for primary checkout mutations.
*
* @param string $handle Workspace handle.
* @param bool $allow Whether primary checkout mutation is explicitly allowed.
* @return array{repo: string, branch_slug: string|null, is_worktree: bool, dir_name: string}|\WP_Error
*/
public function ensure_workspace_mutation_allowed( string $handle, bool $allow = false, string $allow_guidance = 'Pass allow_primary_mutation=true to operate on it' ): array|\WP_Error {
$parsed = $this->require_explicit_workspace_handle($handle);
if ( is_wp_error($parsed) ) {
return $parsed;
}
if ( $parsed['is_worktree'] || $allow ) {
return $parsed;
}
return new \WP_Error(
'primary_mutation_blocked',
sprintf(
'Primary checkout "%s" is read-only by default. %s, or use a worktree handle (e.g. %s@<branch-slug>).',
$parsed['repo'],
$allow_guidance,
$parsed['repo']
),
array( 'status' => 403 )
);
}
/**
* Convert a branch name to a filesystem-safe slug.
*
* Slashes become dashes (`fix/foo-bar` → `fix-foo-bar`). Anything else
* outside [A-Za-z0-9._-] is stripped.
*
* @param string $branch Branch name.
* @return string Slug (empty if branch is invalid).
*/
public function slugify_branch( string $branch ): string {
$branch = trim($branch);
if ( '' === $branch ) {
return '';
}
$slug = str_replace('/', '-', $branch);
return $this->sanitize_slug($slug);
}
/**
* Recover blank worktree identity fields from trusted stored metadata.
*
* @param array<string,mixed> $wt Worktree row.
* @return array<string,mixed>
*/
private function recover_worktree_identity_from_metadata( array $wt ): array {
$handle = (string) ( $wt['handle'] ?? '' );
$repo = (string) ( $wt['repo'] ?? '' );
$branch = (string) ( $wt['branch'] ?? '' );
$path = (string) ( $wt['path'] ?? '' );
$metadata = is_array($wt['metadata'] ?? null) ? (array) $wt['metadata'] : array();
$parsed = '' !== $handle ? $this->parse_handle($handle) : array(
'repo' => '',
'branch_slug' => null,
'is_worktree' => false,
'dir_name' => '',
);
$stored = array(
'repo' => isset($metadata['repo']) ? trim( (string) $metadata['repo'] ) : '',
'branch' => isset($metadata['branch']) ? trim( (string) $metadata['branch'] ) : '',
'path' => isset($metadata['path']) ? rtrim(trim( (string) $metadata['path'] ), '/') : '',
);
$conflicts = array();
$hydrated = array();
if ( '' === $repo && '' !== $stored['repo'] ) {
if ( $parsed['repo'] === $stored['repo'] ) {
$repo = $stored['repo'];
$hydrated[] = 'repo';
} else {
$conflicts['repo'] = array(
'reason' => 'metadata_repo_does_not_match_handle',
'handle_repo' => $parsed['repo'],
'metadata' => $stored['repo'],
);
}
} elseif ( '' !== $repo && '' !== $stored['repo'] && $repo !== $stored['repo'] ) {
$conflicts['repo'] = array(
'reason' => 'metadata_repo_does_not_match_row',
'row' => $repo,
'metadata' => $stored['repo'],
);
}
if ( '' === $branch && '' !== $stored['branch'] ) {
$branch_slug = (string) ( $parsed['branch_slug'] ?? '' );
if ( '' !== $branch_slug && $this->slugify_branch($stored['branch']) === $branch_slug ) {
$branch = $stored['branch'];
$hydrated[] = 'branch';
} else {
$conflicts['branch'] = array(
'reason' => 'metadata_branch_does_not_match_handle_slug',
'handle_slug' => $branch_slug,
'metadata' => $stored['branch'],
'metadata_slug' => $this->slugify_branch($stored['branch']),
);
}
} elseif ( '' !== $branch && '' !== $stored['branch'] && $branch !== $stored['branch'] ) {
$conflicts['branch'] = array(
'reason' => 'metadata_branch_does_not_match_row',
'row' => $branch,
'metadata' => $stored['branch'],
);
}
if ( '' === $path && '' !== $stored['path'] ) {
$stored_basename = basename($stored['path']);
$stored_real = realpath($stored['path']);
$stored_real = false !== $stored_real ? $stored_real : $stored['path'];
$workspace_real = realpath($this->workspace_path);
$workspace_real = false !== $workspace_real ? $workspace_real : $this->workspace_path;
if ( $stored_basename === $handle && str_starts_with(rtrim($stored_real, '/'), rtrim($workspace_real, '/') . '/') ) {
$path = $stored['path'];
$hydrated[] = 'path';
} else {
$conflicts['path'] = array(
'reason' => 'metadata_path_does_not_match_workspace_handle',
'handle' => $handle,
'metadata' => $stored['path'],
'metadata_basename' => $stored_basename,
);
}
} elseif ( '' !== $path && '' !== $stored['path'] ) {
$row_path = rtrim($path, '/');
$metadata_path = rtrim($stored['path'], '/');
$row_real = realpath($row_path);
$row_real = false !== $row_real ? $row_real : $row_path;
$metadata_real = realpath($metadata_path);
$metadata_real = false !== $metadata_real ? $metadata_real : $metadata_path;
if ( rtrim($row_real, '/') !== rtrim($metadata_real, '/') ) {
$conflicts['path'] = array(
'reason' => 'metadata_path_does_not_match_row',
'row' => $row_path,
'metadata' => $metadata_path,
);
}
}
return array(
'repo' => $repo,
'branch' => $branch,
'path' => $path,
'hydrated_fields' => $hydrated,
'conflicts' => $conflicts,
'stored_identity' => array_filter($stored, fn( $value ) => '' !== $value),
'detached_branch' => '' === (string) ( $wt['branch'] ?? '' ) && in_array('branch', $hydrated, true),
);
}
/**
* Sanitize a branch slug. Allows alphanumerics, dots, dashes, underscores.
*
* @param string $slug Raw slug.
* @return string
*/
private function sanitize_slug( string $slug ): string {
$slug = preg_replace('/[^a-zA-Z0-9._-]/', '', $slug);
// Collapse runs of dashes for readability.
$slug = preg_replace('/-{2,}/', '-', (string) $slug);
return trim( (string) $slug, '-.');
}
/**
* Get the primary checkout path for a repo.
*
* @param string $repo Repository name (no @-suffix).
* @return string
*/
public function get_primary_path( string $repo ): string {
$resolved = $this->resolve_primary_repo_name($repo);
if ( is_wp_error($resolved) ) {
return $this->workspace_path . '/' . $this->sanitize_name($repo);
}
return $this->workspace_path . '/' . $resolved;
}
/**
* Resolve a primary repo argument to the canonical workspace directory name.
*
* @param string $repo Primary handle, git URL, or local checkout path.
* @return string|\WP_Error Canonical primary handle or validation error.
*/
public function resolve_primary_repo_name( string $repo ): string|\WP_Error {
$repo = trim($repo);
if ( '' === $repo ) {
return new \WP_Error('invalid_repo', 'Repository name is required.', array( 'status' => 400 ));
}
if ( str_contains($repo, '@') && ! $this->looks_like_git_url($repo) ) {
return new \WP_Error('invalid_repo', 'Worktree handles cannot be used where a primary repository is required.', array( 'status' => 400 ));
}
if ( $this->looks_like_git_url($repo) ) {
$existing = $this->find_primary_by_remote($repo);
if ( null !== $existing ) {
return $existing['name'];
}
return new \WP_Error('unsupported_workspace_repo_argument', sprintf('Repository URL "%s" does not match an existing local primary checkout. Use a registered primary handle or run workspace clone first.', $repo), array( 'status' => 404 ));
}
if ( $this->looks_like_path_argument($repo) ) {
return $this->resolve_primary_repo_name_from_path($repo);
}
if ( str_contains($repo, '/') || str_contains($repo, '\\') ) {
return new \WP_Error('unsupported_workspace_repo_argument', sprintf('Repository argument "%s" is not a primary workspace handle. Use the local primary handle, or pass a URL/path that matches an existing local primary checkout.', $repo), array( 'status' => 400 ));
}
$sanitized = $this->sanitize_name($repo);
if ( '' === $sanitized ) {
return new \WP_Error('invalid_repo', sprintf('Repository argument "%s" did not produce a valid workspace handle.', $repo), array( 'status' => 400 ));
}
return $sanitized;
}
/**
* Resolve a local path argument to an existing primary handle.
*
* @param string $path Local checkout path.
* @return string|\WP_Error Canonical primary handle or validation error.
*/
private function resolve_primary_repo_name_from_path( string $path ): string|\WP_Error {
$path = rtrim($path, '/');
$expanded_path = str_starts_with($path, '~/') ? rtrim( (string) getenv('HOME'), '/') . substr($path, 1) : $path;
$real_path = realpath($expanded_path);
$workspace = realpath($this->workspace_path);
$resolved_path = false !== $real_path ? $real_path : $expanded_path;
if ( false !== $workspace && str_starts_with(rtrim($resolved_path, '/') . '/', rtrim($workspace, '/') . '/') ) {
$name = basename($resolved_path);
if ( '' !== $name && ! str_contains($name, '@') && is_dir($resolved_path) && ( is_dir($resolved_path . '/.git') || is_file($resolved_path . '/.git') ) ) {
return $name;
}
}
$remote = ( is_dir($resolved_path) && ( is_dir($resolved_path . '/.git') || is_file($resolved_path . '/.git') ) ) ? $this->git_get_remote($resolved_path) : null;
if ( null !== $remote ) {
$existing = $this->find_primary_by_remote($remote);
if ( null !== $existing ) {
return $existing['name'];
}
}
return new \WP_Error('unsupported_workspace_repo_argument', sprintf('Repository path "%s" does not resolve to an existing local primary checkout. Use a registered primary handle or run workspace clone/adopt first.', $path), array( 'status' => 404 ));
}
/**
* Whether a repo argument looks like a git URL.
*/
private function looks_like_git_url( string $value ): bool {
return (bool) preg_match('#^(?:https?|ssh|git)://#i', $value) || (bool) preg_match('/^[^@\s]+@[^:\s]+:.+$/', $value);
}
/**
* Whether a repo argument looks like a filesystem path.
*/
private function looks_like_path_argument( string $value ): bool {
return str_starts_with($value, '/') || str_starts_with($value, './') || str_starts_with($value, '../') || str_starts_with($value, '~/');
}
/**
* Normalize a git remote URL for same-repository comparisons.
*
* @param string $url Git remote URL.
* @return string Normalized URL-ish key.
*/
private function normalize_git_remote_url( string $url ): string {
$url = trim($url);
$url = rtrim($url, '/');
$url = preg_replace('/\.git$/', '', $url) ?? $url;
if ( preg_match('/^([^@\s]+)@([^:\s]+):(.+)$/', $url, $matches) ) {
$url = 'ssh://' . $matches[2] . '/' . $matches[3];
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- wp_parse_url() is unavailable in pure-PHP smoke tests.
$parts = function_exists('wp_parse_url') ? wp_parse_url($url) : parse_url($url);
if ( is_array($parts) && ! empty($parts['host']) ) {
$host = strtolower( (string) $parts['host']);
$path = trim( (string) ( $parts['path'] ?? '' ), '/');
$path = preg_replace('/\.git$/', '', $path) ?? $path;
return strtolower($host . '/' . $path);
}
return strtolower($url);
}
/**
* Find an existing primary checkout whose origin remote matches the URL.
*
* @param string $url Git remote URL to match.
* @param string $exclude_name Optional primary name to ignore.
* @return array{name: string, path: string, remote: string}|null
*/
private function find_primary_by_remote( string $url, string $exclude_name = '' ): ?array {
$needle = $this->normalize_git_remote_url($url);
if ( '' === $needle || ! is_dir($this->workspace_path) ) {
return null;
}
$entries = scandir($this->workspace_path);
if ( ! is_array($entries) ) {
return null;
}
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry || str_contains($entry, '@') || $entry === $exclude_name ) {
continue;
}
$path = $this->workspace_path . '/' . $entry;
if ( ! is_dir($path) || ! file_exists($path . '/.git') ) {
continue;
}
$remote = $this->git_get_remote($path);
if ( null !== $remote && $needle === $this->normalize_git_remote_url($remote) ) {
return array(
'name' => $entry,
'path' => $path,
'remote' => $remote,
);
}
}
return null;
}
/**
* Build local-ref freshness metadata for a primary checkout.
*
* This intentionally does not fetch. Read-only status/list/hygiene calls should
* reveal stale local remote refs without mutating repo state or requiring auth.
*
* @param string $repo_path Primary checkout path.
* @param string $handle Workspace primary handle.
* @return array<string,mixed>|null
*/
private function build_primary_freshness_report( string $repo_path, string $handle ): ?array {
if ( ! file_exists($repo_path . '/.git') ) {
return null;
}
$status_result = $this->run_git($repo_path, 'status --porcelain=v1 --branch --untracked-files=no');
if ( is_wp_error($status_result) ) {
return array(
'status' => 'unknown',
'branch' => null,
'upstream' => null,
'behind' => null,
'ahead' => null,
'detached' => false,
'local_refs' => true,
'fetch_checked' => false,
);
}
return $this->build_primary_freshness_report_from_status_output((string) ( $status_result['output'] ?? '' ), $handle);
}
/**
* Build primary freshness metadata from an already-bounded local status probe.
*
* @return array<string,mixed>
*/
private function build_primary_freshness_report_from_status_output( string $status_output, string $handle ): array {
$header = strtok($status_output, "\n");
$header = false === $header ? '' : trim($header);
$branch = null;
$detached = false;
$upstream = null;
$behind = 0;
$ahead = 0;
$status = 'unknown';
if ( preg_match('/^## HEAD \(no branch\)/', $header) ) {
$detached = true;
$status = 'detached';
} elseif ( preg_match('/^## (.+?)(?:\.\.\.([^\s\[]+))?(?: \[(.+)\])?$/', $header, $matches) ) {
$branch = trim( (string) $matches[1]);
$upstream = isset($matches[2]) && '' !== $matches[2] ? trim( (string) $matches[2]) : null;
$divergence = isset($matches[3]) ? (string) $matches[3] : '';
if ( preg_match('/behind (\d+)/', $divergence, $behind_match) ) {
$behind = (int) $behind_match[1];
}
if ( preg_match('/ahead (\d+)/', $divergence, $ahead_match) ) {
$ahead = (int) $ahead_match[1];
}
if ( null === $upstream ) {
$status = 'no_upstream';
} elseif ( $behind > 0 && $ahead > 0 ) {
$status = 'diverged';
} elseif ( $behind > 0 ) {
$status = 'stale';
} elseif ( $ahead > 0 ) {
$status = 'ahead';
} else {
$status = 'current';
}
}
$report = array(
'status' => $status,
'branch' => $branch,
'upstream' => $upstream,
'behind' => null === $upstream ? null : $behind,
'ahead' => null === $upstream ? null : $ahead,
'detached' => $detached,
'local_refs' => true,
'fetch_checked' => false,
);
if ( $this->primary_freshness_needs_refresh($status) ) {
$report['suggested_command'] = $this->primary_refresh_command($handle);
}
return $report;
}
/**
* Build the canonical command for refreshing a primary checkout.
*
* @param string $handle Primary workspace handle.
* @return string WP-CLI command.
*/
private function primary_refresh_command( string $handle ): string {
return sprintf('wp datamachine-code workspace git pull %s --allow-primary-refresh', $handle);
}
/**
* Guard reads from stale or otherwise unsafe primary checkouts.
*
* @param string $handle Workspace handle.
* @param bool $allow_stale_primary Whether stale primary reads are explicitly allowed.
* @return true|\WP_Error
*/
public function ensure_primary_read_allowed( string $handle, bool $allow_stale_primary = false ): true|\WP_Error {
$parsed = $this->parse_handle($handle);
if ( $parsed['is_worktree'] || $allow_stale_primary ) {
return true;
}
$repo_path = $this->workspace_path . '/' . $parsed['dir_name'];
if ( ! is_dir($repo_path) ) {
return true;
}
$freshness = $this->build_primary_freshness_report($repo_path, $parsed['dir_name']);
if ( ! is_array($freshness) ) {
return true;
}
$status = (string) ( $freshness['status'] ?? 'unknown' );
if ( ! in_array($status, array( 'stale', 'diverged', 'detached', 'unknown', 'no_upstream', 'ahead' ), true) ) {
return true;
}
$behind_value = $freshness['behind'] ?? null;
$ahead_value = $freshness['ahead'] ?? null;
return new \WP_Error(
'stale_primary_read_blocked',
sprintf(
'Primary checkout "%s" is %s and may not reflect the current remote. Refresh with `%s`, read a fresh worktree, or pass allow_stale_primary=true to opt in. Behind: %s. Ahead: %s.',
$parsed['repo'],
$status,
(string) ( $freshness['suggested_command'] ?? $this->primary_refresh_command($parsed['dir_name']) ),
null === $behind_value ? '-' : (string) $behind_value,
null === $ahead_value ? '-' : (string) $ahead_value
),
array(
'status' => 409,
'primary_freshness' => $freshness,
)
);
}
/**
* Whether a primary freshness status needs a pull/reconciliation refresh.
*
* @param string $status Freshness status.
* @return bool True when refresh guidance should be shown.
*/
private function primary_freshness_needs_refresh( string $status ): bool {
return in_array($status, array( 'stale', 'diverged' ), true);
}
/**
* Whether a primary freshness status should be surfaced in hygiene attention.
*
* @param string $status Freshness status.
* @return bool True when attention should be shown.
*/
private function primary_freshness_needs_attention( string $status ): bool {
return in_array($status, array( 'stale', 'diverged', 'detached', 'no_upstream', 'unknown' ), true);
}
/**
* Ensure the workspace directory exists with correct permissions.
*
* @return array{success: bool, path: string, created?: bool}|\WP_Error
*/
public function ensure_exists(): array|\WP_Error {
$path = $this->workspace_path;
if ( '' === $path ) {
$visible = $this->require_workspace_visible();
return null !== $visible ? $visible : new \WP_Error('workspace_unavailable', 'Workspace unavailable: no writable path outside the web root.', array( 'status' => 500 ));
}
if ( is_dir($path) ) {
$visible = $this->require_workspace_visible();
if ( null !== $visible ) {
return $visible;
}
return array(
'success' => true,
'path' => $path,
'created' => false,
);
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
$created = wp_mkdir_p($path);
if ( ! $created ) {
return new \WP_Error('workspace_create_failed', sprintf('Failed to create workspace directory: %s', $path), array( 'status' => 500 ));
}
// Set permissions for multi-user access (web server group).
$this->ensure_group_permissions($path);
// Add .htaccess to block web access if inside web root.
$this->protect_directory($path);
return array(
'success' => true,
'path' => $path,
'created' => true,
);
}
/**
* Validate that a target path is contained within a parent directory.
*
* Public security primitive — used by WorkspaceReader and WorkspaceWriter
* to enforce path containment before (and after) file I/O. Uses realpath()
* for symlink-safe resolution, so the target must exist on disk.
*
* For pre-write validation of non-existent files, use has_traversal()
* checks on the relative path first, then call this method post-write
* to verify the file landed where expected.
*
* @param string $target Path to validate.
* @param string $container Parent directory that must contain the target.
* @return array{valid: bool, real_path?: string, message?: string}
*/
public function validate_containment( string $target, string $container ): array {
return PathSecurity::validateContainment($target, $container);
}
/**
* Recursively remove an existing directory after validating containment.
*
* The target must be a real directory inside, but not equal to, the container.
* Symlinks are unlinked as entries and never traversed.
*
* @param string $absolute Absolute directory path to remove.
* @param string $container Parent directory that must contain the target.
* @param string|null $relative_base Base path used to report deleted relative paths.
* @return array<int,string>|\WP_Error
*/
protected function remove_contained_directory_recursive( string $absolute, string $container, ?string $relative_base = null ): array|\WP_Error {
$validation = $this->validate_containment($absolute, $container);
if ( ! $validation['valid'] ) {
return new \WP_Error('path_traversal', (string) ( $validation['message'] ?? 'Path traversal detected. Access denied.' ), array( 'status' => 403 ));
}
$container_real = realpath($container);
$target_real = (string) ( $validation['real_path'] ?? '' );
if ( false === $container_real || '' === $target_real || $target_real === $container_real ) {
return new \WP_Error('unsafe_delete_root', sprintf('Refusing to recursively delete container root: %s', $absolute), array( 'status' => 403 ));
}
if ( ! is_dir($target_real) || is_link($absolute) ) {
return new \WP_Error('not_a_directory', sprintf('Recursive delete target is not a directory: %s', $absolute), array( 'status' => 400 ));
}
$relative_base_real = realpath($relative_base ?? $container);
if ( false === $relative_base_real ) {
$relative_base_real = $container_real;
}
$deleted = array();
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Failure is converted into a WP_Error below.
$entries = @scandir($target_real);
if ( false === $entries ) {
return new \WP_Error('scandir_failed', sprintf('Failed to read directory: %s', $target_real), array( 'status' => 500 ));
}
foreach ( $entries as $entry ) {
if ( '.' === $entry || '..' === $entry ) {
continue;
}
$child = $target_real . '/' . $entry;
if ( is_dir($child) && ! is_link($child) ) {
$nested = $this->remove_contained_directory_recursive($child, $container_real, $relative_base_real);
if ( is_wp_error($nested) ) {
return $nested;
}
$deleted = array_merge($deleted, $nested);
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
if ( ! unlink($child) ) {
return new \WP_Error('delete_failed', sprintf('Failed to delete file: %s', $child), array( 'status' => 500 ));
}
$deleted[] = ltrim(substr($child, strlen($relative_base_real)), '/');
}
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
if ( ! rmdir($target_real) ) {
return new \WP_Error('delete_failed', sprintf('Failed to remove directory: %s', $target_real), array( 'status' => 500 ));
}
$deleted[] = ltrim(substr($target_real, strlen($relative_base_real)), '/');
return $deleted;
}
/**
* Derive a repo name from a git URL.
*
* @param string $url Git URL.
* @return string|null Derived name or null.
*/
protected function derive_repo_name( string $url ): ?string {
// Handle https://github.com/org/repo.git and git@github.com:org/repo.git
$name = basename($url);
$name = preg_replace('/\.git$/', '', $name);
$name = $this->sanitize_name($name);
return ( '' !== $name ) ? $name : null;
}
/**
* Sanitize a directory name for use in the workspace.
*
* @param string $name Raw name.
* @return string Sanitized name (alphanumeric, hyphens, underscores, dots).
*/
private function sanitize_name( string $name ): string {
return preg_replace('/[^a-zA-Z0-9._-]/', '', $name);
}
/**
* Run a git command in a repository.
*