Improve errorhandling
[grml.org.git] / gen_website
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Template;
7 use File::Find::Rule;
8 use File::Path qw(make_path remove_tree);
9 use File::Basename qw (fileparse dirname);
10 use File::Copy::Recursive qw(fcopy dirmove);
11 use File::Temp qw (tempdir);
12
13 my $out_dir = shift || "out/";
14
15 #find all files
16
17 #rule to match git directorys
18 my $git = File::Find::Rule->directory
19                           ->name(".git")
20                           ->prune
21                           ->discard;
22
23 #matches all files
24 my $file_rule = File::Find::Rule->file();
25
26 #combine both
27 my @files = File::Find::Rule->or( $git, $file_rule )
28                             ->in('.');
29
30 #create a tempdir
31 my $tempdir = tempdir( CLEANUP => 1 );
32
33 #initialize template toolkit
34
35 my $template = Template->new;
36
37 foreach my $file (@files) {
38         next if $file =~ /^$out_dir/;
39         next if $file =~ /$0$/;
40         if ($file =~ /\.tt2$/) {
41                 my $output;
42                 $template->process($file, undef, \$output)
43                         || die "Could not process file \"$file\": $!";
44
45                 my ($name,$path,$suffix) = fileparse($file,qw (.tt2));
46         make_path("$tempdir/$path") unless -d "$tempdir/$path";
47                 open (my $fh, '>', "$tempdir/$path/$name")
48                         or die "Could not write to $file: $!";
49                 print $fh $output;
50                 close($fh);
51         } else {
52                 fcopy ($file, "$tempdir/$file") or die "Could not copy $file to $tempdir/$file: $!";
53         }
54 }
55
56 $out_dir =~ s/\/$//;
57 if (-d $out_dir) {
58     dirmove ($out_dir, $out_dir . ".bak")
59         or die "Could not move $out_dir to $out_dir.bak: $!";
60 }
61 if (! dirmove ($tempdir, "$out_dir")) {
62         warn "Could not move $tempdir to $out_dir: $!";
63         warn "Rollback";
64         remove_tree($out_dir);
65         dirmove ($out_dir . ".bak", $out_dir);
66 } else {
67         remove_tree($out_dir . ".bak");
68 }