Create custom php stow app
This commit is contained in:
parent
ac4bf543df
commit
bc0a7fddde
85
stow
Executable file
85
stow
Executable file
@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
function path(...$segments): string
|
||||
{
|
||||
return join(DIRECTORY_SEPARATOR, $segments);
|
||||
}
|
||||
|
||||
function line(string $line): void
|
||||
{
|
||||
echo $line . PHP_EOL;
|
||||
}
|
||||
|
||||
$cwd = getcwd();
|
||||
$action = 'stow';
|
||||
$backup = $force = false;
|
||||
array_shift($argv); // we don't care about the script name
|
||||
|
||||
while (str_starts_with($argv[0], '-')) {
|
||||
$option = substr($argv[0], 1);
|
||||
switch ($option) {
|
||||
case 'u':
|
||||
$action = 'unstow';
|
||||
break;
|
||||
case 'b':
|
||||
$backup = true;
|
||||
break;
|
||||
case 'f':
|
||||
$force = true;
|
||||
break;
|
||||
default:
|
||||
line("Unknown option: $option");
|
||||
exit(1);
|
||||
}
|
||||
array_shift($argv);
|
||||
}
|
||||
|
||||
$stowName = $argv[0];
|
||||
$stowPath = path($cwd, $stowName);
|
||||
$targetPath = dirname($stowPath, 2);
|
||||
|
||||
if (!is_dir($stowPath)) {
|
||||
line("Directory '$stowName' does not exist");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$files = array_diff(scandir($stowPath), ['..', '.']);
|
||||
|
||||
foreach ($files as $file) {
|
||||
$targetFile = path($targetPath, $file);
|
||||
$stowFile = path($stowPath, $file);
|
||||
$isStowed = is_link($targetFile) && readlink($targetFile) === $stowFile;
|
||||
|
||||
if ($action === 'stow') {
|
||||
if (is_link($targetFile)) {
|
||||
line("File $targetFile is already stowed from $stowFile");
|
||||
continue;
|
||||
}
|
||||
if (is_file($targetFile)) {
|
||||
if ($backup) {
|
||||
$backFile = $targetFile . '.bak';
|
||||
if (is_file($backFile)) {
|
||||
line("Backup file $backFile already exists");
|
||||
continue;
|
||||
}
|
||||
rename($targetFile, $backFile);
|
||||
line("Backup file $targetFile to $backFile");
|
||||
} elseif ($force) {
|
||||
line("Todo: delete file $targetFile");
|
||||
continue;
|
||||
} else {
|
||||
line("File $targetFile already exists");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
line("Stow $stowFile to $targetFile");
|
||||
symlink($stowFile, $targetFile);
|
||||
} elseif ($action === 'unstow') {
|
||||
if (!$isStowed) {
|
||||
line("File $targetFile is not stowed from $stowFile");
|
||||
continue;
|
||||
}
|
||||
unlink($targetFile);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user