123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package SugarTrail::Template::Master;
  2. # Master template holder
  3. # new()
  4. # parse()
  5. # _parse_headers()
  6. # _parse_body()
  7. use strict;
  8. use warnings;
  9. use Carp;
  10. use SugarTrail::Template::Slave;
  11. sub new {
  12. my $class = shift;
  13. my $args = { @_ };
  14. my $self = {};
  15. $self->{args} = $args;
  16. return bless $self, $class;
  17. }
  18. sub parse {
  19. my $self = shift;
  20. my ($head, $body) = split "\n\n", $self->{text}, 2;
  21. $self->{head} = $head;
  22. $self->{body} = $body;
  23. return (
  24. $self->_parse_headers(),
  25. $self->_parse_body()
  26. );
  27. }
  28. sub _parse_headers {
  29. my $self = shift;
  30. foreach (split "\n", $self->{head}) {
  31. my ($n, $v) = split ": ", $_, 2;
  32. $self->{meta}->{$n} = $v;
  33. }
  34. return scalar keys %{ $self->{meta} };
  35. }
  36. sub _parse_body {
  37. my $self = shift;
  38. $self->{steps} = [];
  39. foreach (split "\n", $self->{body}) {
  40. chomp; s/ *$//;
  41. my ($line, $cond) = $_ =~ m/^(.*?)(\{(.*)\})?$/;
  42. $line =~ s/ *$//;
  43. push @{ $self->{steps} }, { line => $line, cond => $cond };
  44. }
  45. return scalar @{ $self->{steps} };
  46. }
  47. sub generate_slave {
  48. my $self = shift;
  49. my $args = shift;
  50. my $slave = SugarTrail::Template::Slave->new($args);
  51. my @lines;
  52. STEP: foreach (@{ $self->{steps} }) {
  53. unless ($_->{cond}) {
  54. push @lines, $_->{line};
  55. next STEP;
  56. } else {
  57. push @lines, $_->{line} if &matches($_->{cond}, $args);
  58. }
  59. }
  60. $slave->{meta}->{'Stm'} = $self->{stm};
  61. $slave->{meta}->{'Stm Revision'} = $self->get_current_revision();
  62. $slave->{meta}->{'Params'} = mkmymime($args);
  63. $slave->{lines} = \@lines;
  64. return $slave;
  65. }
  66. # skel: matches if cond has m
  67. sub matches {
  68. my $cond = shift;
  69. my $args = shift;
  70. $cond =~ m/m/;
  71. }
  72. # skel: returns time (might be useful in absence of VCS)
  73. sub get_current_revision {
  74. return time;
  75. }
  76. sub mkmymime {
  77. my $d = shift;
  78. my $d1 = "; "; my $d2 = "=";
  79. my @t;
  80. foreach (sort keys %$d) {
  81. push @t, $_ . $d2 . $d->{$_};
  82. }
  83. return join $d1, @t;
  84. }
  85. 1;