1 |
package file; |
2 |
|
3 |
use File::Slurp; |
4 |
use autodie; |
5 |
use Carp qw/carp confess/; |
6 |
use File::Path qw//; |
7 |
|
8 |
sub mkpath { |
9 |
my $file = shift; |
10 |
my $dir = $1 if $file =~ s{^.+/[^/]+}{}; |
11 |
File::Path::mkpath $dir unless -e $dir; |
12 |
} |
13 |
|
14 |
sub append { |
15 |
my ( $file, $content ) = @_; |
16 |
|
17 |
if ( ! -e $file ) { |
18 |
mkpath $file; |
19 |
write_file $file, $content; |
20 |
my $size = -s $file; |
21 |
carp "append created $size bytes in $file"; |
22 |
return $size; |
23 |
} |
24 |
|
25 |
my $on_disk = read_file $file; |
26 |
|
27 |
my $relaxed_content =~ s{\s+}{\\s+}gs; |
28 |
|
29 |
if ( $on_disk !~ m{$relaxed_content} ) { |
30 |
|
31 |
# $content =~ s{^[\n\r]+}{\n}s; |
32 |
# $content =~ s{[\n\r]*$}{\n}s; |
33 |
|
34 |
open($fh, '>>', $file); |
35 |
print $fh $content; |
36 |
close($fh); |
37 |
|
38 |
my $size = length($content); |
39 |
|
40 |
carp "append $size bytes to $file"; |
41 |
warn $content; |
42 |
return $size; |
43 |
} |
44 |
} |
45 |
|
46 |
sub change { |
47 |
my ( $file, $from, $to ) = @_; |
48 |
|
49 |
my $content = read_file $file; |
50 |
if ( $content =~ s{$from}{$to}s ) { |
51 |
write_file $file, $content; |
52 |
carp "change $file $from => $to"; |
53 |
return 1; |
54 |
} elsif ( $content !~ m{$to}s ) { |
55 |
confess "can't find $from to change into $to in $file"; |
56 |
} |
57 |
} |
58 |
|
59 |
|
60 |
1; |