| 1 | #!/usr/bin/env 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 | 'compress' => \my $compress, | ||
| 51 | '<>' => sub { push(@ARGS, $_[0]); } | ||
| 52 | ); | ||
| 53 | |||
| 54 | pod2usage(-verbose => 2) if ($fullhelp); | ||
| 55 | pod2usage() if $help; | ||
| 56 | |||
| 57 | use WWW::Shopify::Liquid; | ||
| 58 | use WWW::Shopify::Liquid::Beautifier; | ||
| 59 | |||
| 60 | my $liquid = WWW::Shopify::Liquid->new; | ||
| 61 | $liquid->lexer->unparse_spaces(1); | ||
| 62 | my $beautifier = WWW::Shopify::Liquid::Beautifier->new; | ||
| 63 | $beautifier->register_tag($_) for (@{$liquid->tags}); | ||
| 64 | |||
| 65 | eval { | ||
| 66 | sub beautify { | ||
| 67 | my ($text, $compress) = @_; | ||
| 68 | if ($compress){ | ||
| 69 | return $liquid->lexer->unparse_text($beautifier->compress($liquid->lexer->parse_text($text))); | ||
| 70 | } else { | ||
| 71 | return $liquid->lexer->unparse_text($beautifier->beautify($liquid->lexer->parse_text($text))); | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | die "One or more of those files doesn't exist or is a directory." if int(grep { !-e $_ || -d $_ } @ARGS) > 0; | ||
| 76 | |||
| 77 | if (@ARGS) { | ||
| 78 | write_file($_, beautify(scalar(read_file($_)),$compress)) for (@ARGS); | ||
| 79 | } else { | ||
| 80 | my $accumulator = ''; | ||
| 81 | while (my $line = <STDIN>) { | ||
| 82 | $accumulator .= $line; | ||
| 83 | } | ||
| 84 | print beautify($accumulator); | ||
| 85 | } | ||
| 86 | |||
| 87 | exit(0); | ||
| 88 | }; | ||
| 89 | if (my $exp = $@) { | ||
| 90 | $exp =~ s/ at .*? line \d+.//; | ||
| 91 | chomp($exp); | ||
| 92 | print STDERR "$exp\n"; | ||
| 93 | exit(-1); | ||
| 94 | } |