Recursive copy #1

Closed
wants to merge 2 commits into
from
+22 −11
Split
View
@@ -2,12 +2,16 @@ use v6;
module File::Copy;
-sub cp(Str $from, Str $to) is export {
- my $f1 = open $from, :r, :bin;
- my $f2 = open $to, :w, :bin;
- $f2.write($f1.read(4096)) until $f1.eof;
- $f1.close;
- $f2.close;
+sub cp(Str $from, Str $to, :$r) is export {
+ if ($from.IO ~~ :d and $r) {
+ mkdir("$to") if $to.IO !~~ :d;
+ for dir($from) -> $item {
+ mkdir("$to/$item") if "$from/$item".IO ~~ :d;
+ cp("$from/$item", "$to/$item", :r);
+ }
+ } else {
+ $from.IO.copy($to);
+ }
}
=begin pod
@@ -20,14 +24,13 @@ File::Copy -- copy files
use File::Copy;
- cp 'source', 'destination';
+ cp 'source', 'destination', :r;
=head1 DESCRIPTION
C<File::Copy> exports just one subroutine, cp taking two string
-parameters: source and destination. If something comes wrong, the
-internal open() or write() calls will die, C<copy()> has no special
-error reporting.
+parameters: source and destination and a recursion flag. If something
+goes wrong, IO.cp fails. There is no special error reporting.
=end pod
View
@@ -1,10 +1,18 @@
use v6;
use Test;
use File::Copy;
+use File::Find;
-cp 't/test.file', 't/another.file';
+cp 't/test.file', 't/another.file', :r;
is slurp('t/test.file'),
slurp('t/another.file'),
"copied file is identical";
+cp 't/dir1', 't/dir2', :r;
+is dir('t/dir1'),
+ dir('t/dir2'),
+ "recursive copy";
unlink 't/another.file';
+my @filelist := find(dir => 't/dir2');
+for @filelist.reverse -> $file { say $file; unlink $file; }
+unlink 't/dir2';
done;