Repository navigation
Expand file tree
/
Copy pathbuild.php
More file actions
932 lines (786 loc) · 29.7 KB
/
Copy pathbuild.php
File metadata and controls
932 lines (786 loc) · 29.7 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
#!/usr/bin/env php
<?php
/**
* Build Script for Amber WordPress Plugin
*
* Cross-platform build script that works on Windows, macOS, and Linux.
*
* This script handles the compression and packaging of the plugin
* for distribution.
*
* Usage: php build.php [target] [options]
*
* Targets:
* build:production Create production archive (default)
* build:dev Create development archive (includes tests)
* clean Clean build directory only
*
* Options:
* --version=X.X Override version number
* --clean Clean build directory before building
* --help Show this help message
*/
declare(strict_types=1);
class PluginBuilder
{
private string $pluginDir;
private string $buildDir;
private string $version;
private string $pluginName = 'amber';
private bool $isWindows;
// Files and directories to exclude in production builds
private array $productionExcludes = [
// Version control
'.git',
'.gitignore',
'.gitattributes',
// IDE/Editor
'.idea',
'.vscode',
// Build artifacts
'build',
// Tests
'tests',
// Setup/config files not needed in production
'setup',
'node_modules',
'.DS_Store',
'Thumbs.db',
// Composer files (not needed after autoload is generated)
'composer.json',
'composer.lock',
// PHPUnit
'phpunit.xml',
'phpunit.xml.dist',
// Code style
'.phpcs.xml',
'.phpcs.xml.dist',
'.php-cs-fixer.php',
'.php-cs-fixer.cache',
// Static analysis
'phpstan.neon',
'phpstan.neon.dist',
// Documentation
'*.md',
// Package manager
'package.json',
'package-lock.json',
// Editor config
'.editorconfig',
// Build script
'build.php',
// Vendor (no production dependencies needed)
'vendor',
// Dev artefacts that must never ship
'.phpunit.result.cache',
'.phpunit.cache',
'phpstan-baseline.neon',
'.claude',
];
// Files and directories to exclude in dev builds
private array $devExcludes = [
// Version control
'.git',
// IDE/Editor
'.idea',
'.vscode',
// Build artifacts
'build',
// OS files
'node_modules',
'.DS_Store',
'Thumbs.db',
// ==== VENDOR DEV PACKAGES NOT NEEDED IN DEV BUILD ====
// These are dev tools, not needed to run/test the plugin
'vendor/bin',
'vendor/phpstan',
// Vendor unnecessary files
'vendor/*/.git',
'vendor/*/.github',
'vendor/*/*/.github',
'vendor/*/doc',
'vendor/*/docs',
];
public function __construct()
{
$this->isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
$this->pluginDir = $this->normalizePath(dirname(__FILE__));
$this->buildDir = $this->pluginDir . DIRECTORY_SEPARATOR . 'build';
$this->version = $this->getVersionFromPlugin();
// Check for required extensions
$this->checkRequirements();
}
/**
* Stage a clean production vendor/ for inclusion in the archive.
*
* Runs `composer install --no-dev --optimize-autoloader` against a copy of
* composer.json / composer.lock in an isolated staging directory under
* build/, so the developer's working vendor/ -- which holds phpunit,
* phpstan and other test tooling -- is never mutated. Returns the absolute
* path to the staged vendor/, or null when there is nothing to ship (no
* composer.json, or no production dependencies).
*
* This replaces denylisting individual dev packages, which could only ever
* be as current as the last time someone remembered to update the list.
*/
private function stageProductionVendor(): ?string
{
$composerFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'composer.json';
if (!file_exists($composerFile)) {
$this->log("No composer.json - production archive will ship no vendor/");
return null;
}
$stagingDir = $this->buildDir . DIRECTORY_SEPARATOR . '.vendor-staging';
if (is_dir($stagingDir)) {
$this->deleteDirectory($stagingDir);
}
if (!is_dir($stagingDir) && !mkdir($stagingDir, 0755, true)) {
$this->error("Failed to create vendor staging directory: {$stagingDir}");
exit(1);
}
// Copy the dependency manifests so composer resolves the same set, and
// the exact locked versions when a lock file is present.
copy($composerFile, $stagingDir . DIRECTORY_SEPARATOR . 'composer.json');
$lockFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'composer.lock';
if (file_exists($lockFile)) {
copy($lockFile, $stagingDir . DIRECTORY_SEPARATOR . 'composer.lock');
}
$command = sprintf(
'composer install --no-dev --optimize-autoloader --no-interaction --working-dir=%s 2>&1',
escapeshellarg($stagingDir)
);
$this->log("Staging production vendor (no-dev)...");
$output = [];
$returnCode = 0;
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
$this->error("Composer (no-dev) install failed with code {$returnCode}");
foreach ($output as $line) {
$this->error(" " . $line);
}
exit(1);
}
$stagedVendor = $stagingDir . DIRECTORY_SEPARATOR . 'vendor';
if (!is_dir($stagedVendor)) {
// No production dependencies were installed - nothing to ship.
$this->log("No production dependencies - archive will ship no vendor/");
return null;
}
$this->log("Staged production vendor/ (no-dev) ready");
return $stagedVendor;
}
/**
* Remove the vendor staging directory left by stageProductionVendor().
*/
private function cleanVendorStaging(): void
{
$stagingDir = $this->buildDir . DIRECTORY_SEPARATOR . '.vendor-staging';
if (is_dir($stagingDir)) {
$this->deleteDirectory($stagingDir);
}
}
/**
* Normalize path separators for cross-platform compatibility
*/
private function normalizePath(string $path): string
{
return str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
}
/**
* Check for required PHP extensions
*/
private function checkRequirements(): void
{
if (!extension_loaded('zip')) {
$this->error("PHP ZIP extension is required but not installed.");
$this->error("Install it with:");
if ($this->isWindows) {
$this->error(" - Enable extension=zip in php.ini");
} else {
$this->error(" - Ubuntu/Debian: sudo apt-get install php-zip");
$this->error(" - macOS: brew install php");
}
exit(1);
}
if (version_compare(PHP_VERSION, '8.0.0', '<')) {
$this->error("PHP 8.0 or higher is required. Current version: " . PHP_VERSION);
exit(1);
}
}
/**
* Extract version from the main plugin file
*/
private function getVersionFromPlugin(): string
{
$mainFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'amber.php';
if (file_exists($mainFile)) {
$content = file_get_contents($mainFile);
if (preg_match('/Version:\s*([0-9.]+\s*\w*)/', $content, $matches)) {
return trim($matches[1]);
}
if (preg_match("/define\s*\(\s*'AMBER_VERSION'\s*,\s*'([^']+)'/", $content, $matches)) {
return $matches[1];
}
}
return '0.0.1';
}
/**
* Clean the build directory
*/
public function clean(): void
{
$this->log("Cleaning build directory...");
if (is_dir($this->buildDir)) {
$this->deleteDirectory($this->buildDir);
}
$this->log("Build directory cleaned");
}
/**
* Create the plugin archive
*/
public function build(string $type = 'production', ?string $customVersion = null): void
{
if ($customVersion) {
$this->version = $customVersion;
}
$this->log("Building {$type} archive for version {$this->version}...");
$this->log("Platform: " . PHP_OS . " (" . ($this->isWindows ? "Windows" : "Unix-like") . ")");
// Check for vendor directory
$vendorDir = $this->pluginDir . DIRECTORY_SEPARATOR . 'vendor';
if (!is_dir($vendorDir)) {
$this->log("Warning: vendor directory not found. Running 'composer install'...");
$this->runComposer();
}
// Create build directory
if (!is_dir($this->buildDir)) {
if (!mkdir($this->buildDir, 0755, true)) {
$this->error("Failed to create build directory: {$this->buildDir}");
exit(1);
}
}
// Determine archive name and excludes
$archiveName = $this->buildDir . DIRECTORY_SEPARATOR . $this->pluginName;
if ($type === 'dev') {
$archiveName .= '-dev';
$excludes = $this->devExcludes;
} else {
$archiveName .= '-production';
$excludes = $this->productionExcludes;
}
// Sanitize version for filename
$safeVersion = preg_replace('/[^a-zA-Z0-9._-]/', '-', $this->version);
$archiveName .= '-' . $safeVersion . '.zip';
// Sync readme.txt Stable tag with plugin version
$this->syncReadmeVersion();
// Sync README.md version badge with plugin version
$this->syncReadmeMarkdownVersion();
// Stamp the build date into the main plugin header
$this->syncBuildDate();
// Stamp the plugin version into the bundled HTML docs
$this->syncDocsVersion();
// Create ZIP archive
// Stage a clean production vendor/ (no dev tooling) without touching
// the working vendor/ used for tests. Dev builds keep it as-is.
$stagedVendor = $type === 'dev' ? null : $this->stageProductionVendor();
$this->createZip($archiveName, $excludes, $stagedVendor);
$this->cleanVendorStaging();
// Display file size
$this->log("Archive created successfully: " . basename($archiveName));
$fileSize = filesize($archiveName);
if ($fileSize !== false) {
$size = $this->formatBytes($fileSize);
$this->log("File size: {$size}");
}
$this->log("Location: {$archiveName}");
}
/**
* Run composer install if vendor directory is missing
*/
private function runComposer(): void
{
$composerFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'composer.json';
if (!file_exists($composerFile)) {
$this->error("composer.json not found. Cannot install dependencies.");
exit(1);
}
$command = 'composer install --no-dev --optimize-autoloader';
$this->log("Running: {$command}");
$output = [];
$returnCode = 0;
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
$this->error("Composer install failed with code {$returnCode}");
foreach ($output as $line) {
$this->error(" {$line}");
}
exit(1);
}
}
/**
* Create ZIP archive
*/
private function createZip(string $archiveName, array $excludes, ?string $stagedVendor = null): void
{
$this->log("Creating archive: " . basename($archiveName));
// Remove existing archive
if (file_exists($archiveName)) {
unlink($archiveName);
}
$zip = new ZipArchive();
$result = $zip->open($archiveName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($result !== true) {
$this->error("Failed to create ZIP archive. Error code: {$result}");
exit(1);
}
// Get all files
$files = $this->getFiles($this->pluginDir, $excludes);
$fileCount = 0;
foreach ($files as $file) {
$relativePath = $this->pluginName . '/' . substr($file, strlen($this->pluginDir) + 1);
$relativePath = str_replace('\\', '/', $relativePath);
if (is_file($file)) {
// Read file content and add as string to avoid keeping file handles
// open (which causes failures on Windows with many files)
$contents = file_get_contents($file);
if ($contents === false) {
$this->error("Warning: Could not read file: {$file}");
continue;
}
$zip->addFromString($relativePath, $contents);
$fileCount++;
} elseif (is_dir($file)) {
$zip->addEmptyDir($relativePath);
}
}
// Inject the staged production vendor/ (no dev tooling) under the
// plugin's vendor/ path. The working vendor/ is excluded from the walk
// above, so this is the only vendor/ that reaches the archive.
if ($stagedVendor !== null && is_dir($stagedVendor)) {
foreach ($this->getFiles($stagedVendor, []) as $stagedFile) {
if (!is_file($stagedFile)) {
continue;
}
$stagedRelative = str_replace('\\', '/', substr($stagedFile, strlen($stagedVendor) + 1));
$zip->addFile($stagedFile, $this->pluginName . '/vendor/' . $stagedRelative);
$fileCount++;
}
}
if (!$zip->close()) {
$this->error("Failed to write ZIP archive to: {$archiveName}");
exit(1);
}
$this->log("Added {$fileCount} files to archive");
}
/**
* Get all files in directory, excluding specified patterns
*/
private function getFiles(string $dir, array $excludes): array
{
$files = [];
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
$path = $file->getPathname();
$relativePath = substr($path, strlen($dir) + 1);
// Check if file should be excluded
if ($this->shouldExclude($relativePath, $excludes)) {
continue;
}
$files[] = $path;
}
return $files;
}
/**
* Check if a file path should be excluded
*/
private function shouldExclude(string $path, array $excludes): bool
{
// Normalize path for comparison (use forward slashes)
$normalizedPath = str_replace('\\', '/', $path);
foreach ($excludes as $exclude) {
$normalizedExclude = str_replace('\\', '/', $exclude);
// Check for wildcard patterns (e.g., *.md)
if (strpos($normalizedExclude, '*') !== false) {
$pattern = str_replace('*', '.*', preg_quote($normalizedExclude, '/'));
// Use case-insensitive matching (i flag) for wildcard patterns
if (preg_match('/^' . $pattern . '$/i', $normalizedPath)) {
return true;
}
// Also check basename for file extensions (case-insensitive)
if (preg_match('/' . $pattern . '$/i', basename($normalizedPath))) {
return true;
}
}
// Check if path starts with exclude pattern
if (strpos($normalizedPath, $normalizedExclude) === 0) {
return true;
}
// Check if any part of the path matches
if (strpos($normalizedPath, '/' . $normalizedExclude . '/') !== false) {
return true;
}
// Check if path contains the exclude pattern as a directory
if (strpos($normalizedPath, '/' . $normalizedExclude) !== false) {
return true;
}
// Check exact match
if ($normalizedPath === $normalizedExclude) {
return true;
}
}
return false;
}
/**
* Update the Stable tag in readme.txt to match the current plugin version
*/
private function syncReadmeVersion(): void
{
$readmeFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'readme.txt';
if (!file_exists($readmeFile)) {
$this->log("No readme.txt found — skipping version sync");
return;
}
$content = file_get_contents($readmeFile);
if ($content === false) {
$this->error("Failed to read readme.txt");
return;
}
$updated = preg_replace(
'/^Stable tag:[ \t]*[^\r\n]*(?=\r?$)/mi',
'Stable tag: ' . $this->version,
$content,
-1,
$count
);
if ($count > 0 && $updated !== null) {
file_put_contents($readmeFile, $updated);
$this->log("Updated readme.txt Stable tag to {$this->version}");
} else {
$this->log("No Stable tag found in readme.txt — skipping version sync");
}
}
/**
* Update the version badge in README.md to match the current plugin version.
*
* The badge is the canonical place the version appears in README.md. The
* legacy **Version:** line is still rewritten where one exists, so a repo
* that has not been converted keeps working.
*/
private function syncReadmeMarkdownVersion(): void
{
$readmeFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'README.md';
if (!file_exists($readmeFile)) {
$this->log("No README.md found — skipping version sync");
return;
}
$content = file_get_contents($readmeFile);
if ($content === false) {
$this->error("Failed to read README.md");
return;
}
$updated = preg_replace(
'~(img\.shields\.io/badge/version-)[^-\s)]+(-blue)~',
'${1}' . $this->version . '${2}',
$content,
-1,
$badgeCount
);
if ($updated === null) {
$this->error("Failed to rewrite the version badge in README.md");
return;
}
$updated = preg_replace(
'/^\*\*Version:\*\*[ \t]*[^\r\n]*(?=\r?$)/m',
'**Version:** ' . $this->version,
$updated,
-1,
$lineCount
);
if ($updated === null) {
$this->error("Failed to rewrite the **Version:** line in README.md");
return;
}
$count = $badgeCount + $lineCount;
if ($count > 0) {
file_put_contents($readmeFile, $updated);
$this->log("Updated README.md version to {$this->version} ({$badgeCount} badge, {$lineCount} line)");
} else {
$this->log("No version badge or **Version:** line in README.md — skipping version sync");
}
}
/**
* Update the version chip in the bundled HTML documentation.
*
* Replaces the version token inside <span class="version">…</span> with the
* current plugin version (prefixed with "v"), leaving any trailing text —
* such as " · Bristol & District Intergroup" — untouched. Applies to both
* the standalone guide (assets/docs/amber.html) and the in-admin help page
* (templates/help-page.php).
*/
private function syncDocsVersion(): void
{
$docs = [
'assets' . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . 'amber.html',
'templates' . DIRECTORY_SEPARATOR . 'help-page.php',
];
foreach ($docs as $relative) {
$docFile = $this->pluginDir . DIRECTORY_SEPARATOR . $relative;
if (!file_exists($docFile)) {
$this->log("No {$relative} found — skipping doc version sync");
continue;
}
$content = file_get_contents($docFile);
if ($content === false) {
$this->error("Failed to read {$relative}");
continue;
}
// Match the version token immediately after the opening span tag,
// preserving the rest of the chip (e.g. " · Bristol & District…").
//
// The trailing group consumes an optional suffix word, because
// getVersionFromPlugin() can return one ("1.2.0 beta"): without it the
// match would stop at the space, and each build would write the suffix
// in again after the one already there.
$updated = preg_replace(
'/(<span class="version">\s*)v?[0-9][\w.\-]*(?:[ \t]+\w+)?/',
'${1}v' . $this->version,
$content,
1,
$count
);
if ($count > 0 && $updated !== null) {
file_put_contents($docFile, $updated);
$this->log("Updated {$relative} version to v{$this->version}");
} else {
$this->log("No version chip found in {$relative} — skipping doc version sync");
}
}
}
/**
* Update (or insert) the Build date in readme.txt.
*
* Writes the current date in Y/m/d format (e.g. 2026/01/12). If a
* "Build date:" line already exists in readme.txt it is updated;
* otherwise a new line is inserted immediately after the "Stable tag:"
* line, preserving the file's existing line ending convention.
*/
private function syncBuildDate(): void
{
$readmeFile = $this->pluginDir . DIRECTORY_SEPARATOR . 'readme.txt';
if (!file_exists($readmeFile)) {
$this->log("No readme.txt found — skipping build date sync");
return;
}
$content = file_get_contents($readmeFile);
if ($content === false) {
$this->error("Failed to read readme.txt");
return;
}
// Build timestamps reflect the build machine's wall clock, not UTC.
// php.ini sets date.timezone=UTC, so a bare date() call reads an hour
// behind during BST; the zone is stated explicitly here rather than
// left to ini config, which differs per machine.
$buildDate = (new DateTime('now', new DateTimeZone('Europe/London')))
->format('Y/m/d H:i:s');
// First, try to update an existing "Build date:" line.
// The tail is matched as [^\r\n]* with a lookahead, not .+$. In PCRE `.`
// matches \r, so `.+$` swallows the carriage return of a CRLF line and the
// replacement writes it back LF-only, leaving one mixed line ending behind.
// `$` in multiline mode anchors before \n and not before \r, so the CR has
// to be stepped over by a lookahead rather than matched, or nothing matches.
$updated = preg_replace(
'/^Build date:[ \t]*[^\r\n]*(?=\r?$)/mi',
'Build date: ' . $buildDate,
$content,
1,
$count
);
if ($count > 0 && $updated !== null) {
file_put_contents($readmeFile, $updated);
$this->log("Updated readme.txt Build date to {$buildDate}");
return;
}
// No existing line — insert one right after the "Stable tag:" line,
// preserving the file's line ending convention (\r\n or \n).
$updated = preg_replace_callback(
'/^(Stable tag:[ \t]*[^\r\n]*)(\r?\n)/mi',
static function (array $m) use ($buildDate): string {
return $m[1] . $m[2] . 'Build date: ' . $buildDate . $m[2];
},
$content,
1,
$count
);
if ($count > 0 && $updated !== null) {
file_put_contents($readmeFile, $updated);
$this->log("Inserted Build date {$buildDate} into readme.txt");
} else {
$this->log("No Stable tag line found in readme.txt — skipping build date sync");
}
}
/**
* Delete directory recursively (cross-platform)
*/
private function deleteDirectory(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
$path = $dir . DIRECTORY_SEPARATOR . $file;
// Windows: Remove read-only attribute if present
if ($this->isWindows && file_exists($path)) {
chmod($path, 0777);
}
if (is_dir($path)) {
$this->deleteDirectory($path);
} else {
if (!unlink($path)) {
$this->error("Failed to delete file: {$path}");
}
}
}
if (!rmdir($dir)) {
$this->error("Failed to remove directory: {$dir}");
}
}
/**
* Format bytes to human readable format
*/
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
/**
* Log message
*/
private function log(string $message): void
{
echo "[BUILD] {$message}\n";
}
/**
* Log error message
*/
private function error(string $message): void
{
echo "[ERROR] {$message}\n";
}
/**
* Display help message
*/
public function showHelp(): void
{
$phpVersion = PHP_VERSION;
$platform = PHP_OS;
echo <<<HELP
Amber WordPress Plugin Build Script
====================================
Platform: {$platform}
PHP Version: {$phpVersion}
Usage: php build.php [target] [options]
Targets:
build:production Create production archive (default)
build:dev Create development archive (includes tests)
clean Clean build directory only
Options:
--type=production Create production archive (alternative syntax)
--type=dev Create development archive (alternative syntax)
--version=X.X Override version number (default: from plugin file)
--clean Clean build directory before building
--help Show this help message
Examples:
php build.php build:production # Build production archive
php build.php build:dev # Build development archive
php build.php build:production --clean # Clean and build production
php build.php build:dev --version=1.0 # Dev build with custom version
php build.php clean # Only clean build directory
php build.php --type=production # Alternative: using --type flag
php build.php # Default: production build
Composer Scripts (add to composer.json):
"scripts": {
"build:production": "php build.php build:production",
"build:dev": "php build.php build:dev",
"build:clean": "php build.php clean"
}
Files Excluded (Production):
- Development files (.git, .idea, .vscode, tests, etc.)
- Build configuration (composer.json, package.json, etc.)
- Documentation (*.md files)
- PHP tooling configs (phpunit.xml, phpstan.neon, etc.)
Files Excluded (Dev):
- Only: .git, .idea, .vscode, build, node_modules, .DS_Store
Platform-Specific Notes:
HELP;
if ($this->isWindows) {
echo <<<WINDOWS
Windows Detected:
- Paths use backslashes (\\) automatically
- Build directory: .\\build\\
- If permission errors occur, run Command Prompt as Administrator
- Ensure ZIP extension is enabled in php.ini (extension=zip)
WINDOWS;
} else {
echo <<<UNIX
Unix-like System (macOS/Linux) Detected:
- Paths use forward slashes (/)
- Build directory: ./build/
- Make script executable: chmod +x build.php
- Then run directly: ./build.php [target] [options]
- Or run via: php build.php [target] [options]
UNIX;
}
echo <<<NOTES
PSR-4 Autoloading:
This plugin uses Composer for PSR-4 autoloading.
The build script will automatically run 'composer install --no-dev'
if the vendor directory is missing.
Namespace: Amber\\
Source: src/
Note:
Amber is a companion plugin to Unity. Make sure Unity is installed
and activated before activating Amber.
NOTES;
}
}
// Parse command line arguments
$options = getopt('', ['type:', 'version:', 'clean', 'clean-only', 'help']);
// Check for target-style arguments (build:production, build:dev)
$target = null;
foreach ($argv as $arg) {
if ($arg === 'build:production' || $arg === 'production') {
$target = 'production';
} elseif ($arg === 'build:dev' || $arg === 'dev') {
$target = 'dev';
}
}
$builder = new PluginBuilder();
// Handle help
if (isset($options['help']) || in_array('--help', $argv) || in_array('-h', $argv) || in_array('help', $argv)) {
$builder->showHelp();
exit(0);
}
// Handle clean-only
if (isset($options['clean-only']) || in_array('clean', $argv)) {
$builder->clean();
// If only 'clean' was passed without a build target, exit
if ($target === null && !isset($options['type'])) {
exit(0);
}
}
// Handle clean before build
if (isset($options['clean'])) {
$builder->clean();
}
// Determine build type: target style takes precedence, then --type option, then default
$type = $target ?? ($options['type'] ?? 'production');
$version = $options['version'] ?? null;
$builder->build($type, $version);