| 1 | #!/usr/local/bin/perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use WWW::Shopify::Liquid; | ||
| 7 | use Getopt::Long; | ||
| 8 | use File::Find; | ||
| 9 | use File::Slurp; | ||
| 10 | use Pod::Usage; | ||
| 11 | |||
| 12 | |||
| 13 | =head1 NAME | ||
| 14 | |||
| 15 | shopify-liquid-beautify.pl - Beautifies liquid files. | ||
| 16 | |||
| 17 | =head1 SYNOPSIS | ||
| 18 | |||
| 19 | shopify-liquid-beautify.pl [files] | ||
| 20 | |||
| 21 | files The list of files and folders to beautify. | ||
| 22 | If no files are specified, content is read | ||
| 23 | from standard input. | ||
| 24 | |||
| 25 | --verbose Displays extra info. | ||
| 26 | --quiet Suppress everything except errors. | ||
| 27 | |||
| 28 | --help Displays this messaqge. | ||
| 29 | --fullhelp Displays the full pod doc. | ||
| 30 | |||
| 31 | This tool beautifies liquid files. | ||
| 32 | |||
| 33 | =cut | ||
| 34 | |||
| 35 | =head1 EXAMPLES | ||
| 36 | |||
| 37 | shopify-liquid-beautify.pl *.liquid | ||
| 38 | |||
| 39 | Will beautify all liquid files in the oflder. | ||
| 40 | |||
| 41 | =cut | ||
| 42 | |||
| 43 | my @ARGS; | ||
| 44 | |||
| 45 | GetOptions( | ||
| 46 | 'help' => \my $help, | ||
| 47 | 'fullhelp' => \my $fullhelp, | ||
| 48 | 'verbose' => \my $verbose, | ||
| 49 | 'quiet' => \my $quiet, | ||
| 50 | '<>' => sub { push(@ARGS, $_[0]); } | ||
| 51 | ); | ||
| 52 | |||
| 53 | pod2usage(-verbose => 2) if ($fullhelp); | ||
| 54 | pod2usage() if $help; | ||
| 55 | |||
| 56 | use WWW::Shopify::Liquid; | ||
| 57 | use WWW::Shopify::Liquid::Beautifier; | ||
| 58 | |||
| 59 | my $liquid = WWW::Shopify::Liquid->new; | ||
| 60 | $liquid->lexer->unparse_spaces(1); | ||
| 61 | my $beautifier = WWW::Shopify::Liquid::Beautifier->new; | ||
| 62 | $beautifier->register_tag($_) for (@{$liquid->tags}); | ||
| 63 | |||
| 64 | eval { | ||
| 65 | sub beautify { | ||
| 66 | my ($text) = @_; | ||
| 67 | return $liquid->lexer->unparse_text($beautifier->beautify($liquid->lexer->parse_text($text))); | ||
| 68 | } | ||
| 69 | |||
| 70 | die "One or more of those files doesn't exist or is a directory." if int(grep { !-e $_ || -d $_ } @ARGS) > 0; | ||
| 71 | |||
| 72 | if (@ARGS) { | ||
| 73 | write_file($_, beautify(scalar(read_file($_)))) for (@ARGS); | ||
| 74 | } else { | ||
| 75 | my $accumulator = ''; | ||
| 76 | while (my $line = <STDIN>) { | ||
| 77 | $accumulator .= $line; | ||
| 78 | } | ||
| 79 | print beautify($accumulator); | ||
| 80 | } | ||
| 81 | |||
| 82 | exit(0); | ||
| 83 | }; | ||
| 84 | if (my $exp = $@) { | ||
| 85 | $exp =~ s/ at .*? line \d+.//; | ||
| 86 | chomp($exp); | ||
| 87 | print STDERR "$exp\n"; | ||
| 88 | exit(-1); | ||
| 89 | } |