summaryrefslogtreecommitdiff
path: root/usr/src/libpiny/lib/IkiWiki/FakeSetup.pm
blob: c9c823bafe4fb77f3235fa308fd94278eff0a81b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package IkiWiki::FakeSetup;

use strict;
use warnings;

use Data::Dumper qw( );
use Exporter qw( import );

our @EXPORT_OK = qw( readSetup writeSetup );

sub readSetup {
  my ( $setupfile ) = @_;

  # Sorry about the use of globals but it's hard to share lexicals with dynamically generated source.
  $IkiWiki::FakeSetup::package = undef;
  @IkiWiki::FakeSetup::args = ();

  sub inc {
    my ( $self, $file ) = @_;

    my $package = $file;
    $package =~ s/\//::/g;
    $package =~ s/\.pm//;

    my @src =
      ( "package $package;\n"
      , "sub import {\n"
      , "  my ( \$class, \@args ) = \@_;\n"
      , "  \$IkiWiki::FakeSetup::package = \$class;\n"
      , "  \@IkiWiki::FakeSetup::args = \@args;\n"
      , "}\n"
      , "1;\n"
      );

    return sub { if ( scalar @src ) { $_ = shift @src; return 1; } else { return 0; } };

  };

  eval {
    my @oldINC = @INC;
    @INC = ( ".", \&inc );

    my %oldINC = %INC;
    %INC = ( );

    do $setupfile;

    @INC = @oldINC;
    %INC = %oldINC;
  };

  return ( $IkiWiki::FakeSetup::package, @IkiWiki::FakeSetup::args );

}

sub writeSetup {
  my ( $package, @args ) = @_;

  my $d = Data::Dumper->new( \@args );
  $d->Terse( 1 );

  return "#!/usr/bin/perl\n\nuse $package " . $d->Dump( ) . ";\n";
}

1;

__END__

Because it may not be completely obvious, here's how you would use this:

#!/usr/bin/perl

use strict;
use warnings;

use IkiWiki::FakeSetup qw( readSetup writeSetup );

# This reads the setup file, returning the package it uses and any configuration it passed to that package.
my ( $package, $config ) = readSetup( "almighty_ikiwiki_template.setup" );

# Make changes to the configuration.
$config->{"srcdir"} = "/some/dir";
$config->{"adminemail"} = "somejerk\@jerkville.com";

# Open a new file, and write the changed configuration to it.
open( SETUP, ">", "almighty_ikiwiki_template_changed.setup" );
print SETUP writeSetup( $package, $config );
close( SETUP );