-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsmoke-gitsync.php
More file actions
587 lines (530 loc) · 29.1 KB
/
Copy pathsmoke-gitsync.php
File metadata and controls
587 lines (530 loc) · 29.1 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
<?php
/**
* Pure-PHP smoke for the API-first GitSync.
*
* Zero git binary, zero network: GitHub API responses are mocked via
* wp_remote_request, and local file I/O happens inside a scratch temp
* directory that plays the role of ABSPATH. The same harness covers
* Phase 1 (bind/pull/status/list/unbind) and Phase 2 (submit/push/
* policy-update) because the API-first rebuild unifies them.
*
* Run: php tests/smoke-gitsync.php
*/
declare( strict_types=1 );
namespace {
if (! defined('ABSPATH') ) {
$scratch = sys_get_temp_dir() . '/dmc-gitsync-api-' . getmypid();
@mkdir($scratch, 0755, true);
define('ABSPATH', $scratch . '/');
}
if (! defined('WP_CONTENT_DIR') ) {
define('WP_CONTENT_DIR', rtrim($scratch, '/') . '-content');
}
$GLOBALS['__dmc_options'] = array();
$GLOBALS['__dmc_http_mock'] = array();
$GLOBALS['__dmc_http_capture'] = array();
if (! class_exists('WP_Error') ) {
class WP_Error
{
public string $code;
public string $message;
public array $data;
public function __construct( string $code = '', string $message = '', array $data = array() )
{
$this->code = $code;
$this->message = $message;
$this->data = $data;
}
public function get_error_code(): string
{
return $this->code;
}
public function get_error_message(): string
{
return $this->message;
}
}
}
if (! function_exists('is_wp_error') ) {
function is_wp_error( $thing ): bool
{
return $thing instanceof \WP_Error;
}
}
if (! function_exists('wp_mkdir_p') ) {
function wp_mkdir_p( string $path ): bool
{
return is_dir($path) || mkdir($path, 0755, true);
}
}
if (! function_exists('get_option') ) {
function get_option( string $name, $default = false )
{
return $GLOBALS['__dmc_options'][ $name ] ?? $default;
}
}
if (! function_exists('update_option') ) {
function update_option( string $name, $value, $autoload = null ): bool
{
$GLOBALS['__dmc_options'][ $name ] = $value;
return true;
}
}
if (! function_exists('wp_json_encode') ) {
function wp_json_encode( $data, int $options = 0 )
{
return json_encode($data, $options);
}
}
if (! function_exists('add_query_arg') ) {
function add_query_arg( array $args, string $url ): string
{
$qs = http_build_query($args);
return $url . ( str_contains($url, '?') ? '&' : '?' ) . $qs;
}
}
if (! function_exists('wp_remote_request') ) {
function wp_remote_request( string $url, array $args = array() )
{
$method = strtoupper($args['method'] ?? 'GET');
$GLOBALS['__dmc_http_capture'][] = array(
'url' => $url,
'method' => $method,
'body' => $args['body'] ?? null,
'headers' => $args['headers'] ?? array(),
);
// Match on "METHOD <url-without-query>" first, then on exact URL
// with query so tests can be specific when needed.
$clean_url = strtok($url, '?');
$keys = array(
$method . ' ' . $url,
$method . ' ' . $clean_url,
);
foreach ( $keys as $key ) {
if (isset($GLOBALS['__dmc_http_mock'][ $key ]) ) {
$mock = $GLOBALS['__dmc_http_mock'][ $key ];
// Allow mocks to be callables for dynamic responses.
if (is_callable($mock) ) {
return $mock($url, $args);
}
return $mock;
}
}
return array(
'response' => array( 'code' => 404 ),
'body' => json_encode(array( 'message' => 'Not mocked: ' . $method . ' ' . $clean_url )),
);
}
}
if (! function_exists('wp_remote_get') ) {
function wp_remote_get( string $url, array $args = array() )
{
$args['method'] = 'GET';
return wp_remote_request($url, $args);
}
}
if (! function_exists('wp_remote_retrieve_response_code') ) {
function wp_remote_retrieve_response_code( $response ): int
{
return (int) ( $response['response']['code'] ?? 0 );
}
}
if (! function_exists('wp_remote_retrieve_body') ) {
function wp_remote_retrieve_body( $response ): string
{
return (string) ( $response['body'] ?? '' );
}
}
// Stub GitHubAbilities — real class has too many dependencies to load
// here. We mirror just the static surface GitSync's path calls.
if (! class_exists('\DataMachineCode\Abilities\GitHubAbilities') ) {
eval(
'namespace DataMachineCode\\Abilities;
class GitHubAbilities {
public static function getPat(): string { return "test-pat"; }
public static function apiGet( string $url, array $query, string $pat ) {
if ( ! empty( $query ) ) { $url = add_query_arg( $query, $url ); }
$resp = wp_remote_get( $url, array( "headers" => array( "Authorization" => "token " . $pat ) ) );
$code = (int) wp_remote_retrieve_response_code( $resp );
$body = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
if ( $code >= 400 ) {
$err_code = 404 === $code ? "github_not_found" : "github_api_error";
return new \\WP_Error( $err_code, is_array( $body ) && isset( $body["message"] ) ? (string) $body["message"] : "stub error", array( "status" => $code ) );
}
return array( "success" => true, "data" => $body );
}
public static function apiRequest( string $method, string $url, array $body, string $pat ) {
$resp = wp_remote_request( $url, array( "method" => $method, "headers" => array( "Authorization" => "token " . $pat ), "body" => json_encode( $body ) ) );
$code = (int) wp_remote_retrieve_response_code( $resp );
$decoded = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
if ( $code >= 400 ) {
$err_code = 404 === $code ? "github_not_found" : "github_api_error";
return new \\WP_Error( $err_code, is_array( $decoded ) && isset( $decoded["message"] ) ? (string) $decoded["message"] : "stub error", array( "status" => $code ) );
}
return array( "success" => true, "data" => $decoded );
}
}'
);
}
include __DIR__ . '/../inc/Support/PathSecurity.php';
include __DIR__ . '/../inc/Support/GitHubRemote.php';
include __DIR__ . '/../inc/GitSync/GitSyncBinding.php';
include __DIR__ . '/../inc/GitSync/GitSyncRegistry.php';
include __DIR__ . '/../inc/GitSync/GitSyncFetcher.php';
include __DIR__ . '/../inc/GitSync/GitSyncProposer.php';
include __DIR__ . '/../inc/GitSync/GitSync.php';
$failures = 0;
$total = 0;
$assert = function ( $cond, string $message ) use ( &$failures, &$total ): void {
$total++;
if ($cond ) { echo " ✓ {$message}\n"; return;
}
$failures++;
echo " ✗ {$message}\n";
};
register_shutdown_function(fn() => is_dir($scratch) && exec('rm -rf ' . escapeshellarg($scratch)));
echo "GitSync API-first — smoke\n";
echo "Scratch ABSPATH: " . ABSPATH . "\n\n";
// Helper: build a git-blob SHA for mocked tree responses.
$blob_sha = fn( string $content ): string => sha1('blob ' . strlen($content) . "\0" . $content);
// =========================================================================
// 1. Input validation at bind time.
// =========================================================================
echo "Input validation\n";
$gs = new \DataMachineCode\GitSync\GitSync();
$r = $gs->bind(array( 'slug' => 'Bad Slug!', 'local_path' => '/x/', 'remote_url' => 'https://github.com/a/b' ));
$assert(is_wp_error($r) && 'invalid_slug' === $r->get_error_code(), 'rejects invalid slug');
$r = $gs->bind(array( 'slug' => 's', 'local_path' => '/x/', 'remote_url' => 'https://gitlab.com/a/b' ));
$assert(is_wp_error($r) && 'invalid_remote_url' === $r->get_error_code(), 'rejects non-GitHub remote');
$r = $gs->bind(array( 'slug' => 's', 'local_path' => '/../etc/', 'remote_url' => 'https://github.com/a/b' ));
$assert(is_wp_error($r) && 'path_traversal' === $r->get_error_code(), 'rejects traversal in local_path');
$r = $gs->bind(array( 'slug' => 's', 'local_path' => '/.env/', 'remote_url' => 'https://github.com/a/b' ));
$assert(is_wp_error($r) && 'sensitive_path' === $r->get_error_code(), 'rejects sensitive local_path');
// =========================================================================
// 2. Bind (registry only — no HTTP, no disk).
// =========================================================================
echo "\nBind\n";
$bound = $gs->bind(
array(
'slug' => 'wiki',
'local_path' => '/content/wiki/',
'remote_url' => 'https://github.com/Automattic/a8c-wiki-woocommerce',
)
);
$assert(! is_wp_error($bound), 'bind succeeded');
$assert(false === is_dir(ABSPATH . 'content/wiki/'), 'bind did not create directory');
$content_bound = $gs->bind(
array(
'slug' => 'wp-content-binding',
'local_path' => '/wp-content/uploads/wiki/',
'remote_url' => 'https://github.com/Automattic/a8c-wiki-woocommerce',
)
);
$assert(! is_wp_error($content_bound), 'wp-content bind succeeded');
$content_binding = ( new \DataMachineCode\GitSync\GitSyncRegistry() )->get('wp-content-binding');
$assert($content_binding instanceof \DataMachineCode\GitSync\GitSyncBinding, 'wp-content binding stored');
$assert(
rtrim(WP_CONTENT_DIR, '/') . '/uploads/wiki' === $content_binding->resolveAbsolutePath(),
'wp-content binding resolves through WP_CONTENT_DIR'
);
$gs->unbind('wp-content-binding');
$dup = $gs->bind(array( 'slug' => 'wiki', 'local_path' => '/x/', 'remote_url' => 'https://github.com/a/b' ));
$assert(is_wp_error($dup) && 'binding_exists' === $dup->get_error_code(), 'refuses duplicate slug');
// =========================================================================
// 3. Pull — initial sync materializes files on disk.
// =========================================================================
echo "\nPull (initial)\n";
$content_a = "article a v1\n";
$content_b = "article b v1\n";
$sha_a = $blob_sha($content_a);
$sha_b = $blob_sha($content_b);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/trees/main'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(
array(
'sha' => 'tree-sha-1',
'truncated' => false,
'tree' => array(
array( 'path' => 'articles/a.md', 'type' => 'blob', 'sha' => $sha_a ),
array( 'path' => 'articles/b.md', 'type' => 'blob', 'sha' => $sha_b ),
),
)
),
);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/contents/articles/a.md'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'content' => base64_encode($content_a), 'encoding' => 'base64', 'sha' => $sha_a )),
);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/contents/articles/b.md'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'content' => base64_encode($content_b), 'encoding' => 'base64', 'sha' => $sha_b )),
);
$pull = $gs->pull('wiki');
$assert(! is_wp_error($pull), 'pull succeeded — ' . ( is_wp_error($pull) ? $pull->get_error_message() : '' ));
$assert(2 === count((array) ( $pull['updated'] ?? array() )), 'pulled 2 files');
$assert(file_get_contents(ABSPATH . 'content/wiki/articles/a.md') === $content_a, 'articles/a.md content matches');
$assert(file_get_contents(ABSPATH . 'content/wiki/articles/b.md') === $content_b, 'articles/b.md content matches');
// =========================================================================
// 4. Pull again — nothing should change (SHAs match on disk).
// =========================================================================
echo "\nPull (idempotent)\n";
$GLOBALS['__dmc_http_capture'] = array();
$pull2 = $gs->pull('wiki');
$assert(! is_wp_error($pull2), 'second pull succeeded');
$assert(0 === count((array) ( $pull2['updated'] ?? array() )), 'second pull updated 0 files (already in sync)');
$assert(2 === ( $pull2['unchanged'] ?? 0 ), 'second pull reports 2 unchanged');
// =========================================================================
// 5. Upstream delete → local file removed, pulled_paths shrinks.
// =========================================================================
echo "\nPull (upstream deleted a file)\n";
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/trees/main'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(
array(
'sha' => 'tree-sha-2',
'tree' => array(
array( 'path' => 'articles/a.md', 'type' => 'blob', 'sha' => $sha_a ),
// b.md removed upstream
),
)
),
);
$pull3 = $gs->pull('wiki');
$assert(! is_wp_error($pull3), 'pull after upstream delete succeeded');
$assert(in_array('articles/b.md', (array) ( $pull3['deleted'] ?? array() ), true), 'reports articles/b.md deleted');
$assert(! is_file(ABSPATH . 'content/wiki/articles/b.md'), 'articles/b.md removed from disk');
// Untracked local file (consumer-owned proposal) is left alone.
file_put_contents(ABSPATH . 'content/wiki/articles/local-only.md', "proposal\n");
$pull4 = $gs->pull('wiki');
$assert(is_file(ABSPATH . 'content/wiki/articles/local-only.md'), 'untracked local file preserved across pull');
// =========================================================================
// 6. Conflict: tracked file modified locally, upstream also changed.
// =========================================================================
echo "\nPull conflict (fail policy)\n";
file_put_contents(ABSPATH . 'content/wiki/articles/a.md', "article a local-edit\n");
$content_a_v2 = "article a v2\n";
$sha_a_v2 = $blob_sha($content_a_v2);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/trees/main'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(
array(
'sha' => 'tree-sha-3',
'tree' => array(
array( 'path' => 'articles/a.md', 'type' => 'blob', 'sha' => $sha_a_v2 ),
),
)
),
);
$conflicted = $gs->pull('wiki');
$assert(is_array($conflicted['conflicts'] ?? null) && 1 === count($conflicted['conflicts']), 'conflict surfaced under fail policy');
$assert(false === ( $conflicted['success'] ?? true ), 'conflicted pull reports success=false');
$assert("article a local-edit\n" === file_get_contents(ABSPATH . 'content/wiki/articles/a.md'), 'local edit preserved under fail policy');
// upstream_wins overrides.
$gs->updatePolicy('wiki', array( 'conflict' => 'upstream_wins' ));
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/contents/articles/a.md'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'content' => base64_encode($content_a_v2), 'encoding' => 'base64', 'sha' => $sha_a_v2 )),
);
$wins = $gs->pull('wiki');
$assert(! is_wp_error($wins), 'pull under upstream_wins succeeded');
$assert($content_a_v2 === file_get_contents(ABSPATH . 'content/wiki/articles/a.md'), 'upstream_wins overwrote local edit');
// =========================================================================
// 7. Submit — write path, gated by policy.
// =========================================================================
echo "\nSubmit (gated)\n";
$r = $gs->submit('wiki', array( 'message' => 'update article a content' ));
$assert(is_wp_error($r) && 'write_disabled' === $r->get_error_code(), 'submit refused without write_enabled');
$gs->updatePolicy('wiki', array( 'write_enabled' => true ));
$r = $gs->submit('wiki', array( 'message' => 'update article a content' ));
$assert(is_wp_error($r) && 'no_allowed_paths' === $r->get_error_code(), 'submit refused without allowed_paths');
$gs->updatePolicy('wiki', array( 'allowed_paths' => array( 'articles/' ) ));
// Clean up the untracked-probe file from the earlier pull test — it
// would otherwise become a valid "new file" candidate for submit and
// require its own PUT mock.
@unlink(ABSPATH . 'content/wiki/articles/local-only.md');
// Edit locally, then submit.
file_put_contents(ABSPATH . 'content/wiki/articles/a.md', "article a v3 proposal\n");
$sha_a_v3 = $blob_sha("article a v3 proposal\n");
// Mock GitHub ref + branch + PR endpoints for submit flow.
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/ref/heads/main'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'object' => array( 'sha' => 'base-sha-1' ) )),
);
// Tree for submit's context — same as last pull.
// (Already mocked above.)
// Feature branch doesn't exist yet → 404
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/ref/heads/gitsync%2Fwiki'] = array(
'response' => array( 'code' => 404 ),
'body' => json_encode(array( 'message' => 'Not Found' )),
);
$GLOBALS['__dmc_http_mock']['POST https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/refs'] = array(
'response' => array( 'code' => 201 ),
'body' => json_encode(array( 'ref' => 'refs/heads/gitsync/wiki', 'object' => array( 'sha' => 'base-sha-1' ) )),
);
$GLOBALS['__dmc_http_mock']['PUT https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/contents/articles/a.md'] = array(
'response' => array( 'code' => 201 ),
'body' => json_encode(array( 'content' => array( 'sha' => $sha_a_v3 ), 'commit' => array( 'sha' => 'commit-1' ) )),
);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/pulls'] = array(
'response' => array( 'code' => 200 ),
'body' => '[]',
);
$GLOBALS['__dmc_http_mock']['POST https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/pulls'] = array(
'response' => array( 'code' => 201 ),
'body' => json_encode(array( 'number' => 7, 'html_url' => 'https://github.com/a/b/pull/7', 'state' => 'open' )),
);
$submit = $gs->submit('wiki', array( 'message' => 'update article a content' ));
$assert(! is_wp_error($submit), 'submit succeeded — ' . ( is_wp_error($submit) ? $submit->get_error_message() : '' ));
$assert('gitsync/wiki' === ( $submit['branch'] ?? null ), 'feature branch is gitsync/wiki');
$assert(null === ( $submit['proposal'] ?? null ), 'default submit has no proposal key');
$assert(7 === ( $submit['pr']['number'] ?? null ), 'PR #7 opened');
$assert('opened' === ( $submit['pr']['action'] ?? null ), 'PR reported as opened');
// =========================================================================
// 8. Submit again — existing branch + PR is updated in place.
// =========================================================================
echo "\nSubmit (update existing PR)\n";
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/ref/heads/gitsync%2Fwiki'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'object' => array( 'sha' => 'feature-old-sha' ) )),
);
$GLOBALS['__dmc_http_mock']['PATCH https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/refs/heads/gitsync%2Fwiki'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'object' => array( 'sha' => 'base-sha-1' ) )),
);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/pulls'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(
array(
array( 'number' => 7, 'html_url' => 'https://github.com/a/b/pull/7', 'state' => 'open' ),
)
),
);
$GLOBALS['__dmc_http_mock']['PATCH https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/pulls/7'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'number' => 7, 'html_url' => 'https://github.com/a/b/pull/7', 'state' => 'open' )),
);
file_put_contents(ABSPATH . 'content/wiki/articles/a.md', "article a v4 proposal\n");
$submit2 = $gs->submit('wiki', array( 'message' => 'further update article a' ));
$assert(! is_wp_error($submit2), 'second submit succeeded');
$assert('updated' === ( $submit2['pr']['action'] ?? null ), 'PR reported as updated');
// =========================================================================
// 9. Submit with a proposal key — isolated branch and PR lookup.
// =========================================================================
echo "\nSubmit (keyed proposal branch)\n";
// Sticky branch gitsync/wiki already exists from the default submit flow;
// keyed proposals must use a sibling ref so both branches can coexist.
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/ref/heads/gitsync%2Fwiki-script-modules'] = array(
'response' => array( 'code' => 404 ),
'body' => json_encode(array( 'message' => 'Not Found' )),
);
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/pulls'] = array(
'response' => array( 'code' => 200 ),
'body' => '[]',
);
$GLOBALS['__dmc_http_mock']['POST https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/pulls'] = array(
'response' => array( 'code' => 201 ),
'body' => json_encode(array( 'number' => 8, 'html_url' => 'https://github.com/a/b/pull/8', 'state' => 'open' )),
);
file_put_contents(ABSPATH . 'content/wiki/articles/a.md', "article a script modules proposal\n");
$capture_before_keyed = count($GLOBALS['__dmc_http_capture']);
$keyed = $gs->submit('wiki', array( 'message' => 'script modules update', 'proposal' => 'Script Modules' ));
$assert(! is_wp_error($keyed), 'keyed submit succeeded — ' . ( is_wp_error($keyed) ? $keyed->get_error_message() : '' ));
$assert('script-modules' === ( $keyed['proposal'] ?? null ), 'proposal key normalized to script-modules');
$assert('gitsync/wiki-script-modules' === ( $keyed['branch'] ?? null ), 'keyed feature branch is sibling of sticky branch');
$assert(8 === ( $keyed['pr']['number'] ?? null ), 'keyed proposal opened separate PR');
$keyed_requests = array_slice($GLOBALS['__dmc_http_capture'], $capture_before_keyed);
$keyed_pr_body = null;
$keyed_ref_body = null;
$saw_nested_keyed_ref = false;
foreach ( $keyed_requests as $request ) {
if ( 'POST' === $request['method'] && str_ends_with($request['url'], '/pulls') ) {
$keyed_pr_body = json_decode((string) $request['body'], true);
}
if ( 'POST' === $request['method'] && str_ends_with($request['url'], '/git/refs') ) {
$keyed_ref_body = json_decode((string) $request['body'], true);
}
if ( str_contains($request['url'], 'gitsync%2Fwiki%2Fscript-modules') ) {
$saw_nested_keyed_ref = true;
}
}
$assert('refs/heads/gitsync/wiki-script-modules' === ( $keyed_ref_body['ref'] ?? null ), 'keyed branch ref coexists with sticky branch namespace');
$assert('gitsync/wiki-script-modules' === ( $keyed_pr_body['head'] ?? null ), 'keyed PR uses keyed branch head');
$assert(false === $saw_nested_keyed_ref, 'keyed submit does not request nested sticky-branch ref');
// =========================================================================
// 10. Submit with nothing changed → nothing_to_submit.
// =========================================================================
echo "\nSubmit (nothing to propose)\n";
// File's current SHA must match upstream tree's reported SHA.
$current = file_get_contents(ABSPATH . 'content/wiki/articles/a.md');
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/trees/main'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(
array(
'sha' => 'tree-sha-4',
'tree' => array(
array( 'path' => 'articles/a.md', 'type' => 'blob', 'sha' => $blob_sha($current) ),
),
)
),
);
$nothing = $gs->submit('wiki', array( 'message' => 'should have nothing' ));
$assert(is_wp_error($nothing) && 'nothing_to_submit' === $nothing->get_error_code(), 'submit refuses when nothing changed');
// =========================================================================
// 11. Direct push — two-key auth.
// =========================================================================
echo "\nPush (two-key auth)\n";
file_put_contents(ABSPATH . 'content/wiki/articles/a.md', "article a v5 direct\n");
$r = $gs->push('wiki', array( 'message' => 'direct update' ));
$assert(is_wp_error($r) && 'direct_push_blocked' === $r->get_error_code(), 'push refused without safe_direct_push');
$gs->updatePolicy('wiki', array( 'safe_direct_push' => true ));
$GLOBALS['__dmc_http_mock']['PUT https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/contents/articles/a.md'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(array( 'content' => array( 'sha' => 'sha-after-direct' ), 'commit' => array( 'sha' => 'commit-2' ) )),
);
// Submit refreshed upstream tree mock so push's context reads it as changed.
$sha_old_on_upstream = $blob_sha("article a v3 proposal\n"); // still v3 upstream
$GLOBALS['__dmc_http_mock']['GET https://api.github.com/repos/Automattic/a8c-wiki-woocommerce/git/trees/main'] = array(
'response' => array( 'code' => 200 ),
'body' => json_encode(
array(
'sha' => 'tree-sha-5',
'tree' => array(
array( 'path' => 'articles/a.md', 'type' => 'blob', 'sha' => $sha_old_on_upstream ),
),
)
),
);
$push = $gs->push('wiki', array( 'message' => 'direct update' ));
$assert(! is_wp_error($push), 'push with both keys succeeded — ' . ( is_wp_error($push) ? $push->get_error_message() : '' ));
$assert(1 === count((array) ( $push['commits'] ?? array() )), 'push recorded 1 commit');
// =========================================================================
// 12. Status + list + unbind round-trip.
// =========================================================================
echo "\nStatus + list + unbind\n";
$st = $gs->status('wiki');
$assert(! is_wp_error($st) && 'wiki' === $st['slug'], 'status returns binding');
$assert(true === ( $st['exists'] ?? false ), 'status reports exists=true');
$l = $gs->list_bindings();
$assert(1 === count($l['bindings'] ?? array()), 'list returns 1 binding');
$u = $gs->unbind('wiki');
$assert(! is_wp_error($u) && false === ( $u['purged'] ?? true ), 'unbind preserved directory by default');
$assert(is_dir(ABSPATH . 'content/wiki/'), 'directory still exists after non-purge unbind');
// Re-bind and purge.
$gs->bind(array( 'slug' => 'wiki', 'local_path' => '/content/wiki/', 'remote_url' => 'https://github.com/Automattic/a8c-wiki-woocommerce' ));
$p = $gs->unbind('wiki', true);
$assert(! is_wp_error($p) && true === ( $p['purged'] ?? false ), 'purge unbind succeeded');
$assert(! is_dir(ABSPATH . 'content/wiki/'), 'directory removed by purge');
// =========================================================================
// 13. Policy validation.
// =========================================================================
echo "\nPolicy validation\n";
$gs->bind(array( 'slug' => 'p', 'local_path' => '/content/p/', 'remote_url' => 'https://github.com/Automattic/a8c-wiki-woocommerce' ));
$bad = $gs->updatePolicy('p', array( 'bogus' => true ));
$assert(is_wp_error($bad) && 'unknown_policy_key' === $bad->get_error_code(), 'rejects unknown policy key');
$orphan = $gs->updatePolicy('p', array( 'safe_direct_push' => true ));
$assert(is_wp_error($orphan) && 'policy_conflict' === $orphan->get_error_code(), 'rejects safe_direct_push without write_enabled');
$bad_conflict = $gs->updatePolicy('p', array( 'conflict' => 'nuke' ));
$assert(is_wp_error($bad_conflict) && 'invalid_conflict_strategy' === $bad_conflict->get_error_code(), 'rejects unknown conflict strategy');
echo "\nResult: " . ( $total - $failures ) . "/{$total} passed\n";
exit($failures > 0 ? 1 : 0);
}