/[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

Annotation of /lib/PXElator/file.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 290 - (hide 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 dpavlin 271 package file;
2    
3     use File::Slurp;
4     use autodie;
5     use Carp qw/carp confess/;
6     use File::Path qw//;
7 dpavlin 290 use Data::Dump qw/dump/;
8 dpavlin 271
9 dpavlin 290 my $debug = 1;
10    
11 dpavlin 271 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 dpavlin 290 carp "## append created $size bytes in $file";
25 dpavlin 271 return $size;
26     }
27    
28     my $on_disk = read_file $file;
29    
30 dpavlin 290 my $relaxed_content = $content;
31     $relaxed_content =~ s{\s+}{\\s+}gs;
32 dpavlin 271
33     if ( $on_disk !~ m{$relaxed_content} ) {
34    
35     # $content =~ s{^[\n\r]+}{\n}s;
36     # $content =~ s{[\n\r]*$}{\n}s;
37    
38 dpavlin 290 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 dpavlin 271
48 dpavlin 290 carp "## append to $file";
49     return -s $file;
50 dpavlin 271 }
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 dpavlin 290 carp "## change $file $from => $to" if $debug;
60 dpavlin 271 return 1;
61     } elsif ( $content !~ m{$to}s ) {
62 dpavlin 290 confess "can't find $from to change into $to in $file in ",dump( $content );
63 dpavlin 271 }
64     }
65    
66 dpavlin 277 sub replace {
67     my ( $file, $content ) = @_;
68     mkpath $file;
69     write_file $file, $content;
70     }
71 dpavlin 271
72 dpavlin 290 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 dpavlin 271 1;

  ViewVC Help
Powered by ViewVC 1.1.26