Copy.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # File/Copy.pm. Written in 1994 by Aaron Sherman <ajs@ajs.com>. This
  2. # source code has been placed in the public domain by the author.
  3. # Please be kind and preserve the documentation.
  4. #
  5. # Additions copyright 1996 by Charles Bailey. Permission is granted
  6. # to distribute the revised code under the same terms as Perl itself.
  7. package File::Copy;
  8. use 5.006;
  9. use strict;
  10. use warnings; no warnings 'newline';
  11. use File::Spec;
  12. use Config;
  13. # During perl build, we need File::Copy but Scalar::Util might not be built yet
  14. # And then we need these games to avoid loading overload, as that will
  15. # confuse miniperl during the bootstrap of perl.
  16. my $Scalar_Util_loaded = eval q{ require Scalar::Util; require overload; 1 };
  17. our(@ISA, @EXPORT, @EXPORT_OK, $VERSION, $Too_Big, $Syscopy_is_copy);
  18. sub copy;
  19. sub syscopy;
  20. sub cp;
  21. sub mv;
  22. $VERSION = '2.30';
  23. require Exporter;
  24. @ISA = qw(Exporter);
  25. @EXPORT = qw(copy move);
  26. @EXPORT_OK = qw(cp mv);
  27. $Too_Big = 1024 * 1024 * 2;
  28. sub croak {
  29. require Carp;
  30. goto &Carp::croak;
  31. }
  32. sub carp {
  33. require Carp;
  34. goto &Carp::carp;
  35. }
  36. sub _catname {
  37. my($from, $to) = @_;
  38. if (not defined &basename) {
  39. require File::Basename;
  40. import File::Basename 'basename';
  41. }
  42. return File::Spec->catfile($to, basename($from));
  43. }
  44. # _eq($from, $to) tells whether $from and $to are identical
  45. sub _eq {
  46. my ($from, $to) = map {
  47. $Scalar_Util_loaded && Scalar::Util::blessed($_)
  48. && overload::Method($_, q{""})
  49. ? "$_"
  50. : $_
  51. } (@_);
  52. return '' if ( (ref $from) xor (ref $to) );
  53. return $from == $to if ref $from;
  54. return $from eq $to;
  55. }
  56. sub copy {
  57. croak("Usage: copy(FROM, TO [, BUFFERSIZE]) ")
  58. unless(@_ == 2 || @_ == 3);
  59. my $from = shift;
  60. my $to = shift;
  61. my $size;
  62. if (@_) {
  63. $size = shift(@_) + 0;
  64. croak("Bad buffer size for copy: $size\n") unless ($size > 0);
  65. }
  66. my $from_a_handle = (ref($from)
  67. ? (ref($from) eq 'GLOB'
  68. || UNIVERSAL::isa($from, 'GLOB')
  69. || UNIVERSAL::isa($from, 'IO::Handle'))
  70. : (ref(\$from) eq 'GLOB'));
  71. my $to_a_handle = (ref($to)
  72. ? (ref($to) eq 'GLOB'
  73. || UNIVERSAL::isa($to, 'GLOB')
  74. || UNIVERSAL::isa($to, 'IO::Handle'))
  75. : (ref(\$to) eq 'GLOB'));
  76. if (_eq($from, $to)) { # works for references, too
  77. carp("'$from' and '$to' are identical (not copied)");
  78. return 0;
  79. }
  80. if (!$from_a_handle && !$to_a_handle && -d $to && ! -d $from) {
  81. $to = _catname($from, $to);
  82. }
  83. if ((($Config{d_symlink} && $Config{d_readlink}) || $Config{d_link}) &&
  84. !($^O eq 'MSWin32' || $^O eq 'os2')) {
  85. my @fs = stat($from);
  86. if (@fs) {
  87. my @ts = stat($to);
  88. if (@ts && $fs[0] == $ts[0] && $fs[1] == $ts[1] && !-p $from) {
  89. carp("'$from' and '$to' are identical (not copied)");
  90. return 0;
  91. }
  92. }
  93. }
  94. elsif (_eq($from, $to)) {
  95. carp("'$from' and '$to' are identical (not copied)");
  96. return 0;
  97. }
  98. if (defined &syscopy && !$Syscopy_is_copy
  99. && !$to_a_handle
  100. && !($from_a_handle && $^O eq 'os2' ) # OS/2 cannot handle handles
  101. && !($from_a_handle && $^O eq 'MSWin32')
  102. && !($from_a_handle && $^O eq 'NetWare')
  103. )
  104. {
  105. if ($^O eq 'VMS' && -e $from
  106. && ! -d $to && ! -d $from) {
  107. # VMS natively inherits path components from the source of a
  108. # copy, but we want the Unixy behavior of inheriting from
  109. # the current working directory. Also, default in a trailing
  110. # dot for null file types.
  111. $to = VMS::Filespec::rmsexpand(VMS::Filespec::vmsify($to), '.');
  112. # Get rid of the old versions to be like UNIX
  113. 1 while unlink $to;
  114. }
  115. return syscopy($from, $to) || 0;
  116. }
  117. my $closefrom = 0;
  118. my $closeto = 0;
  119. my ($status, $r, $buf);
  120. local($\) = '';
  121. my $from_h;
  122. if ($from_a_handle) {
  123. $from_h = $from;
  124. } else {
  125. open $from_h, "<", $from or goto fail_open1;
  126. binmode $from_h or die "($!,$^E)";
  127. $closefrom = 1;
  128. }
  129. # Seems most logical to do this here, in case future changes would want to
  130. # make this croak for some reason.
  131. unless (defined $size) {
  132. $size = tied(*$from_h) ? 0 : -s $from_h || 0;
  133. $size = 1024 if ($size < 512);
  134. $size = $Too_Big if ($size > $Too_Big);
  135. }
  136. my $to_h;
  137. if ($to_a_handle) {
  138. $to_h = $to;
  139. } else {
  140. $to_h = \do { local *FH }; # XXX is this line obsolete?
  141. open $to_h, ">", $to or goto fail_open2;
  142. binmode $to_h or die "($!,$^E)";
  143. $closeto = 1;
  144. }
  145. $! = 0;
  146. for (;;) {
  147. my ($r, $w, $t);
  148. defined($r = sysread($from_h, $buf, $size))
  149. or goto fail_inner;
  150. last unless $r;
  151. for ($w = 0; $w < $r; $w += $t) {
  152. $t = syswrite($to_h, $buf, $r - $w, $w)
  153. or goto fail_inner;
  154. }
  155. }
  156. close($to_h) || goto fail_open2 if $closeto;
  157. close($from_h) || goto fail_open1 if $closefrom;
  158. # Use this idiom to avoid uninitialized value warning.
  159. return 1;
  160. # All of these contortions try to preserve error messages...
  161. fail_inner:
  162. if ($closeto) {
  163. $status = $!;
  164. $! = 0;
  165. close $to_h;
  166. $! = $status unless $!;
  167. }
  168. fail_open2:
  169. if ($closefrom) {
  170. $status = $!;
  171. $! = 0;
  172. close $from_h;
  173. $! = $status unless $!;
  174. }
  175. fail_open1:
  176. return 0;
  177. }
  178. sub cp {
  179. my($from,$to) = @_;
  180. my(@fromstat) = stat $from;
  181. my(@tostat) = stat $to;
  182. my $perm;
  183. return 0 unless copy(@_) and @fromstat;
  184. if (@tostat) {
  185. $perm = $tostat[2];
  186. } else {
  187. $perm = $fromstat[2] & ~(umask || 0);
  188. @tostat = stat $to;
  189. }
  190. # Might be more robust to look for S_I* in Fcntl, but we're
  191. # trying to avoid dependence on any XS-containing modules,
  192. # since File::Copy is used during the Perl build.
  193. $perm &= 07777;
  194. if ($perm & 06000) {
  195. croak("Unable to check setuid/setgid permissions for $to: $!")
  196. unless @tostat;
  197. if ($perm & 04000 and # setuid
  198. $fromstat[4] != $tostat[4]) { # owner must match
  199. $perm &= ~06000;
  200. }
  201. if ($perm & 02000 && $> != 0) { # if not root, setgid
  202. my $ok = $fromstat[5] == $tostat[5]; # group must match
  203. if ($ok) { # and we must be in group
  204. $ok = grep { $_ == $fromstat[5] } split /\s+/, $)
  205. }
  206. $perm &= ~06000 unless $ok;
  207. }
  208. }
  209. return 0 unless @tostat;
  210. return 1 if $perm == ($tostat[2] & 07777);
  211. return eval { chmod $perm, $to; } ? 1 : 0;
  212. }
  213. sub _move {
  214. croak("Usage: move(FROM, TO) ") unless @_ == 3;
  215. my($from,$to,$fallback) = @_;
  216. my($fromsz,$tosz1,$tomt1,$tosz2,$tomt2,$sts,$ossts);
  217. if (-d $to && ! -d $from) {
  218. $to = _catname($from, $to);
  219. }
  220. ($tosz1,$tomt1) = (stat($to))[7,9];
  221. $fromsz = -s $from;
  222. if ($^O eq 'os2' and defined $tosz1 and defined $fromsz) {
  223. # will not rename with overwrite
  224. unlink $to;
  225. }
  226. if ($^O eq 'VMS' && -e $from
  227. && ! -d $to && ! -d $from) {
  228. # VMS natively inherits path components from the source of a
  229. # copy, but we want the Unixy behavior of inheriting from
  230. # the current working directory. Also, default in a trailing
  231. # dot for null file types.
  232. $to = VMS::Filespec::rmsexpand(VMS::Filespec::vmsify($to), '.');
  233. # Get rid of the old versions to be like UNIX
  234. 1 while unlink $to;
  235. }
  236. return 1 if rename $from, $to;
  237. # Did rename return an error even though it succeeded, because $to
  238. # is on a remote NFS file system, and NFS lost the server's ack?
  239. return 1 if defined($fromsz) && !-e $from && # $from disappeared
  240. (($tosz2,$tomt2) = (stat($to))[7,9]) && # $to's there
  241. ((!defined $tosz1) || # not before or
  242. ($tosz1 != $tosz2 or $tomt1 != $tomt2)) && # was changed
  243. $tosz2 == $fromsz; # it's all there
  244. ($tosz1,$tomt1) = (stat($to))[7,9]; # just in case rename did something
  245. {
  246. local $@;
  247. eval {
  248. local $SIG{__DIE__};
  249. $fallback->($from,$to) or die;
  250. my($atime, $mtime) = (stat($from))[8,9];
  251. utime($atime, $mtime, $to);
  252. unlink($from) or die;
  253. };
  254. return 1 unless $@;
  255. }
  256. ($sts,$ossts) = ($! + 0, $^E + 0);
  257. ($tosz2,$tomt2) = ((stat($to))[7,9],0,0) if defined $tomt1;
  258. unlink($to) if !defined($tomt1) or $tomt1 != $tomt2 or $tosz1 != $tosz2;
  259. ($!,$^E) = ($sts,$ossts);
  260. return 0;
  261. }
  262. sub move { _move(@_,\&copy); }
  263. sub mv { _move(@_,\&cp); }
  264. # &syscopy is an XSUB under OS/2
  265. unless (defined &syscopy) {
  266. if ($^O eq 'VMS') {
  267. *syscopy = \&rmscopy;
  268. } elsif ($^O eq 'MSWin32' && defined &DynaLoader::boot_DynaLoader) {
  269. # Win32::CopyFile() fill only work if we can load Win32.xs
  270. *syscopy = sub {
  271. return 0 unless @_ == 2;
  272. return Win32::CopyFile(@_, 1);
  273. };
  274. } else {
  275. $Syscopy_is_copy = 1;
  276. *syscopy = \&copy;
  277. }
  278. }
  279. 1;
  280. __END__
  281. =head1 NAME
  282. File::Copy - Copy files or filehandles
  283. =head1 SYNOPSIS
  284. use File::Copy;
  285. copy("sourcefile","destinationfile") or die "Copy failed: $!";
  286. copy("Copy.pm",\*STDOUT);
  287. move("/dev1/sourcefile","/dev2/destinationfile");
  288. use File::Copy "cp";
  289. $n = FileHandle->new("/a/file","r");
  290. cp($n,"x");
  291. =head1 DESCRIPTION
  292. The File::Copy module provides two basic functions, C<copy> and
  293. C<move>, which are useful for getting the contents of a file from
  294. one place to another.
  295. =over 4
  296. =item copy
  297. X<copy> X<cp>
  298. The C<copy> function takes two
  299. parameters: a file to copy from and a file to copy to. Either
  300. argument may be a string, a FileHandle reference or a FileHandle
  301. glob. Obviously, if the first argument is a filehandle of some
  302. sort, it will be read from, and if it is a file I<name> it will
  303. be opened for reading. Likewise, the second argument will be
  304. written to. If the second argument does not exist but the parent
  305. directory does exist, then it will be created. Trying to copy
  306. a file into a non-existent directory is an error.
  307. Trying to copy a file on top of itself is also an error.
  308. C<copy> will not overwrite read-only files.
  309. If the destination (second argument) already exists and is a directory,
  310. and the source (first argument) is not a filehandle, then the source
  311. file will be copied into the directory specified by the destination,
  312. using the same base name as the source file. It's a failure to have a
  313. filehandle as the source when the destination is a directory.
  314. B<Note that passing in
  315. files as handles instead of names may lead to loss of information
  316. on some operating systems; it is recommended that you use file
  317. names whenever possible.> Files are opened in binary mode where
  318. applicable. To get a consistent behaviour when copying from a
  319. filehandle to a file, use C<binmode> on the filehandle.
  320. An optional third parameter can be used to specify the buffer
  321. size used for copying. This is the number of bytes from the
  322. first file, that will be held in memory at any given time, before
  323. being written to the second file. The default buffer size depends
  324. upon the file, but will generally be the whole file (up to 2MB), or
  325. 1k for filehandles that do not reference files (eg. sockets).
  326. You may use the syntax C<use File::Copy "cp"> to get at the C<cp>
  327. alias for this function. The syntax is I<exactly> the same. The
  328. behavior is nearly the same as well: as of version 2.15, C<cp> will
  329. preserve the source file's permission bits like the shell utility
  330. C<cp(1)> would do, while C<copy> uses the default permissions for the
  331. target file (which may depend on the process' C<umask>, file
  332. ownership, inherited ACLs, etc.). If an error occurs in setting
  333. permissions, C<cp> will return 0, regardless of whether the file was
  334. successfully copied.
  335. =item move
  336. X<move> X<mv> X<rename>
  337. The C<move> function also takes two parameters: the current name
  338. and the intended name of the file to be moved. If the destination
  339. already exists and is a directory, and the source is not a
  340. directory, then the source file will be renamed into the directory
  341. specified by the destination.
  342. If possible, move() will simply rename the file. Otherwise, it copies
  343. the file to the new location and deletes the original. If an error occurs
  344. during this copy-and-delete process, you may be left with a (possibly partial)
  345. copy of the file under the destination name.
  346. You may use the C<mv> alias for this function in the same way that
  347. you may use the C<cp> alias for C<copy>.
  348. =item syscopy
  349. X<syscopy>
  350. File::Copy also provides the C<syscopy> routine, which copies the
  351. file specified in the first parameter to the file specified in the
  352. second parameter, preserving OS-specific attributes and file
  353. structure. For Unix systems, this is equivalent to the simple
  354. C<copy> routine, which doesn't preserve OS-specific attributes. For
  355. VMS systems, this calls the C<rmscopy> routine (see below). For OS/2
  356. systems, this calls the C<syscopy> XSUB directly. For Win32 systems,
  357. this calls C<Win32::CopyFile>.
  358. B<Special behaviour if C<syscopy> is defined (OS/2, VMS and Win32)>:
  359. If both arguments to C<copy> are not file handles,
  360. then C<copy> will perform a "system copy" of
  361. the input file to a new output file, in order to preserve file
  362. attributes, indexed file structure, I<etc.> The buffer size
  363. parameter is ignored. If either argument to C<copy> is a
  364. handle to an opened file, then data is copied using Perl
  365. operators, and no effort is made to preserve file attributes
  366. or record structure.
  367. The system copy routine may also be called directly under VMS and OS/2
  368. as C<File::Copy::syscopy> (or under VMS as C<File::Copy::rmscopy>, which
  369. is the routine that does the actual work for syscopy).
  370. =item rmscopy($from,$to[,$date_flag])
  371. X<rmscopy>
  372. The first and second arguments may be strings, typeglobs, typeglob
  373. references, or objects inheriting from IO::Handle;
  374. they are used in all cases to obtain the
  375. I<filespec> of the input and output files, respectively. The
  376. name and type of the input file are used as defaults for the
  377. output file, if necessary.
  378. A new version of the output file is always created, which
  379. inherits the structure and RMS attributes of the input file,
  380. except for owner and protections (and possibly timestamps;
  381. see below). All data from the input file is copied to the
  382. output file; if either of the first two parameters to C<rmscopy>
  383. is a file handle, its position is unchanged. (Note that this
  384. means a file handle pointing to the output file will be
  385. associated with an old version of that file after C<rmscopy>
  386. returns, not the newly created version.)
  387. The third parameter is an integer flag, which tells C<rmscopy>
  388. how to handle timestamps. If it is E<lt> 0, none of the input file's
  389. timestamps are propagated to the output file. If it is E<gt> 0, then
  390. it is interpreted as a bitmask: if bit 0 (the LSB) is set, then
  391. timestamps other than the revision date are propagated; if bit 1
  392. is set, the revision date is propagated. If the third parameter
  393. to C<rmscopy> is 0, then it behaves much like the DCL COPY command:
  394. if the name or type of the output file was explicitly specified,
  395. then no timestamps are propagated, but if they were taken implicitly
  396. from the input filespec, then all timestamps other than the
  397. revision date are propagated. If this parameter is not supplied,
  398. it defaults to 0.
  399. Like C<copy>, C<rmscopy> returns 1 on success. If an error occurs,
  400. it sets C<$!>, deletes the output file, and returns 0.
  401. =back
  402. =head1 RETURN
  403. All functions return 1 on success, 0 on failure.
  404. $! will be set if an error was encountered.
  405. =head1 AUTHOR
  406. File::Copy was written by Aaron Sherman I<E<lt>ajs@ajs.comE<gt>> in 1995,
  407. and updated by Charles Bailey I<E<lt>bailey@newman.upenn.eduE<gt>> in 1996.
  408. =cut