generate.pl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env perl
  2. package generate;
  3. use warnings;
  4. use strict;
  5. use lib './perl';
  6. # JSON::Tiny is included in the "JSON" directory, so it doesn't need to be
  7. # installed. JSON::Tiny is licensed under Artistic License version 2.0
  8. # (http://www.perlfoundation.org/artistic_license_2_0) available from:
  9. # https://metacpan.org/pod/JSON::Tiny
  10. use JSON::Tiny qw(decode_json);
  11. # For array_contains
  12. use List::Util qw(any);
  13. # Templating engine
  14. use Text::Template;
  15. sub get_file_contents {
  16. my $filepath = shift;
  17. if ( -f $filepath ) {
  18. open( my $file_handle, "<", "$filepath" ) or die("File $filepath not found");
  19. $/ = undef;
  20. my $content = <$file_handle>;
  21. close($file_handle);
  22. return $content;
  23. } else {
  24. return '';
  25. }
  26. }
  27. # Get code from given filename.
  28. # This also encodes *some* HTML entities for inclusion inside <pre> tags.
  29. sub get_pre_code {
  30. my $code_text = get_file_contents(shift);
  31. $code_text =~ s/&/&amp;/g;
  32. $code_text =~ s/</&lt;/g;
  33. $code_text =~ s/>/&gt;/g;
  34. return $code_text;
  35. }
  36. sub write_file_contents {
  37. my $string = shift;
  38. my $filepath = shift;
  39. open(my $file_handler, '>', $filepath) or die $!;
  40. print $file_handler $string;
  41. close($file_handler);
  42. }
  43. sub read_json {
  44. return decode_json( get_file_contents(shift) );
  45. }
  46. sub string_replace {
  47. my $string = shift;
  48. my $search = shift;
  49. my $replace = shift;
  50. $string =~ s/\Q$search\E/$replace/g;
  51. return $string;
  52. }
  53. # requires having use List::Util qw(any);
  54. sub array_contains {
  55. my $value = shift;
  56. # https://stackoverflow.com/a/16690762
  57. return any { $_ eq $value } @_;
  58. }
  59. my $json = read_json('src/info.json');
  60. # Create template object
  61. my $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'src/html/index.html');
  62. # Attach default data to language entries according to default_langs
  63. if ( $json->{languages} ) {
  64. foreach my $lang (@{$json->{languages}}) {
  65. if ( array_contains( $lang->{slug}, @{$json->{default_langs}} ) ) {
  66. $lang->{default} = 1;
  67. }
  68. }
  69. }
  70. # Get parsed template file
  71. my $text = $template->fill_in(HASH => $json, DELIMITERS => [ '{_', '_}' ]);
  72. # Write output
  73. write_file_contents($text, 'public/index.html');