| 1 | # You may distribute under the terms of either the GNU General Public License | ||
| 2 | # or the Artistic License (the same terms as Perl itself) | ||
| 3 | # | ||
| 4 | # (C) Paul Evans, 2023 -- leonerd@leonerd.org.uk | ||
| 5 | |||
| 6 | use v5.36; | ||
| 7 | use Object::Pad 0.807; | ||
| 8 | |||
| 9 | class App::perl::distrolint::Check::Unimport 0.09; | ||
| 10 | |||
| 11 | apply App::perl::distrolint::CheckRole::EachFile; | ||
| 12 | apply App::perl::distrolint::CheckRole::TreeSitterPerl; | ||
| 13 | |||
| 14 | use Text::Treesitter 0.07; # child_by_field_name | ||
| 15 | |||
| 16 | use constant DESC => "check that if import exists then so does unimport"; | ||
| 17 | use constant SORT => 20; | ||
| 18 | |||
| 19 | =head1 NAME | ||
| 20 | |||
| 21 | C<App::perl::distrolint::Check::Unimport> - check that a C<sub unimport> is defined if required | ||
| 22 | |||
| 23 | =head1 DESCRIPTION | ||
| 24 | |||
| 25 | This checks that if any package defines a C<sub import>, then it also defines | ||
| 26 | a C<sub unimport>. This helps to ensure that whatever effects the module | ||
| 27 | normally provides at import time can be undone by the C<no ...> syntax. | ||
| 28 | =cut | ||
| 29 | |||
| 30 | method run ( $app ) | ||
| 31 | { | ||
| 32 | return $self->run_for_each_perl_file( check_file => ); | ||
| 33 | } | ||
| 34 | |||
| 35 | my $QUERY = <<'EOF'; | ||
| 36 | (subroutine_declaration_statement name: _ @name) | ||
| 37 | EOF | ||
| 38 | |||
| 39 | method check_file ( $file ) | ||
| 40 | { | ||
| 41 | my $tree = $self->parse_perl_file( $file ); | ||
| 42 | |||
| 43 | my $have_import; | ||
| 44 | my $have_unimport; | ||
| 45 | |||
| 46 | $self->walk_each_query_match( $QUERY, $tree->root_node, method ( $captures ) { | ||
| 47 | my $subname = $captures->{name}->text; | ||
| 48 | |||
| 49 | $have_import++ if $subname eq "import"; | ||
| 50 | $have_unimport++ if $subname eq "unimport"; | ||
| 51 | |||
| 52 | return 1; | ||
| 53 | } ); | ||
| 54 | |||
| 55 | return 1 if $have_unimport or !$have_import; | ||
| 56 | |||
| 57 | App->diag( App->format_file( $file ), " has sub import but no sub unimport" ); | ||
| 58 | return 0; | ||
| 59 | } | ||
| 60 | |||
| 61 | =head1 AUTHOR | ||
| 62 | |||
| 63 | Paul Evans <leonerd@leonerd.org.uk> | ||
| 64 | |||
| 65 | =cut | ||
| 66 | |||
| 67 | 0x55AA; |