Skip to content

Instantly share code, notes, and snippets.

@maximkott
Last active August 29, 2015 14:15
Show Gist options
  • Save maximkott/9a79ca2bc40e907d401e to your computer and use it in GitHub Desktop.
Save maximkott/9a79ca2bc40e907d401e to your computer and use it in GitHub Desktop.
Swap two files/folders.
#!/usr/bin/env php
<?php
function ask($string) {
echo "$string (y/n): ";
$handle = fopen("php://stdin","r");
$line = trim(fgets($handle));
if ($line == 'y' or $line == 'yes') {
return true;
} else {
return false;
}
}
function say($key, $string = null) {
if ( ! $string) {
$string = $key;
} else {
$string = "$key: $string";
}
echo "$string\n";
}
////////////////////////////////////////////////////////////////////////////////
function main($args) {
if (@$args[1] == "update") {
$file = $args[0];
$fileBackup = $file . ".bak";
$script = file_get_contents("https://gist.githubusercontent.com/maximkott/9a79ca2bc40e907d401e/raw");
$oldScript = file_get_contents($file);
if ($script == $oldScript) {
say("error", "gist did not change yet.");
exit;
}
say("starting update...");
if (file_exists($fileBackup)) {
unlink($fileBackup);
}
rename($file, $fileBackup);
file_put_contents($file, $script);
exec("chmod +x $file");
say("update completed.");
unlink($fileBackup);
exit;
}
$file1 = @$args[1];
$file2 = @$args[2];
if ( ! $file1) {
say("error", "target and destination paths required.");
exit;
} else if ( ! $file2) {
if (substr($file1, -1) != '/') $file1 = $file1 . "/";
$file2 = $file1 . "green";
$file1 = $file1 ."red";
}
if ( ! file_exists($file1)) {
say("error", "bad argument: $file1.");
exit;
} else if ( ! file_exists($file2)) {
say("error", "bad argument: $file2.");
exit;
}
if (ask("swap files $file1 -> $file2?")) {
$fileTmp = $file1 . "_tmp_" . time();
rename($file1, $fileTmp);
rename($file2, $file1);
rename($fileTmp, $file2);
say("all done!");
}
}
main($argv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment