| 1 | package Shotenjin::Embedder; | ||
| 2 | BEGIN { | ||
| 3 | $Shotenjin::Embedder::VERSION = '0.06'; | ||
| 4 | } | ||
| 5 | |||
| 6 | # ABSTRACT: embedd and escape template content | ||
| 7 | |||
| 8 | use strict; | ||
| 9 | use warnings; | ||
| 10 | |||
| 11 | use Path::Class; | ||
| 12 | |||
| 13 | |||
| 14 | my $GENERATED = '/* GENERATED BY SHOTENJIN HELPER, DO NOT MODIFY DIRECTLY */'; | ||
| 15 | my $GENERATED_QUOTED = quotemeta $GENERATED; | ||
| 16 | |||
| 17 | |||
| 18 | |||
| 19 | sub process_dir { | ||
| 20 | my ($self, $dir, $strip_whitespace, $base_dir) = @_; | ||
| 21 | |||
| 22 | dir($dir)->recurse( callback => sub { | ||
| 23 | my ($file) = @_; | ||
| 24 | |||
| 25 | $self->process_file($file, $strip_whitespace, $base_dir) if -f $file; | ||
| 26 | } ) | ||
| 27 | } | ||
| 28 | |||
| 29 | |||
| 30 | sub process_file { | ||
| 31 | my ($self, $file, $strip_whitespace, $base_dir) = @_; | ||
| 32 | |||
| 33 | my $content = file($file)->slurp . ""; | ||
| 34 | |||
| 35 | my $res = $self->process_string($content, $strip_whitespace, $base_dir || file($file)->dir); | ||
| 36 | |||
| 37 | if ($content ne $res) { | ||
| 38 | my $fh = file($file)->openw(); | ||
| 39 | print $fh $res; | ||
| 40 | $fh->close(); | ||
| 41 | |||
| 42 | print "UPDATED: $file\n"; | ||
| 43 | } | ||
| 44 | } | ||
| 45 | |||
| 46 | |||
| 47 | sub process_string { | ||
| 48 | my ($self, $content, $strip_whitespace, $base_dir) = @_; | ||
| 49 | |||
| 50 | my $content_copy = $content; | ||
| 51 | |||
| 52 | pos $content = 0; | ||
| 53 | |||
| 54 | while ($content =~ m! | ||
| 55 | ^( | ||
| 56 | |||
| 57 | ( | ||
| 58 | |||
| 59 | ([\t\f ]*) /\*tj (.*?) tj(?:file)?\*/ | ||
| 60 | ) | ||
| 61 | |||
| 62 | (?:\s+$GENERATED_QUOTED\s+sources\s:\s'.*?'\s*)? | ||
| 63 | )$ | ||
| 64 | !msgx) { | ||
| 65 | |||
| 66 | my $overall = $1; | ||
| 67 | my $overall_quoted = quotemeta $overall; | ||
| 68 | |||
| 69 | my $whitespace = $3; | ||
| 70 | my $directive = $2; | ||
| 71 | my $template = $4; | ||
| 72 | |||
| 73 | my $is_from_file = $template =~ m/^file\( (.+?) \)$/mx; | ||
| 74 | |||
| 75 | if ($is_from_file) { | ||
| 76 | |||
| 77 | my $from_file = file($1)->absolute( dir($base_dir) ); | ||
| 78 | |||
| 79 | $template = -e $from_file ? $from_file->slurp : "File [$from_file] not found"; | ||
| 80 | } | ||
| 81 | |||
| 82 | # removing leading and trailing whitespace | ||
| 83 | $template =~ s/^\s*(.*?)\s*$/$1/mg if $strip_whitespace; | ||
| 84 | # $template =~ s/^[\t\f ]*(.*?)[\t\f ]*$/$1/mg; | ||
| 85 | |||
| 86 | # escaping \, new-lines and ' | ||
| 87 | $template =~ s!\\!\\\\!g; | ||
| 88 | $template =~ s!\r?\n!\\n!g; | ||
| 89 | $template =~ s!'!\\'!g; | ||
| 90 | |||
| 91 | $content_copy =~ s!$overall_quoted!${directive}\n\n$whitespace$GENERATED\n${whitespace}sources : '$template'!ms; | ||
| 92 | } | ||
| 93 | |||
| 94 | return $content_copy; | ||
| 95 | } | ||
| 96 | |||
| 97 | |||
| 98 | |||
| 99 | __END__ |