| 1 | #!/usr/bin/perl |
| 2 | |
| 3 | # Usage: manisort [-q] [-o outfile] [filename] |
| 4 | # |
| 5 | # Without 'filename', looks for MANIFEST in the current dir. |
| 6 | # With '-o outfile', writes the sorted MANIFEST to the specified file. |
| 7 | # Prints the result of the sort to stderr. '-q' silences this. |
| 8 | # The exit code for the script is the sort result status |
| 9 | # (i.e., 0 means already sorted properly, 1 means not properly sorted) |
| 10 | |
| 11 | use strict; |
| 12 | use warnings; |
| 13 | $| = 1; |
| 14 | |
| 15 | # Get command line options |
| 16 | use Getopt::Long; |
| 17 | my $outfile; |
| 18 | my $check_only = 0; |
| 19 | my $quiet = 0; |
| 20 | GetOptions ('output=s' => \$outfile, |
| 21 | 'check' => \$check_only, |
| 22 | 'quiet' => \$quiet); |
| 23 | |
| 24 | my $file = (@ARGV) ? shift : 'MANIFEST'; |
| 25 | |
| 26 | # Read in the MANIFEST file |
| 27 | open(my $IN, '<', $file) |
| 28 | or die("Can't read '$file': $!"); |
| 29 | my @manifest = <$IN>; |
| 30 | close($IN) or die($!); |
| 31 | chomp(@manifest); |
| 32 | |
| 33 | # Sort by dictionary order (ignore-case and |
| 34 | # consider whitespace and alphanumeric only) |
| 35 | my @sorted = sort { |
| 36 | (my $aa = $a) =~ s/[^\s\da-zA-Z]//g; |
| 37 | (my $bb = $b) =~ s/[^\s\da-zA-Z]//g; |
| 38 | uc($aa) cmp uc($bb) |
| 39 | } @manifest; |
| 40 | |
| 41 | # Check if the file is sorted or not |
| 42 | my $exit_code = 0; |
| 43 | for (my $ii = 0; $ii < $#manifest; $ii++) { |
| 44 | next if ($manifest[$ii] eq $sorted[$ii]); |
| 45 | $exit_code = 1; # Not sorted |
| 46 | last; |
| 47 | } |
| 48 | |
| 49 | # Output sorted file |
| 50 | if (defined($outfile)) { |
| 51 | open(my $OUT, '>', $outfile) |
| 52 | or die("Can't open output file '$outfile': $!"); |
| 53 | print($OUT join("\n", @sorted), "\n"); |
| 54 | close($OUT) or die($!); |
| 55 | } |
| 56 | |
| 57 | # Report on sort results |
| 58 | printf(STDERR "'$file' is%s sorted properly\n", |
| 59 | (($exit_code) ? ' NOT' : '')) if (! $quiet); |
| 60 | |
| 61 | # Exit with the sort results status |
| 62 | exit($exit_code); |
| 63 | |
| 64 | # EOF |