-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdpl.php
More file actions
executable file
·706 lines (639 loc) · 21.5 KB
/
dpl.php
File metadata and controls
executable file
·706 lines (639 loc) · 21.5 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
#!/usr/bin/env php
<?php
// cli only
if (PHP_SAPI !== "cli") {
exit("Run from CLI only." . PHP_EOL);
}
// check for PHP version 8.3 or higher
if (version_compare(PHP_VERSION, "8.3.0", "<")) {
exit("Requires PHP 8.3 or higher." . PHP_EOL);
}
const DEFAULT_REV_FILE = ".dplrev";
const DEFAULT_SECTION = "main";
/**
* Writes the given revision string to the .dplrev file on the remote host.
* Returns true on success, false on failure.
*/
function writeRemoteRevision(
string $ssh,
string $revFile,
string $revision,
): bool {
exec(
"$ssh 'echo " . escapeshellarg($revision) . " > $revFile' 2>/dev/null",
$output,
$code,
);
return $code === 0;
}
/**
* Filters a list of files by exclude patterns.
* Patterns support wildcards (fnmatch-style): *.log, composer.*, .*, vendor/*
* A pattern without a wildcard that matches a path prefix is treated as a directory: vendor
*/
function filterExcluded(array $files, array $excludePatterns): array
{
if (empty($excludePatterns)) {
return $files;
}
return array_values(
array_filter($files, function (string $file) use (
$excludePatterns,
): bool {
foreach ($excludePatterns as $pattern) {
$pattern = trim($pattern);
if ($pattern === "") {
continue;
}
// Match against full path or just the filename
if (
fnmatch($pattern, $file) ||
fnmatch($pattern, basename($file))
) {
return false;
}
// Treat pattern as a directory prefix (e.g. "vendor" or "vendor/")
$dir = rtrim($pattern, "/") . "/";
if (strncmp($file, $dir, strlen($dir)) === 0) {
return false;
}
}
return true;
}),
);
}
/**
* Merges a named section from the full config with [*] defaults.
* Scalar keys fall back to [*] if not set in the section.
* exclude[] arrays are merged (union of both).
*/
function mergeSection(array $config, string $section): array
{
$sectionConfig = $config[$section] ?? [];
$defaults = $config["*"] ?? [];
if (!empty($defaults)) {
$defaultExcludes = $defaults["exclude"] ?? [];
if (!is_array($defaultExcludes)) {
$defaultExcludes =
$defaultExcludes !== "" ? [$defaultExcludes] : [];
}
$sectionExcludes = $sectionConfig["exclude"] ?? [];
if (!is_array($sectionExcludes)) {
$sectionExcludes =
$sectionExcludes !== "" ? [$sectionExcludes] : [];
}
// Section scalar values take priority; fall back to [*] for missing keys
$sectionConfig = [
...array_filter(
$defaults,
fn($k) => $k !== "exclude",
ARRAY_FILTER_USE_KEY,
),
...array_filter(
$sectionConfig,
fn($k) => $k !== "exclude",
ARRAY_FILTER_USE_KEY,
),
];
// Merge exclude arrays from both sections
$sectionConfig["exclude"] = array_values(
array_unique([...$defaultExcludes, ...$sectionExcludes]),
);
}
return $sectionConfig;
}
/**
* Deploys a single section to its remote host.
* Returns 0 on success, 1 on failure.
*/
/**
* Upload files via rsync. Returns [uploaded_count, failed_files].
*/
function uploadViaRsync(
array $files,
string $sshBase,
string $sshDest,
string $path,
): array {
$tmpFile = tempnam(sys_get_temp_dir(), "dpl_");
file_put_contents($tmpFile, implode(PHP_EOL, $files) . PHP_EOL);
$cmd =
"rsync -az --files-from=" .
escapeshellarg($tmpFile) .
" -e " .
escapeshellarg($sshBase) .
" . $sshDest:$path/ 2>/dev/null";
exec($cmd, $output, $code);
unlink($tmpFile);
if ($code !== 0) {
return [0, $files];
}
return [count($files), []];
}
/**
* Upload files one-by-one via scp. Returns [uploaded_count, failed_files].
*/
function uploadViaScp(
array $files,
string $sshBase,
string $sshDest,
string $path,
): array {
// scp uses -P for port instead of ssh's -p
$scpBase = preg_replace('/^ssh\b/', 'scp', $sshBase);
$scpBase = preg_replace('/ -p (\d+)/', ' -P $1', $scpBase);
$uploaded = 0;
$failed = [];
$lastMkdir = null;
foreach ($files as $file) {
echo " Uploading $file" . PHP_EOL;
$fileDir = dirname($file);
$remoteDir = escapeshellarg("$sshDest:$path/$fileDir");
$localFile = escapeshellarg($file);
if ($lastMkdir !== $fileDir) {
exec("$sshBase $sshDest 'mkdir -p " . escapeshellarg("$path/$fileDir") . "' 2>/dev/null");
$lastMkdir = $fileDir;
}
$cmd = "$scpBase $localFile $remoteDir/ 2>/dev/null";
exec($cmd, $out, $code);
if ($code !== 0) {
$failed[] = $file;
} else {
$uploaded++;
}
}
return [$uploaded, $failed];
}
function deploySection(
string $sectionName,
array $sectionConfig,
string $localRev,
bool $noColor,
bool $autoYes,
): int {
// which files to exclude from deployment, based on patterns in dpl.ini
$excludePatterns = $sectionConfig["exclude"] ?? [];
if (!is_array($excludePatterns)) {
$excludePatterns = [$excludePatterns];
}
// always exclude the revision file, regardless of dpl.ini exclude list
$revFileName = $sectionConfig["revision_file"] ?? DEFAULT_REV_FILE;
if (!in_array($revFileName, $excludePatterns)) {
$excludePatterns[] = $revFileName;
}
$host = $sectionConfig["host"];
$path = rtrim($sectionConfig["path"], "/");
$port = (int) ($sectionConfig["port"] ?? 22);
$user = $sectionConfig["user"] ?? null;
$sshKey = $sectionConfig["ssh_key"] ?? null;
$sshBase = "ssh -p $port";
if ($sshKey) {
$sshBase .= " -i $sshKey";
}
$sshDest = $user ? "$user@$host" : $host;
$ssh = "$sshBase $sshDest";
$revFile = "$path/$revFileName";
exec("{$ssh} 'test -d $path && test -w $path' 2>/dev/null", $output, $code);
if ($code !== 0) {
fwrite(STDERR, "Error: Cannot access $path on $host." . PHP_EOL);
return 1;
}
exec("{$ssh} 'test -f $revFile' 2>/dev/null", $output, $code);
if ($code !== 0) {
exec("{$ssh} 'touch $revFile' 2>/dev/null", $output, $code);
if ($code !== 0) {
fwrite(STDERR, "Error: Cannot create $revFile on $host." . PHP_EOL);
return 1;
}
} elseif (
exec(
"{$ssh} 'test -r $revFile && test -w $revFile' 2>/dev/null",
$output,
$code,
) === false ||
$code !== 0
) {
fwrite(STDERR, "Error: Cannot read/write $revFile on $host." . PHP_EOL);
return 1;
}
$revOutput = [];
exec("{$ssh} 'cat $revFile' 2>/dev/null", $revOutput, $code);
if ($code !== 0) {
fwrite(STDERR, "Error: Cannot read $revFile on $host." . PHP_EOL);
return 1;
}
$remoteRev = trim($revOutput[0] ?? "");
if ($remoteRev !== "" && !preg_match('/^[0-9a-f]{32,40}$/i', $remoteRev)) {
fwrite(
STDERR,
"Error: Unexpected content in $revFile: \"$remoteRev\"." . PHP_EOL,
);
return 1;
}
echo "Remote revision: " . ($remoteRev ?: "(none)") . PHP_EOL;
// check if local revision is the same as remote revision
if ($localRev === $remoteRev) {
echo "Local revision is the same as remote revision. Nothing to deploy." .
PHP_EOL;
return 0;
}
$uploadFiles = [];
$deleteFiles = [];
if ($remoteRev === "") {
// No previous deploy — all tracked files are uploads, nothing to delete
exec("git ls-files 2>/dev/null", $uploadFiles, $code);
} else {
// Verify the remote revision exists in this repository before diffing
exec("git cat-file -t $remoteRev 2>/dev/null", $catOutput, $catCode);
if ($catCode !== 0) {
fwrite(
STDERR,
"Error: Remote revision $remoteRev does not exist in this repository." .
PHP_EOL,
);
fwrite(
STDERR,
" Is \"$path\" on $host the right path for this project?" .
PHP_EOL,
);
return 1;
}
// git diff --name-status gives lines like "M\tfile", "D\tfile", "R90\told\tnew"
$diffOutput = [];
exec(
"git diff --name-status $remoteRev $localRev 2>/dev/null",
$diffOutput,
$code,
);
foreach ($diffOutput as $line) {
$parts = explode("\t", $line);
$status = $parts[0][0]; // first char: A, M, D, R, C, ...
if ($status === "D") {
$deleteFiles[] = $parts[1];
} elseif ($status === "R") {
$deleteFiles[] = $parts[1]; // old name → delete
$uploadFiles[] = $parts[2]; // new name → upload
} else {
$uploadFiles[] = $parts[1];
}
}
}
if ($code !== 0) {
fwrite(STDERR, "Error: Failed to get list of changed files." . PHP_EOL);
return 1;
}
$uploadFiles = filterExcluded($uploadFiles, $excludePatterns);
$deleteFiles = filterExcluded($deleteFiles, $excludePatterns);
if (empty($uploadFiles) && empty($deleteFiles)) {
echo "Nothing to deploy." . PHP_EOL;
writeRemoteRevision($ssh, $revFile, $localRev);
return 0;
}
$green = $noColor ? "" : "\033[32m";
$red = $noColor ? "" : "\033[31m";
$reset = $noColor ? "" : "\033[0m";
$totalFiles = count($uploadFiles) + count($deleteFiles);
echo "Files to deploy ($totalFiles):" . PHP_EOL;
foreach ($uploadFiles as $file) {
echo " {$green}U $file{$reset}" . PHP_EOL;
}
foreach ($deleteFiles as $file) {
echo " {$red}D $file{$reset}" . PHP_EOL;
}
if ($autoYes) {
echo PHP_EOL . "Continue? [Y/n] Y" . PHP_EOL;
} else {
echo PHP_EOL . "Continue? [Y/n] ";
$answer = trim(fgets(STDIN));
if (
$answer !== "" &&
strtolower($answer) !== "y" &&
strtolower($answer) !== "yes"
) {
echo "Aborted." . PHP_EOL;
return 0;
}
}
// Upload files
$uploaded = 0;
$uploadFailed = [];
if (!empty($uploadFiles)) {
$transfer = strtolower(trim($sectionConfig["transfer"] ?? "rsync"));
if ($transfer === "scp") {
[$uploaded, $uploadFailed] = uploadViaScp(
$uploadFiles,
$sshBase,
$sshDest,
$path,
);
} else {
// Try rsync first; fall back to scp if rsync is unavailable
[$uploaded, $uploadFailed] = uploadViaRsync(
$uploadFiles,
$sshBase,
$sshDest,
$path,
);
if ($uploaded === 0 && count($uploadFailed) === count($uploadFiles)) {
echo "rsync failed, falling back to scp..." . PHP_EOL;
[$uploaded, $uploadFailed] = uploadViaScp(
$uploadFiles,
$sshBase,
$sshDest,
$path,
);
}
}
}
// Delete files
$deleted = 0;
$deleteFailed = [];
foreach ($deleteFiles as $file) {
echo " Deleting $file" . PHP_EOL;
$remoteFile = escapeshellarg("$path/$file");
exec("$ssh 'rm -f $remoteFile' 2>/dev/null", $rmOutput, $rmCode);
if ($rmCode !== 0) {
$deleteFailed[] = $file;
} else {
$deleted++;
}
}
// Update remote revision if at least uploads succeeded (partial failure still records progress)
if (empty($uploadFailed)) {
if (!writeRemoteRevision($ssh, $revFile, $localRev)) {
fwrite(
STDERR,
"Warning: Deploy done but failed to update remote revision in $revFile." .
PHP_EOL,
);
}
}
// Summary
echo PHP_EOL . "Deploy summary:" . PHP_EOL;
echo " Uploaded : $uploaded" . PHP_EOL;
echo " Deleted : $deleted" . PHP_EOL;
if (!empty($uploadFailed)) {
fwrite(
STDERR,
PHP_EOL .
"Failed to upload (" .
count($uploadFailed) .
"):" .
PHP_EOL,
);
foreach ($uploadFailed as $file) {
fwrite(STDERR, " $file" . PHP_EOL);
}
}
if (!empty($deleteFailed)) {
fwrite(
STDERR,
PHP_EOL .
"Failed to delete (" .
count($deleteFailed) .
"):" .
PHP_EOL,
);
foreach ($deleteFailed as $file) {
fwrite(STDERR, " $file" . PHP_EOL);
}
}
return !empty($uploadFailed) || !empty($deleteFailed) ? 1 : 0;
}
// ─── Main ────────────────────────────────────────────────────────────────────
// This template is used when running with --init to create a new dpl.ini file.
// It should be kept up to date with the actual expected format of dpl.ini.
$defRevFile = DEFAULT_REV_FILE; // aliases for heredoc interpolation
$defSection = DEFAULT_SECTION;
$iniTemplate = <<<INI
; [*] defines defaults inherited by all sections.
; Scalar values (host, user, port, ...) can be overridden per section.
; exclude[] patterns are merged with the section's own exclude[] list.
[*]
exclude[] = dpl.ini
exclude[] = .git*
; exclude[] = .env
; exclude[] = tmp/*
[{$defSection}]
host = example.com
; port = 22
; user =
path = /var/www/html
; ssh_key = ~/.ssh/id_rsa
; revision_file = {$defRevFile}
; transfer = rsync ; rsync (default, falls back to scp) or scp
exclude[] = logs/*
; [production]
; host = prod.example.com
; path = /var/www/html
INI;
$iniFile = getcwd() . "/dpl.ini";
if (in_array("--help", $argv) || in_array("-?", $argv)) {
echo <<<HELP
dpl — a simple SSH/rsync deploy tool
Usage:
php dpl.php [section] [options]
php dpl.php --all [options]
dpl reads dpl.ini from the current directory to determine the remote host,
path, and transfer settings. It uses the local git repository to calculate
which files have changed since the last deploy and transfers only those files.
Arguments:
section Section name from dpl.ini to deploy (default: {$defSection}).
Options:
--init Create a dpl.ini template in the current directory.
--all Deploy to all sections defined in dpl.ini. If --all is
specified, ignores the [section] argument.
--yes, -y Auto-accept the confirmation prompt before deploying.
--no-color Disable colored output (U/D file markers).
--help, -? Show this help screen.
dpl.ini section keys:
host Remote host (required).
path Remote deploy path (required).
port SSH port (default: 22).
user SSH user (default: current system user).
ssh_key Path to SSH private key (default: SSH agent / ~/.ssh/id_rsa).
revision_file Name of the remote revision tracking file (default: {$defRevFile}).
transfer Transfer method: rsync (default) or scp. rsync is used by
default and automatically falls back to scp if rsync is not
available on the remote. Set to scp to skip rsync entirely.
exclude[] File/dir pattern to exclude from deploy (repeatable).
Supports wildcards: *.log, .*, vendor/*, composer.*
Examples:
php dpl.php --init Create a dpl.ini in the current project.
php dpl.php Deploy changed files to [{$defSection}] interactively.
php dpl.php production Deploy changed files to [production].
php dpl.php --all -y Deploy all sections without prompts (for CI).
php dpl.php -y --no-color Deploy without prompts or colors (for CI).
HELP;
exit(0);
}
if (in_array("--init", $argv)) {
if (file_exists($iniFile)) {
fwrite(STDERR, "Error: dpl.ini already exists." . PHP_EOL);
exit(1);
}
file_put_contents($iniFile, $iniTemplate . PHP_EOL);
echo "Created dpl.ini in " . getcwd() . PHP_EOL;
exit(0);
}
if (!file_exists($iniFile)) {
fwrite(
STDERR,
"Error: dpl.ini not found. Run with --init to create one." . PHP_EOL,
);
exit(1);
}
$deployAll = in_array("--all", $argv);
$noColor = in_array("--no-color", $argv);
$autoYes = in_array("--yes", $argv) || in_array("-y", $argv);
$config = parse_ini_file($iniFile, true);
if ($config === false) {
fwrite(STDERR, "Error: Failed to parse dpl.ini." . PHP_EOL);
exit(1);
}
// Determine target sections
if ($deployAll) {
$targetSections = array_keys(
array_filter($config, fn($k) => $k !== "*", ARRAY_FILTER_USE_KEY),
);
if (empty($targetSections)) {
fwrite(
STDERR,
"Error: No deployable sections found in dpl.ini." . PHP_EOL,
);
exit(1);
}
} else {
// Parse optional positional argument for section name (default: DEFAULT_SECTION)
$section = DEFAULT_SECTION;
foreach (array_slice($argv, 1) as $arg) {
if (strlen($arg) > 0 && $arg[0] !== "-") {
$section = $arg;
break;
}
}
if ($section === "*") {
fwrite(
STDERR,
"Error: [*] is a defaults section and cannot be deployed to." .
PHP_EOL,
);
exit(1);
}
if (empty($config[$section])) {
fwrite(
STDERR,
"Error: Section \"[$section]\" not found in dpl.ini." . PHP_EOL,
);
exit(1);
}
$targetSections = [$section];
}
// Validate required keys in all target sections before doing any git/SSH work
foreach ($targetSections as $sectionName) {
$merged = mergeSection($config, $sectionName);
foreach (["host", "path"] as $required) {
if (empty($merged[$required])) {
fwrite(
STDERR,
"Error: \"$required\" is required in [$sectionName] section of dpl.ini." .
PHP_EOL,
);
exit(1);
}
}
}
// check git for not being in a repository
$gitOutput = [];
exec("git rev-parse --is-inside-work-tree 2>/dev/null", $gitOutput, $gitCode);
if ($gitCode !== 0 || trim($gitOutput[0] ?? "") !== "true") {
fwrite(
STDERR,
"Error: Not a git repository. Please run this script in a git repository." .
PHP_EOL,
);
exit(1);
}
// check for uncommitted changes
$gitOutput = [];
exec("git status --porcelain 2>/dev/null", $gitOutput, $gitCode);
if ($gitCode !== 0) {
fwrite(STDERR, "Error: Failed to check git status." . PHP_EOL);
exit(1);
}
// git status --porcelain lines are "XY filename"; extract just the filename
$localFiles = [];
foreach ($gitOutput as $line) {
$file = trim(substr($line, 3));
if ($file === "") {
continue;
}
// renamed files are shown as "old -> new"; take the new name
if (strpos($file, " -> ") !== false) {
$file = substr($file, strrpos($file, " -> ") + 4);
}
$localFiles[] = $file;
}
// For --all: use only [*] excludes for the uncommitted-file check.
// For a single section: use the merged section excludes (same as before).
if ($deployAll) {
$checkExcludes = $config["*"]["exclude"] ?? [];
if (!is_array($checkExcludes)) {
$checkExcludes = $checkExcludes !== "" ? [$checkExcludes] : [];
}
} else {
$mergedConfig = mergeSection($config, $targetSections[0]);
$checkExcludes = $mergedConfig["exclude"] ?? [];
if (!is_array($checkExcludes)) {
$checkExcludes = [$checkExcludes];
}
// Also exclude the revision file as the deploy itself does
$revFileName = $mergedConfig["revision_file"] ?? DEFAULT_REV_FILE;
if (!in_array($revFileName, $checkExcludes)) {
$checkExcludes[] = $revFileName;
}
}
$filesWithChanges = filterExcluded($localFiles, $checkExcludes);
if (!empty($filesWithChanges)) {
fwrite(
STDERR,
"Error: Uncommitted changes detected. Stash or commit before deploying:" .
PHP_EOL,
);
foreach ($filesWithChanges as $file) {
fwrite(STDERR, " $file" . PHP_EOL);
}
exit(1);
}
// Check the local directory for git and get the current revision
$gitOutput = [];
exec("git rev-parse HEAD 2>/dev/null", $gitOutput, $gitCode);
$localRev = trim($gitOutput[0] ?? "");
if ($gitCode !== 0 || !preg_match('/^[0-9a-f]{40}$/i', $localRev)) {
fwrite(
STDERR,
"Error: Failed to get local git revision. Is this a git repository?" .
PHP_EOL,
);
exit(1);
}
echo "Local revision: $localRev" . PHP_EOL;
// Deploy each target section
$exitCode = 0;
foreach ($targetSections as $sectionName) {
if ($deployAll) {
echo PHP_EOL . "==> Deploying [$sectionName]..." . PHP_EOL;
}
$mergedConfig = mergeSection($config, $sectionName);
$result = deploySection(
$sectionName,
$mergedConfig,
$localRev,
$noColor,
$autoYes,
);
if ($result !== 0) {
$exitCode = $result;
}
}
exit($exitCode);