Last active
September 2, 2015 17:05
-
-
Save josuecau/53bf7e6126b7656cf47c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Transfert des fichiers modifiés depuis un commit vers un hôte distant. | |
* Synopsis : php deploy.php commit [user@]host:dir | |
* Exemple : php deploy.php C0MM1TH45H^ host.example.com:/path/to/dir | |
*/ | |
// Pas en CLI | |
if (PHP_SAPI !== 'cli') { | |
exit; | |
} | |
// Pas le bon nombre d'arguments | |
if ($argc !== 3) { | |
exit(sprintf('Usage : php %s C0MM1TH45H^ host.example.com:/path/to/dir%s', $argv[0], PHP_EOL)); | |
} | |
$commit = $argv[1]; | |
$remote = explode(':', $argv[2]); | |
// Adresse distante invalide | |
if (count($remote) !== 2) { | |
exit('Adresse invalide.'.PHP_EOL); | |
} | |
$host = $remote[0]; | |
$path = rtrim($remote[1], '/'); | |
// Change de dossier courant pour la racine du dépôt git | |
$cwd = trim(shell_exec('git rev-parse --show-toplevel')); | |
if (!chdir($cwd)) { | |
exit(sprintf('Impossible de changer de répertoire vers "%s".%s', $cwd, PHP_EOL)); | |
} | |
// Liste des fichiers modifiés | |
$diff = shell_exec(sprintf('git diff --name-only %s', $commit)); | |
$files = array_filter(explode(PHP_EOL, $diff)); | |
// Répertoires créés | |
$dirnames = []; | |
foreach ($files as $file) { | |
// Fichier supprimé | |
if (!file_exists($file)) { | |
$rm = sprintf('ssh %s rm -f "%s/%s"', $host, $path, $file); | |
shell_exec($rm); | |
echo $rm, PHP_EOL; | |
continue; | |
} | |
$dirname = dirname($file); | |
$dirname = $dirname === '.' ? '' : $dirname; | |
// Création du répertoire distant s'il n'existe pas | |
if (!empty($dirname) && !in_array($dirname, $dirnames)) { | |
$mkdirp = sprintf('ssh %s mkdir -p "%s/%s"', $host, $path, $dirname); | |
shell_exec($mkdirp); | |
echo $mkdirp, PHP_EOL; | |
$dirnames[] = $dirname; | |
} | |
// Fichier ajouté ou modifié | |
$scp = sprintf('scp "%s" "%s:%s/%s"', $file, $host, $path, $dirname); | |
shell_exec($scp); | |
echo $scp, PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment