--- lib/PXElator/file.pm 2009/08/19 22:48:54 271 +++ lib/PXElator/file.pm 2009/09/20 16:11:16 438 @@ -4,11 +4,17 @@ use autodie; use Carp qw/carp confess/; use File::Path qw//; +use Data::Dump qw/dump/; + +my $debug = 0; sub mkpath { my $file = shift; - my $dir = $1 if $file =~ s{^.+/[^/]+}{}; - File::Path::mkpath $dir unless -e $dir; + my $dir = $1 if $file =~ s{(^.+)/[^/]+}{$1}; + if ( $dir && ! -d $dir ) { + carp "# mkdir $dir"; + File::Path::mkpath $dir; + } } sub append { @@ -18,28 +24,34 @@ mkpath $file; write_file $file, $content; my $size = -s $file; - carp "append created $size bytes in $file"; + carp "## append created $size bytes in $file"; return $size; } my $on_disk = read_file $file; - my $relaxed_content =~ s{\s+}{\\s+}gs; + my $relaxed_content = $content; + $relaxed_content =~ s{\s+}{\\s+}gs; if ( $on_disk !~ m{$relaxed_content} ) { # $content =~ s{^[\n\r]+}{\n}s; # $content =~ s{[\n\r]*$}{\n}s; - open($fh, '>>', $file); - print $fh $content; - close($fh); - - my $size = length($content); - - carp "append $size bytes to $file"; - warn $content; - return $size; + if ( $on_disk =~ s{([\s+]exit[\s\d]*)$}{\n$content\n$1}s ) { + warn "# insert $file\n$on_disk" if $debug; + write_file $file, $on_disk; + } else { + warn "# append $file\n$content\n" if $debug; + open($fh, '>>', $file); + print $fh $content; + close($fh); + } + + carp "## append to $file" if $debug; + return -s $file; + } else { + warn "## $file not modified" if $debug; } } @@ -49,12 +61,28 @@ my $content = read_file $file; if ( $content =~ s{$from}{$to}s ) { write_file $file, $content; - carp "change $file $from => $to"; + carp "## change $file $from => $to" if $debug; return 1; } elsif ( $content !~ m{$to}s ) { - 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 ); } } +sub replace { + my ( $file, $content ) = @_; + mkpath $file; + write_file $file, $content; +} + +sub copy_once { + my ( $from, $to ) = @_; + die "no destination" unless $to; + return if -e $to; + mkpath $to; + my $perm = (stat $from)[2]; + carp "# copy_once $from => $to $perm"; + write_file $to, read_file($from); + chmod $perm, $to; +} 1;