File: DeleteMethod.pm

package info (click to toggle)
prt 0.22-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 404 kB
  • sloc: perl: 1,185; makefile: 3
file content (103 lines) | stat: -rw-r--r-- 2,235 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package App::PRT::Command::DeleteMethod;
use strict;
use warnings;
use PPI;

sub new {
    my ($class) = @_;
    bless {}, $class;
}

# parse arguments from CLI
# arguments:
#   @arguments
# returns:
#   @rest_arguments
sub parse_arguments {
    my ($self, @arguments) = @_;

    die "class and method required" unless @arguments >= 2;

    $self->register(shift @arguments => shift @arguments);

    @arguments;
}

# register a replacing rule
# arguments:
#   $target_class_name:  Target Class Name
#   $target_method_name: Target Method Name
sub register {
    my ($self, $target_class_name, $target_method_name) = @_;

    $self->{target_class_name} = $target_class_name;
    $self->{target_method_name} = $target_method_name;
}

sub target_class_name {
    my ($self) = @_;

    $self->{target_class_name};
}

sub target_method_name {
    my ($self) = @_;

    $self->{target_method_name};
}

sub deleted_code {
    my ($self) = @_;

    $self->{deleted_code};
}

# refactor a file
# argumensts:
#   $file: filename for refactoring
sub execute {
    my ($self, $file) = @_;

    my $document = PPI::Document->new($file);

    return unless $document;

    my $package = $document->find_first('PPI::Statement::Package');

    return unless $package;
    return unless $package->namespace eq $self->target_class_name;

    my $subs = $document->find('PPI::Statement::Sub');

    my $replaced = 0;
    for my $sub (@$subs) {
        next unless $sub->name eq $self->target_method_name;
        my @garbages;

        # comment before method
        my $cursor = $sub->first_token->previous_token;
        while (defined $cursor && ref $cursor eq 'PPI::Token::Comment') {
            unshift @garbages, $cursor;
            $cursor = $cursor->previous_token;
        }

        # method body
        push @garbages, $sub;

        # whitespace after method
        $cursor = $sub->last_token->next_token;
        while (defined $cursor && ref $cursor eq 'PPI::Token::Whitespace') {
            push @garbages, $cursor;
            $cursor = $cursor->next_token;
        }

        $self->{deleted_code} = join '', @garbages;

        $_->remove for @garbages;
        $replaced++;
    }

    $document->save($file) if $replaced;
}

1;