File Coverage

blib/lib/File/Util/Rename.pm
Criterion Covered Total %
statement 14 38 36.8
branch 0 16 0.0
condition 0 4 0.0
subroutine 5 7 71.4
pod 2 2 100.0
total 21 67 31.3


line stmt bran cond sub pod time code
1             package File::Util::Rename;
2              
3 2     2   339931 use 5.010001;
  2         8  
4 2     2   12 use strict;
  2         4  
  2         56  
5 2     2   15 use warnings;
  2         3  
  2         110  
6 2     2   3984 use Log::ger;
  2         122  
  2         13  
7              
8 2     2   587 use Exporter 'import';
  2         3  
  2         1121  
9              
10             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
11             our $DATE = '2025-03-28'; # DATE
12             our $DIST = 'File-Util-Rename'; # DIST
13             our $VERSION = '0.003'; # VERSION
14              
15             our @EXPORT_OK = qw(
16             rename_noclobber
17             rename_warnclobber
18             );
19              
20             sub rename_noclobber {
21 0 0   0 1   my $opts = ref $_[0] eq 'HASH' ? shift : {};
22 0   0       $opts->{pattern} //= " (%02d)";
23              
24 0           my ($from, $to) = @_;
25 0 0         my $ext; $to =~ s/(\.\w+)\z// and $ext = $1;
  0            
26              
27 0           my $i = 0;
28 0           my $to_final;
29 0           while (1) {
30 0 0         if ($i) {
31 0           my $suffix = sprintf $opts->{pattern}, $i;
32 0 0         $to_final = $ext ? "$to$suffix$ext" : "$to$suffix";
33             } else {
34 0           $to_final = $to;
35             }
36 0           lstat $to_final;
37 0 0         last unless -e _;
38 0           $i++;
39             }
40 0           rename $from, $to_final;
41             }
42              
43             sub rename_warnclobber {
44 0 0   0 1   my $opts = ref $_[0] eq 'HASH' ? shift : {};
45 0   0       $opts->{log} //= 0;
46              
47 0           my ($from, $to) = @_;
48              
49 0 0         if (-e $to) {
50 0 0         if ($opts->{log}) {
51 0           log_warn "rename_warnclobber(`$from`, `$to`): Target already exists, renaming anyway ...";
52             } else {
53 0           warn "rename_warnclobber(`$from`, `$to`): Target already exists, renaming anyway ...\n";
54             }
55             }
56              
57 0           rename $from, $to;
58             }
59              
60             1;
61             # ABSTRACT: Utilities related to renaming files
62              
63             __END__