/[pxelator]/lib/PXElator/file.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /lib/PXElator/file.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 290 - (show annotations)
Wed Aug 26 08:43:40 2009 UTC (14 years, 8 months ago) by dpavlin
File size: 1569 byte(s)
added copy_once and modified append to understand exit in shell scripts and insert before it
1 package file;
2
3 use File::Slurp;
4 use autodie;
5 use Carp qw/carp confess/;
6 use File::Path qw//;
7 use Data::Dump qw/dump/;
8
9 my $debug = 1;
10
11 sub mkpath {
12 my $file = shift;
13 my $dir = $1 if $file =~ s{^.+/[^/]+}{};
14 File::Path::mkpath $dir unless -e $dir;
15 }
16
17 sub append {
18 my ( $file, $content ) = @_;
19
20 if ( ! -e $file ) {
21 mkpath $file;
22 write_file $file, $content;
23 my $size = -s $file;
24 carp "## append created $size bytes in $file";
25 return $size;
26 }
27
28 my $on_disk = read_file $file;
29
30 my $relaxed_content = $content;
31 $relaxed_content =~ s{\s+}{\\s+}gs;
32
33 if ( $on_disk !~ m{$relaxed_content} ) {
34
35 # $content =~ s{^[\n\r]+}{\n}s;
36 # $content =~ s{[\n\r]*$}{\n}s;
37
38 if ( $on_disk =~ s{([\s+]exit[\s\d]*)$}{\n$content\n$1}s ) {
39 # warn "# insert $file\n$on_disk";
40 write_file $file, $on_disk;
41 } else {
42 # warn "# append $file\n$content\n";
43 open($fh, '>>', $file);
44 print $fh $content;
45 close($fh);
46 }
47
48 carp "## append to $file";
49 return -s $file;
50 }
51 }
52
53 sub change {
54 my ( $file, $from, $to ) = @_;
55
56 my $content = read_file $file;
57 if ( $content =~ s{$from}{$to}s ) {
58 write_file $file, $content;
59 carp "## change $file $from => $to" if $debug;
60 return 1;
61 } elsif ( $content !~ m{$to}s ) {
62 confess "can't find $from to change into $to in $file in ",dump( $content );
63 }
64 }
65
66 sub replace {
67 my ( $file, $content ) = @_;
68 mkpath $file;
69 write_file $file, $content;
70 }
71
72 sub copy_once {
73 my ( $from, $to ) = @_;
74 $to ||= $from;
75 return if -e $to;
76 mkpath $to;
77 write_file $to, read_file $from;
78 # warn "# copy_once $to ", -s $to, " bytes";
79 }
80
81 1;

  ViewVC Help
Powered by ViewVC 1.1.26