4 |
use autodie; |
use autodie; |
5 |
use Carp qw/carp confess/; |
use Carp qw/carp confess/; |
6 |
use File::Path qw//; |
use File::Path qw//; |
7 |
|
use Data::Dump qw/dump/; |
8 |
|
|
9 |
|
my $debug = 1; |
10 |
|
|
11 |
sub mkpath { |
sub mkpath { |
12 |
my $file = shift; |
my $file = shift; |
13 |
my $dir = $1 if $file =~ s{^.+/[^/]+}{}; |
my $dir = $1 if $file =~ s{(^.+)/[^/]+}{$1}; |
14 |
File::Path::mkpath $dir unless -e $dir; |
if ( $dir && ! -d $dir ) { |
15 |
|
carp "# mkdir $dir"; |
16 |
|
File::Path::mkpath $dir; |
17 |
|
} |
18 |
} |
} |
19 |
|
|
20 |
sub append { |
sub append { |
24 |
mkpath $file; |
mkpath $file; |
25 |
write_file $file, $content; |
write_file $file, $content; |
26 |
my $size = -s $file; |
my $size = -s $file; |
27 |
carp "append created $size bytes in $file"; |
carp "## append created $size bytes in $file"; |
28 |
return $size; |
return $size; |
29 |
} |
} |
30 |
|
|
31 |
my $on_disk = read_file $file; |
my $on_disk = read_file $file; |
32 |
|
|
33 |
my $relaxed_content =~ s{\s+}{\\s+}gs; |
my $relaxed_content = $content; |
34 |
|
$relaxed_content =~ s{\s+}{\\s+}gs; |
35 |
|
|
36 |
if ( $on_disk !~ m{$relaxed_content} ) { |
if ( $on_disk !~ m{$relaxed_content} ) { |
37 |
|
|
38 |
# $content =~ s{^[\n\r]+}{\n}s; |
# $content =~ s{^[\n\r]+}{\n}s; |
39 |
# $content =~ s{[\n\r]*$}{\n}s; |
# $content =~ s{[\n\r]*$}{\n}s; |
40 |
|
|
41 |
open($fh, '>>', $file); |
if ( $on_disk =~ s{([\s+]exit[\s\d]*)$}{\n$content\n$1}s ) { |
42 |
print $fh $content; |
# warn "# insert $file\n$on_disk"; |
43 |
close($fh); |
write_file $file, $on_disk; |
44 |
|
} else { |
45 |
|
# warn "# append $file\n$content\n"; |
46 |
|
open($fh, '>>', $file); |
47 |
|
print $fh $content; |
48 |
|
close($fh); |
49 |
|
} |
50 |
|
|
51 |
my $size = length($content); |
carp "## append to $file"; |
52 |
|
return -s $file; |
|
carp "append $size bytes to $file"; |
|
|
warn $content; |
|
|
return $size; |
|
53 |
} |
} |
54 |
} |
} |
55 |
|
|
59 |
my $content = read_file $file; |
my $content = read_file $file; |
60 |
if ( $content =~ s{$from}{$to}s ) { |
if ( $content =~ s{$from}{$to}s ) { |
61 |
write_file $file, $content; |
write_file $file, $content; |
62 |
carp "change $file $from => $to"; |
carp "## change $file $from => $to" if $debug; |
63 |
return 1; |
return 1; |
64 |
} elsif ( $content !~ m{$to}s ) { |
} elsif ( $content !~ m{$to}s ) { |
65 |
confess "can't find $from to change into $to in $file"; |
confess "can't find $from to change into $to in $file in ",dump( $content ); |
66 |
} |
} |
67 |
} |
} |
68 |
|
|
69 |
|
sub replace { |
70 |
|
my ( $file, $content ) = @_; |
71 |
|
mkpath $file; |
72 |
|
write_file $file, $content; |
73 |
|
} |
74 |
|
|
75 |
|
sub copy_once { |
76 |
|
my ( $from, $to ) = @_; |
77 |
|
die "no destination" unless $to; |
78 |
|
return if -e $to; |
79 |
|
mkpath $to; |
80 |
|
carp "# copy_once $from => $to"; |
81 |
|
write_file $to, read_file($from); |
82 |
|
} |
83 |
|
|
84 |
1; |
1; |