-
Notifications
You must be signed in to change notification settings - Fork 53
/
cp
executable file
·424 lines (350 loc) · 12 KB
/
cp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/perl
=begin metadata
Name: cp
Description: copy files and/or directories
Author: Ken Schumack, schumacks@att.net
License: perl
=end metadata
=cut
require 5;
use strict;
use Cwd;
use Config;
use File::Basename;
use File::Find;
use File::Spec::Functions qw(catfile);
use Getopt::Std;
####### S U B R O U T I N E S ###############
sub insufficientArgs($);
sub printUsage();
sub checkArgs(@);
sub findCopy; ## used by find()
sub copyFile($$); ## used by find()
=pod
B<-f> Force copy if possible (DEFAULT)
B<-i> Prompt for confirmation whenever the copy would overwrite an existing target.
B<-p> Preserve source file attributes (like modDate) as much as possible onto the target.
B<-v> Verbose. Echo "cp source target" before copy is done.
=cut
run(@ARGV) unless caller;
sub run {
my @args = @_;
require Getopt::Long;
my %opts;
my $ret = Getopt::Long::GetOptionsFromArray(
\@args,
'f' => \$opts{'f'},
'i' => \$opts{'i'},
'p' => \$opts{'p'},
'v' => \$opts{'v'},
);
my( $source, $destination ) = @args;
my @unix_like = qw(darwin freebsd linux);
if( $^O eq 'MSWin32' ) {
# https://home.csulb.edu/~murdock/copy.html
my @command = 'cmd', '/c', 'copy';
push @command, '/-Y' if $opts{i};
push @command, $source, $destination;
print "cp $source $destination\n" if $opts{v};
my $rc = system { $command[0] } @command
}
elsif( grep { $^O eq $_ } @unix_like and in_path('cp') ) {
# Although File::Copy seems like it should do the right thing,
# it doesn't.
my @command = 'cp';
push @command, map { "-$_" } grep { $opts{$_} } qw(i f p v );
push @command, $source, $destination;
my $rc = system { $command[0] } @command
}
else {
require File::Copy;
print "cp $source $destination\n" if $opts{v};
File::Copy::copy( $source, $destination );
}
};
sub in_path {
my( $command ) = @_;
foreach my $dir ( split /$Config{path_sep}/, $ENV{PATH} ) {
my $path = catfile( $dir, $command );
return 1 if -x $path;
}
return 0;
}
__END__
####### P R O C E S S - O P T I O N S ####################################
my $VERBOSE = 0;
my $PRESERVE = 0;
unless (getopts("fipv"))
{
&printUsage();
exit 1;
}
if (defined $main::opt_f) { $main::opt_i = undef; } ## -f overrides -i
$VERBOSE = 1 if (defined $main::opt_v);
$PRESERVE = 1 if (defined $main::opt_p);
#######
$cp::BINMODE = 1; ## default cp is binary mode
$cp::CWD = cwd(); ## where user invoked command
$cp::EXIT_STATUS = 0; ## this means everything worked
#$cp::PATH; ## used below ... mentioned here
#$cp::TARGET; ## used below
####### O S S T U F F ####################################################
$cp::USES_DRIVE_LETTER = 0; ## the Windows 'C:\' type of thing...
if ($^O =~ /Win32/i)
{
$cp::USES_DRIVE_LETTER = 1;
}
## Do not use binary mode on some OS's ...
#if ( $^O =~ /????/i ) ## need some help here
#{
# $cp::BINMODE = 0;
#}
$cp::CASE_SENSITIVE = 1;
$cp::CWD =~ s|\\|/|g; ## normalize for compares
####### C H E C K P A T H S & C L E A N U P I F N E E D E D ######
my @paths = checkArgs(@ARGV); ## checks and cleans up args
if ($#paths < 1) ## need at least one source and a target
{
insufficientArgs($#paths);
&printUsage();
exit 1;
}
####### E S T A B L I S H T H E T A R G E T ############################
my $target = pop @paths; ## last is target...
####### M O V E S O U R C E S T O T A R G E T ########################
for my $path (@paths)
{
my $current_target = $target;
if (-d $target)
{
my $base_path = basename($path);
$current_target = "$target/$base_path";
}
if ($path eq $current_target) ## check again... compare may wk out after code above
{
print STDERR "cp: $path and target $current_target are identical ... skipping\n";
$cp::EXIT_STATUS++;
next;
}
## copy it ...
if (! -d $path) ## cp'ing a file
{
copyFile($path, $current_target);
}
else ## cp'ing a directory
{
print "cp $path $current_target\n" if $VERBOSE;
$cp::TARGET = $current_target;
$cp::PATH = $path;
&File::Find::find(\&findCopy, $path); ## copy files/dirs top -> down
}
}
exit $cp::EXIT_STATUS;
################################################################################
####### E N D O F C P
################################################################################
################################################################################
### This is called via find() to copy directory trees (top down)
sub findCopy
{
$_ = uc $_ if (! $cp::CASE_SENSITIVE);
my $dir_tail = cwd(); ## find() has "cd'ed" us here...
$dir_tail = uc $dir_tail if (! $cp::CASE_SENSITIVE);
$dir_tail =~ s|^$cp::PATH||;
$dir_tail = "$dir_tail/" unless $dir_tail eq "";
if (-d $_)
{
$_ =~ s|\.$||;
$_ =~ s|\/$|| unless $_ eq '/';
mkdir "$cp::TARGET/dir_tail$_", 0777; ## umask will modify
if (! -d "$cp::TARGET/$dir_tail$_")
{
print STDERR "mv: Unable to create dir $cp::TARGET/$dir_tail/$_\n";
$cp::EXIT_STATUS++;
}
}
else
{
if ((defined $main::opt_i) && (-e "$cp::TARGET/$dir_tail/$_"))
{
my $path2show = "$cp::TARGET/$dir_tail/$_";
$path2show =~ s|^$cp::CWD|.|;
print STDERR "cp: overwrite $path2show (yes/no)? ";
my $response = <STDIN>;
return if ($response !~ /^y/i);
}
copyFile($_, "$cp::TARGET/$dir_tail/$_");
}
}
################################################################################
### This copies a single file
sub copyFile($$)
{ ## source, target
my ($path, $target) = @_;
$path = uc $path if (! $cp::CASE_SENSITIVE);
$target = uc $target if (! $cp::CASE_SENSITIVE);
if ((defined $main::opt_i) && (-e $target)) ## used if '-i' option was given
{
my $path2show = $target;
$path2show =~ s|^$cp::CWD|.|;
print STDERR "cp: overwrite $path2show (yes/no)? ";
my $response = <STDIN>;
return if ($response !~ /^y/i); ## not this one
}
print "cp $path $target\n" if $VERBOSE;
open(PATH, '<', $path) or die "Unable to read $path: $!";
open(TARGET, '>', $target) or die "Unable to create $target: $!";
if ($cp::BINMODE) { binmode PATH; binmode TARGET; }
my $buffer;
while (read PATH, $buffer, 1024) { print TARGET $buffer; }
close PATH;
close TARGET;
if ($PRESERVE) ## preserve as many file attributes as possible...
{
my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat $path;
utime $atime, $mtime, ($target);
chown $uid, $gid, ($target);
my $oldMode = (07777 & $mode); ## from man -s 2 mknod
chmod $oldMode, $target;
}
}
################################################################################
## print Insufficient arguments error
sub insufficientArgs($)
{
my $arg_num = ($_[0] + 1); ## num to display
print STDERR "cp: Insufficient arguments ($arg_num)\n";
$cp::EXIT_STATUS++;
}
################################################################################
sub printUsage()
{
print STDERR <<EOE
Usage: cp [-fivp] file1 file2
cp [-fivp] file1... filex dir
cp [-fivp] dir1... dirx dir
cp [-fivp] dir1... dirx file1... filex dir
EOE
}
################################################################################
sub checkArgs(@)
{
my $target = $_[$#_];
if ($#_ > 1) ### cp'ing > 1 thing target has to be an existing directory
{
if (! -e $target) ## has to be an existing directory... sorry it's over
{
print STDERR "cp: $target not found\n";
print STDERR " exiting...\n";
$cp::EXIT_STATUS++;
exit $cp::EXIT_STATUS
}
elsif (! -d $target) ## can only work if a directory...
{
print STDERR "cp: Target $target must be a directory when cp'ing > 1 thing\n";
print STDERR " exiting...\n";
printUsage();
$cp::EXIT_STATUS++;
exit $cp::EXIT_STATUS
}
}
my $paths = "";
my $Cwd = cwd();
$Cwd = uc $Cwd if (! $cp::CASE_SENSITIVE);
$Cwd =~ s|[/\\]$|| unless $Cwd eq '/'; ## remove any possible trailing slash (DOS or UNIX style)
my @paths = "";
for my $path (@_) ## check all paths passed in
{
$path =~ s|\\|/|g; ## normalize
## if OS is not case sensitive then let's just set to uc and make life easy
$path = uc $path if (! $cp::CASE_SENSITIVE);
if ((! -e $path) && ($path ne $target))
{
print STDERR "cp: can not access $path ... skipping\n";
$cp::EXIT_STATUS++;
## continue on... ignore this one
}
elsif (((! -d $path) && (! -r $path)) && ($path ne $target))
{
print STDERR "cp: can not read $path ... skipping\n";
$cp::EXIT_STATUS++;
## continue on... ignore this one
}
else
{
$path =~ s|^\.\/||; ## no need for './' at the path start
if ($path =~ /^\.\.\//) ## change relative to full path
{ ## ../../abc to /aaa/bbb/ccc/abc
my $path_front = $Cwd;
$path_front = uc $path if (! $cp::CASE_SENSITIVE);
while ($path =~ /^\.\.\//)
{
$path =~ s|^...||;
$path_front =~ s|(.*)\/[^\/]+|$1/|;
}
$path = $path_front.$path;
}
elsif (($path !~ /\//) && ($path !~ /^[a-z]:/i) && $cp::USES_DRIVE_LETTER) ## it's right here...
{
$path = "$Cwd/$path";
}
elsif (($path !~ /\//) && (! $cp::USES_DRIVE_LETTER)) ## it's right here...
{
$path = "$Cwd/$path";
}
while ($path =~ /\/\.\./) ## remove '/..' from middle or end of path
{
$path =~ s|[^\/]+\/\.\.||;
}
$path =~ s|\/\.?$|| unless $path eq '/'; ## remove '/' or '/.' from end of path
my $path_cnt = 0; ## number used for splicing
for my $tmpPath (@paths)
{
if ($path eq $tmpPath)
{
print STDERR "cp: $path found more than once on command line. Ignoring 1st occurance\n";
$cp::EXIT_STATUS++;
splice @paths, $path_cnt, 1;
}
else
{
$path_cnt++;
}
}
push @paths, $path;
}
}
splice @paths, 0, 1; ## the "my @paths" initialization gave this....
return @paths; ## checked, cleaned, and ready to go...
}
__END__
=pod
=head1 NAME
cp - copy files and/or directories
=head1 SYNOPSIS
cp [ B<->B<fiv> ] source_file target_file
cp [ B<->B<fiv> ] source... target_dir
=head1 DESCRIPTION
The cp utility copies the source files/directories to the target. If the
target is a file you may only specify one file as the source. cp will not
copy a file onto itself.
=head2 OPTIONS
B<-f> Force copy if possible (DEFAULT)
B<-i> Prompt for confirmation whenever the copy would overwrite an existing target.
B<-p> Preserve source file attributes (like modDate) as much as possible onto the target.
B<-v> Verbose. Echo "cp source target" before copy is done.
Specifying both B<-f> and B<-i> options is not considered an
error. The B<-f> option will override the B<-i> option.
=head1 BUGS
B<cp> has no known bugs, but be aware that the current copy mode
is binary mode.
=head1 EXIT STATUS
0 = All sources were copied successfully.
=head1 AUTHOR
This Perl implementation of B<cp> was written by Ken Schumack schumacks@att.net
=head1 COPYRIGHT and LICENSE
This program is copyright by Ken Schumack 1999.
This program is free and open software. You may use, modify, distribute
and sell this program (and any modified variants) in any way you wish,
provided you do not restrict others from doing the same.
=cut