Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Created August 8, 2019 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cereal-s/799ab9c97a82f35147351024e9b6afa0 to your computer and use it in GitHub Desktop.
Save cereal-s/799ab9c97a82f35147351024e9b6afa0 to your computer and use it in GitHub Desktop.
Compare list of files
<?php
try {
function _trim($str) {
return rtrim(trim($str, ' \r\t\n\0\x0B'), ' /');
}
# paths to compare
$dir1 = isset($argv[1]) ? _trim($argv[1]) : null;
$dir2 = isset($argv[2]) ? _trim($argv[2]) : null;
touch("/tmp/ORIGINAL.txt");
touch("/tmp/DESTINATION.txt");
$tmp1 = "/tmp/ORIGINAL.txt";
$tmp2 = "/tmp/DESTINATION.txt";
# file type
$ftype = isset($argv[3]) ? '*.' . _trim($argv[3]) : null;
# file comparison
$only_compare = false;
if('-files' === $dir1) {
$only_compare = true;
} elseif(null === $dir1 || null === $dir2 || null === $ftype) {
throw new Exception("Provide all arguments", 1);
}
if(false === $only_compare) {
# md5sum files
print 'Hashing the files on '. $dir1 . '/' . $ftype . PHP_EOL;
`md5sum "{$dir1}/"{$ftype} > {$tmp1}` . PHP_EOL;
print 'Hashing the files on '. $dir2 . '/' . $ftype . PHP_EOL;
`md5sum "{$dir2}/"{$ftype} > {$tmp2}` . PHP_EOL;
}
# compare
print 'Comparing the files' . PHP_EOL;
print `diff -q {$tmp1} {$tmp2}` . PHP_EOL;
# continue
print 'Do you want to see the differences?' . PHP_EOL;
$handle = fopen('php://stdin', 'r');
$line = fgets($handle);
if('yes' == trim($line) || 'y' == trim($line)) {
print `diff -y {$tmp1} {$tmp2}`;
} else {
throw new Exception("Exiting...", 2);
}
} catch (Exception $e) {
print 'Code: ' . $e->getCode() . PHP_EOL;
print 'Message: ' . $e->getMessage() . PHP_EOL;
print 'To make the lists and compare do: ' . PHP_EOL;
print 'php ./compare.php PATH_1 PATH_2 FILE_TYPE' . PHP_EOL;
print 'To just compare lists do: ' . PHP_EOL;
print 'php ./compare.php -files';
} finally {
if(isset($handle)) {
fclose($handle);
}
print PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment