Created
September 9, 2024 00:25
-
-
Save oalders/f00c1a05402c5a4eb23043ac2adc97e2 to your computer and use it in GitHub Desktop.
Sort Perl imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# find lib ! -type d | xargs -n1 bin/sort-imports.pl | |
# find t ! -type d | xargs -n1 bin/sort-imports.pl | |
use strict; | |
use warnings; | |
use Path::Tiny qw( path ); | |
# Check if a file path is provided | |
if ( @ARGV != 1 ) { | |
die "Usage: $0 <file_path>\n"; | |
} | |
my $file_path = $ARGV[0]; | |
my @lines = path($file_path)->lines; | |
my @sorted_lines; | |
my $in_use_block = 0; | |
my @use_block; | |
my $use_block_start_index; | |
sub sort_and_splice { | |
my ($lines_ref, $start_index, $block_ref) = @_; | |
splice(@$lines_ref, $start_index, scalar(@$block_ref), sort { lc($a) cmp lc($b) } @$block_ref); | |
} | |
foreach my $index ( 0 .. $#lines ) { | |
my $line = $lines[$index]; | |
if ( $line =~ /^use\s+/ && $line !~ /^use\s+(v|strict|warnings|Moo|5)/ && $line =~ /;\s*$/ ) { | |
if ( !$in_use_block ) { | |
$in_use_block = 1; | |
@use_block = (); | |
$use_block_start_index = $index; | |
} | |
push @use_block, $line; | |
} | |
elsif ($in_use_block) { | |
if ( $line =~ /^\s*#/ ) { | |
# If a comment line is encountered, end the current use block | |
$in_use_block = 0; | |
sort_and_splice(\@lines, $use_block_start_index, \@use_block); | |
} | |
else { | |
# End of use block | |
$in_use_block = 0; | |
sort_and_splice(\@lines, $use_block_start_index, \@use_block); | |
} | |
} | |
} | |
# If the file ends with a use block, sort and add it | |
if ($in_use_block) { | |
sort_and_splice(\@lines, $use_block_start_index, \@use_block); | |
} | |
# Write the sorted lines back to the file | |
path($file_path)->spew(@lines); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment