our
$VERSION
=
'1.16.0'
;
@EXPORT
=
qw(md5)
;
sub
md5 {
my
(
$file
) =
@_
;
my
$fs
= Rex::Interface::Fs->create;
if
(
$fs
->is_file(
$file
) ) {
Rex::Logger::debug(
"Calculating checksum (MD5) of $file"
);
my
$md5
= _digest_md5(
$file
) // _binary_md5(
$file
);
if
( !
$md5
) {
my
$message
=
"Unable to get MD5 checksum of $file: $!"
;
Rex::Logger::info(
$message
);
die
(
$message
);
}
Rex::Logger::debug(
"MD5 checksum of $file: $md5"
);
return
$md5
;
}
else
{
my
$message
=
"File not found: $file"
;
Rex::Logger::debug(
$message
);
die
(
$message
);
}
}
sub
_digest_md5 {
my
$file
=
shift
;
my
$md5
;
my
$perl
= Rex::is_local() ?
$EXECUTABLE_NAME
:
'perl'
;
my
$command
=
( $^O =~ m/^MSWin/i && Rex::is_local() )
?
qq("$perl" -MDigest::MD5 -e "open my \$fh, '<', \$ARGV[0] or die 'Cannot open ' . \$ARGV[0]; binmode \$fh; print Digest::MD5->new->addfile(\$fh)
->hexdigest;"
"$file"
)
:
qq('$perl' -MDigest::MD5 -e 'open my \$fh, "<", \$ARGV[0] or die "Cannot open " . \$ARGV[0]; binmode \$fh; print Digest::MD5->new->addfile(\$fh)
->hexdigest;'
'$file'
);
my
$result
= i_run(
$command
,
fail_ok
=> 1 );
if
( $? == 0 ) {
$md5
=
$result
;
}
return
$md5
;
}
sub
_binary_md5 {
my
$file
=
shift
;
my
$md5
;
my
$exec
= Rex::Interface::Exec->create;
if
( Rex::Commands::Run::can_run(
'md5'
) ) {
(
$md5
) =
$exec
->
exec
(
"md5 '$file'"
) =~
qr{\s+=\s+([a-f0-9]{32}
)\s*$};
}
elsif
( Rex::Commands::Run::can_run(
'md5sum'
) ) {
(
$md5
) =
$exec
->
exec
(
"md5sum '$file'"
) =~
qr{^\\?([a-f0-9]{32}
)\s+};
}
return
$md5
;
}
1;