12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- #!/usr/bin/env perl
- package generate;
- use warnings;
- use strict;
- use lib './perl';
- # JSON::Tiny is included in the "JSON" directory, so it doesn't need to be
- # installed. JSON::Tiny is licensed under Artistic License version 2.0
- # (http://www.perlfoundation.org/artistic_license_2_0) available from:
- # https://metacpan.org/pod/JSON::Tiny
- use JSON::Tiny qw(decode_json);
- # For array_contains
- use List::Util qw(any);
- # Templating engine
- use Text::Template;
- sub get_file_contents {
- my $filepath = shift;
- if ( -f $filepath ) {
- open( my $file_handle, "<", "$filepath" ) or die("File $filepath not found");
- $/ = undef;
- my $content = <$file_handle>;
- close($file_handle);
- return $content;
- } else {
- return '';
- }
- }
- # Get code from given filename.
- # This also encodes *some* HTML entities for inclusion inside <pre> tags.
- sub get_pre_code {
- my $code_text = get_file_contents(shift);
- $code_text =~ s/&/&/g;
- $code_text =~ s/</</g;
- $code_text =~ s/>/>/g;
- return $code_text;
- }
- sub write_file_contents {
- my $string = shift;
- my $filepath = shift;
- open(my $file_handler, '>', $filepath) or die $!;
- print $file_handler $string;
- close($file_handler);
- }
- sub read_json {
- return decode_json( get_file_contents(shift) );
- }
- sub string_replace {
- my $string = shift;
- my $search = shift;
- my $replace = shift;
- $string =~ s/\Q$search\E/$replace/g;
- return $string;
- }
- # requires having use List::Util qw(any);
- sub array_contains {
- my $value = shift;
- # https://stackoverflow.com/a/16690762
- return any { $_ eq $value } @_;
- }
- my $json = read_json('src/info.json');
- # Create template object
- my $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'src/html/index.html');
- # Attach default data to language entries according to default_langs
- if ( $json->{languages} ) {
- foreach my $lang (@{$json->{languages}}) {
- if ( array_contains( $lang->{slug}, @{$json->{default_langs}} ) ) {
- $lang->{default} = 1;
- }
- }
- }
- # Get parsed template file
- my $text = $template->fill_in(HASH => $json, DELIMITERS => [ '{_', '_}' ]);
- # Write output
- write_file_contents($text, 'public/index.html');
|