Skip to content

Instantly share code, notes, and snippets.

@nekoya
Created May 28, 2009 07:11
Show Gist options
  • Save nekoya/119154 to your computer and use it in GitHub Desktop.
Save nekoya/119154 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use local::lib;
use File::Temp;
use FindBin;
use Getopt::Long;
# Help messages
my $usage = <<'END_USAGE';
rdiff - ローカルとリモートのファイルのdiffを取る
Usage: rdiff [--help] filename server
Options:
-h(--help) このヘルプを表示
filenameにはディレクトリも指定可能。
serverはサーバ名を1つだけ指定。
diffの出力オプションには環境変数 $DIFF_OPT の値が適用される。
ex)
rdiff /etc/passwd u1
u1との/etc/passwdのdiffを取る
DIFF_OPT='-U 1' rdiff ~/.ssh u1
u1との~/.sshのdiffを取る。diffの出力は-U 1で。
Written by Ryo Miyake<ryo.studiom@gmail.com>
END_USAGE
# init
my $diffOpt = $ENV{DIFF_OPT} || '';
# analyze options
my %opt;
usage() if !GetOptions(
\%opt,
'help',
);
usage() if $opt{help};
# Main
eval {
# Analyze arguments
my $file = shift @ARGV or die;
my $s = shift @ARGV or die;
die if @ARGV;
# Compare file
if (-f $file) {
my $fh = File::Temp->new or die("Failed create temporary file.");
my $tmpfile = $fh->filename;
system "scp $s:$file $tmpfile 2>/dev/null";
system "diff $diffOpt $file $tmpfile";
}
# Compare directory
elsif (-d $file) {
# get local hash
my $fh1 = File::Temp->new or die("Failed create temporary file.");
my $fn1 = $fh1->filename;
for my $d (`find "$file" -type d|sort`) {
chomp $d;
print $fh1 "$d\n";
}
for my $f (`find "$file" -type f|sort`) {
chop $f;
my $md5 = (split(/ /, `md5sum $f 2>/dev/null`))[0];
print $fh1 sprintf("%-32s %s\n", $f, $md5);
}
# get remote hash
my $fh2 = File::Temp->new or die("Failed create temporary file.");
my $fn2 = $fh2->filename;
for my $d (`ssh $s find "$file" -type d|sort`) {
chomp $d;
print $fh2 "$d\n";
}
for my $f (`ssh $s find "$file" -type f|sort`) {
chomp $f;
next if !$f;
my $md5 = (split(/ /, `ssh $s md5sum $f 2>/dev/null`))[0];
print $fh2 sprintf("%-32s %s\n", $f, $md5);
}
system "diff $diffOpt $fn1 $fn2";
#print "--- $fn1 ---\n";
#system "cat $fn1";
#print "--- $fn2 ---\n";
#system "cat $fn2";
}
};
if ( $@ ) {
usage() if $@ =~ /^Died at /;
die $@;
}
sub usage {
print $usage;
exit 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment