aboutsummaryrefslogtreecommitdiff
path: root/bin/mkdocs-prep.pl
blob: e452e0bb78b97831a4b3008d96c7ee1f901b9843 (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 $cfgfile = path('site.mk');
  37. my $config = $cfgfile->exists
  38. ? Config::Tiny->read( $cfgfile, 'utf8' )
  39. : Config::Tiny->new;
  40. my $config_has_changed;
  41. my $content = path($infile)->slurp_utf8;
  42. $content =~ s/^#+\s*Special strings\s*\n((?:\n|[^#\n][^\n]*\n)*)//m;
  43. my $section = $1 || '';
  44. my %defaults;
  45. while ( $section =~ /^(\w+)\h*:\h*(\w\S*(?:\h+\S+)*)/mg ) {
  46. my $token = $1;
  47. my $string = $2;
  48. unless ( exists $config->{_}->{$1} ) {
  49. $_ = prompt "Which string should replace token '$token'?";
  50. next unless $_;
  51. $config->{_}->{$1} = $_;
  52. $config_has_changed++;
  53. }
  54. $content =~ s/\Q$string\E/{{$token}}/g;
  55. };
  56. my $compiler = Text::Hogan::Compiler->new;
  57. my $template = $compiler->compile($content);
  58. path($outfile)->spew_utf8( $template->render( $config->{_} ) );
  59. $cfgfile->touch;
  60. $config->write( $cfgfile, 'utf8' )
  61. if $config_has_changed;
  62. 1;