| 1 | #!/usr/local/bin/perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use JavaScript::Beautifier qw/js_beautify/; | ||
| 6 | use Getopt::Long; | ||
| 7 | use Pod::Usage; | ||
| 8 | use IO::File; | ||
| 9 | use Carp qw/croak/; | ||
| 10 | |||
| 11 | my $file = pop @ARGV; | ||
| 12 | pod2usage(1) unless ($file); | ||
| 13 | |||
| 14 | my %params; | ||
| 15 | GetOptions( | ||
| 16 | \%params, | ||
| 17 | "help|?", | ||
| 18 | "w|overwrite", | ||
| 19 | "o|output=s", | ||
| 20 | "s|indent_size=i", | ||
| 21 | "c|indent_character=s", | ||
| 22 | "p|preserve_newlines", | ||
| 23 | ) or pod2usage(2); | ||
| 24 | |||
| 25 | pod2usage(1) if $params{help}; | ||
| 26 | |||
| 27 | my $file_io; | ||
| 28 | if ($file eq '-') { | ||
| 29 | my $io = new IO::Handle; | ||
| 30 | $file_io = $io->fdopen(fileno(STDIN),"r"); | ||
| 31 | } else { | ||
| 32 | $file_io = new IO::File($file, "<"); | ||
| 33 | defined $file_io or croak "can't open $file: $!"; | ||
| 34 | } | ||
| 35 | local $/; | ||
| 36 | my $js_source_code = <$file_io>; | ||
| 37 | $file_io->close; | ||
| 38 | |||
| 39 | my $pretty_js = js_beautify( $js_source_code, { | ||
| 40 | indent_size => $params{s} || 4, | ||
| 41 | indent_character => $params{c} || ' ', | ||
| 42 | preserve_newlines => $params{p} || 1 | ||
| 43 | } ); | ||
| 44 | |||
| 45 | if ( $params{o} or $params{w} ) { | ||
| 46 | my $to_file = $params{o} || $file; | ||
| 47 | open(my $fh, '>', $to_file) or die("could not open $to_file: $!"); | ||
| 48 | print $fh $pretty_js; | ||
| 49 | close($fh); | ||
| 50 | } else { | ||
| 51 | print $pretty_js; | ||
| 52 | } | ||
| 53 | |||
| 54 | 1; | ||
| 55 | __END__ |