aboutsummaryrefslogtreecommitdiff
path: root/bin/mkdocs-prep.pl
blob: 96bba69a018bef9228e13084c633679bdd9d5938 (plain)
  1. #!/usr/bin/perl
  2. use v5.18; # needed for \h (horizontal whitespace) in regexes
  3. use strict;
  4. use warnings;
  5. use autodie;
  6. use List::Util qw(pairs);
  7. use Config::Tiny;
  8. use Path::Tiny;
  9. use Text::Hogan::Compiler;
  10. use IO::Prompter;
  11. =head1 NAME
  12. mkdocs-prep - mkdocs preprocessor expanding inline hints and mustache tokens
  13. =head1 VERSION
  14. Version 0.02
  15. =head1 SYNOPSIS
  16. =head1 DESCRIPTION
  17. B<mkdocs-prep> prepares a markdown document for B<mkdocs> processing.
  18. The document is converted using inline hint section to a mustache template
  19. and resolved using an external set of single-word tokens.
  20. A document section named "Special strings" is parsed for token definitions
  21. where each line lists a single-word token, a colon, and default string.
  22. The section is then stripped,
  23. and all occurences of default strings are replaced with tokens
  24. wrapped with double curly brackets.
  25. Template tokens are gathered from external config file F<site.mk>,
  26. where each line lists a token, an equals sign, and replacement string.
  27. Inline defined tokens not declared in F<site.mk> will be prompted for.
  28. if a value is provided it will be used, and also saved in F<site.mk>.
  29. If no value is provided then inline default string is used.
  30. Each token in the document,
  31. wrapped with double curly brackets {{like_this}},
  32. is replaced (including brackets) with corresponding string.
  33. =cut
  34. my ( $infile, $outfile ) = @ARGV;
  35. @ARGV = undef;
  36. my $config = Config::Tiny->new;
  37. $config = Config::Tiny->read( 'site.mk', 'utf8' );
  38. my $config_has_changed;
  39. my $content = path($infile)->slurp_utf8;
  40. $content =~ s/^#+\s*Special strings\s*\n((?:\n|[^#\n][^\n]*\n)*)//m;
  41. my $section = $1 || '';
  42. my %defaults;
  43. while ( $section =~ /^(\w+)\h*:\h*(\w+(?:\h+\w+)*)/mg ) {
  44. my $token = $1;
  45. my $string = $2;
  46. unless ( exists $config->{_}->{$1} ) {
  47. $_ = prompt "Which string should replace token '$token'?";
  48. next unless $_;
  49. $config->{_}->{$1} = $_;
  50. $config_has_changed++;
  51. }
  52. $content =~ s/\Q$string\E/{{$token}}/g;
  53. };
  54. my $compiler = Text::Hogan::Compiler->new;
  55. my $template = $compiler->compile($content);
  56. path($outfile)->spew_utf8( $template->render( $config->{_} ) );
  57. $config->write( 'site.mk', 'utf8' )
  58. if $config_has_changed;
  59. 1;