~rjpcasalino/bss

bss/bss.pl -rwxr-xr-x 7.5 KiB
b2d1bf07rjpc add some notes and fix formatting in places 8 days ago
                                                                                
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env perl

# bss - boring static site generator
# Copyright (C) 2021,2022  Ryan Joseph Patrick Casalino
#
# This program is free software; you can redistribute it and/or modify it under
# the same terms as Perl itself.

# See http://www.perl.com/perl/misc/Artistic.html

use v5.32;
use warnings;
# this code should be fixed but duct tape works also!
# https://stackoverflow.com/questions/1480066/in-perl-how-can-i-concisely-check-if-a-variable-is-defined-and-contains-a-non
no warnings "exiting";
no warnings "uninitialized";

use autodie;
use Config::IniFiles;
use Cwd qw(abs_path realpath);
use Data::Dumper;
use File::Find;
use File::Basename;
use File::Spec::Functions qw(catfile);
use FindBin qw($Bin);
use lib "$Bin/lib";
use Getopt::Long qw(GetOptions);
use IO::File;
use POSIX qw(setsid strftime);
use Pod::Usage qw(pod2usage);
use Text::Markdown qw(markdown);
use Template;
use IO::Socket;
use Web;
use YAML;

my $script = File::Basename::basename($0);
my $SELF   = catfile( $FindBin::Bin, $script );

my ($cmd)    = @ARGV;
my %opts     = ( server => '', verbose => '', help => '');
my $manifest = "manifest.ini";
my $quit     = 0;

# FIXME
# what was I doing here?
#$SIG{CHLD} = sub {
#    while ( waitpid( -1, "WNOHANG" ) > 0 ) { }
#};

$SIG{INT} = sub { say "\nGoodbye!"; sleep 1; $quit++ };

GetOptions(
    \%opts, qw(
      server
      verbose
      help
      )
);

do_build() if defined $cmd and $cmd =~ /[bB]uild/ or die pod2usage(1);

pod2usage(1) if $opts{help};

sub do_build {

    print "bss: No manifest.ini found!" and exit unless -e $manifest;
    $manifest = Config::IniFiles->new( -file => "manifest.ini" );

    # Main config (gets passed around...)
    my %config = (
        TT_DIR =>
          realpath( $manifest->val( "build", "templates_dir" ) // "templates" ),
        SRC => $manifest->val( "build", "src" )
          // "src",    # TODO: disallow back/forward slashes
        DEST        => $manifest->val( "build", "dest" )        // "_site",
        ENCODING    => $manifest->val( "build", "encoding" )    // "UTF-8",
        COLLECTIONS => $manifest->val( "build", "collections" ) // undef,
        EXCLUDE => $manifest->val( "build",  "exclude" ) // "*.md, templates",
        EVAL_PERL => $manifest->val( "build",  "evaluate perl" ) // 0,
        PORT    => $manifest->val( "server", "port" )    // "9000",
        HOST    => $manifest->val( "server", "host" )    // "localhost"
    );

    # Template Toolkit #
    # FIXME
    # tt config is handled poorly
    # this needs to be embedded in the overall config
    my $tt_config = {
        INCLUDE_PATH => undef,
        ENCODING     => undef,
        EVAL_PERL    => undef,
        ENCODING     => undef,
        PLUGINS      => undef
    };

    # set template toolkit options
    $config{TT_CONFIG}->{INCLUDE_PATH} = $config{TT_DIR};
    $config{TT_CONFIG}->{ENCODING}     = $config{ENCODING};
    $config{TT_CONFIG}->{EVAL_PERL}    = $config{EVAL_PERL};
    $config{TT_CONFIG}->{PLUGINS}      = { Markdown => 'Markdown' };

    my $debug_tt_config = Dumper($config{TT_CONFIG});

    say qq{
	SRC: $config{SRC}
	DEST: $config{DEST}
	Excluding: $config{EXCLUDE}
	Encoding: $config{ENCODING}
	Template Toolkit Config: $debug_tt_config
	Server -
	 PORT:$config{PORT}
    } if $opts{verbose};

    mkdir( $config{DEST} ) unless -e $config{DEST};

    system "rm", "-rf", $config{DEST};
    my @collections = split /,/, $config{COLLECTIONS};
    my %collections = ();
    for my $dir (@collections) {

        # push an empty list into some hash:
        push( @{ $collections{$dir} }, () );
        find(
            sub {
                # see no warnings "exiting";
                next if $_ eq "." or $_ eq "..";
                # FIXME: only picks up .md ext
                $_ =~ s/\.[mM](ark)?[dD](own)?$/\.html/;
                push @{ $collections{$dir} }, $_;
            },
            File::Spec->catfile( $config{SRC}, $dir )
        );
        $config{COLLECTIONS} = \%collections;
    }

    # the actual build; note the sub and wanted here
    find(
        {
            wanted => sub { \&build(%config) }
        },
        $config{SRC}
    );

    # rsync is annoying...
    # easy to exclude things using a file, however.
    open my $exclude_fh, ">", "exclude.txt";
    my @excludes = split /,/, $config{EXCLUDE};
    for my $line (@excludes) {
        say $exclude_fh "$line";
    }

    # rsync info
    my $info_flags = "NONE";
    $info_flags = "ALL" if $opts{verbose};

    system "rsync", "-avmh", "--exclude-from=exclude.txt",
      "--info=$info_flags", $config{SRC},
      $config{DEST};

    # house cleaning
    unlink("exclude.txt");
    find(
        sub {
            if ( $_ =~ /.html$/ ) { unlink($_) }
        },
        $config{SRC}
    );

    say "Site created in $config{DEST}!";
    server(%config) if $opts{server};
}

sub build {
    my %config   = @_;
    my $filename = $_;
    if ( -d $filename ) {

        # FIXME
        if ( $_ =~ /$config{TT_DIR}/ ) {
            say "Ignoring: $File::Find::name" if $opts{verbose};
            $File::Find::prune = 1;
        }
    }
    elsif ( $_ =~ /.[mM](ark)?[dD](own)?$/ ) {
        handle_yaml(%config);
    }
    elsif ( $_ =~ /.png|.jpg|.jpeg|.gif|.svg$/i ) {
        # TODO
    }
}

sub handle_yaml {
    my %config = @_;
    my $yaml;
    my $markdown = $_;
    open(my $MD, $markdown);

    undef $/;
    my $data = <$MD>;
    if ( $data =~ /---(.+)---/s ) {
        $yaml = Load($1);
    }
    write_html( $markdown, $yaml, %config );
}

sub write_html {
    my ( $html, $yaml, %config ) = @_;
    $html =~ s/\.[mM](ark)?[dD](own)?$/\.html/;

    my $template = Template->new( $config{TT_CONFIG} );
    my @body;

    open(my $MD, $_);
    while (<$MD>) {

        # FIXME:
        # hacky way to get rid of the YAML
        # block. That should be gone before
        # this...alas, here we are...
        if ( $_ =~ /(---(.+)---)/s ) {
            s/$1//g;
        }
        push( @body, markdown($_) );
    }
    open my $HTML, ">", $html;

    my $vars = {
        title         => $yaml->{title},
        body          => \@body,
        collections   => $config{COLLECTIONS},
    };

    # select layout (template)
    find(
	sub {
	    # see no warnings 'uninitialized';
	    if ( $_ =~ /$yaml->{layout}(.tmpl|.template|.html|.tt|.tt2)$/ ) {
		$yaml->{layout} = $_;
	    }
	},
	$config{TT_DIR}
    );
    # FIXME
    # seems slow; look into speeding up
    # takes 13 ~ seconds on 900MHz Intel
    # look into image compression
    $template->process( $yaml->{layout}, $vars, $HTML )
      or die $template->error();
    say "$yaml->{title} processed." if $opts{verbose};
}

sub server {
    my %config = @_;

    my $listen_socket = IO::Socket::INET->new(
        LocalPort => $config{PORT},
        Listen    => "SOMAXCONN",
        Reuse     => 1
    ) or die "Can't create listen socket: $!";
    say "Started local dev server on $config{PORT}!";

    while ( !$quit ) {

        next unless my $connection = $listen_socket->accept;

        defined( my $child = fork() ) or die "Can't fork: $!";

        if ( $child == 0 ) {
            $listen_socket->close;
            handle_connection($connection);
            exit 0;
        }
        $connection->close;
    }
}
=head1 NAME

boring static site generator

=head1 SYNOPSIS

bss build [options]

     Options:
       --help     display this help message
       --server   serves config DEST
       --verbose  gets talkative

=head1 DESCRIPTION

bss is a boring static site generator.
There isn't much to it. As such, beware!

=head1 LICENSE

This is released under the Artistic
License. See L<perlartistic>.
=cut