File: AddMethod.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 (66 lines) | stat: -rw-r--r-- 1,486 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
package App::PRT::Command::AddMethod;
use strict;
use warnings;
use PPI;

# Internal command to add method to file

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

# register a method
# arguments:
#   $code: Source code string of method to add
sub register {
    my ($self, $code) = @_;

    $self->{code} = $code;
}

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

    $self->{code};
}

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

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

    my $statements = $document->find('PPI::Statement');
    die 'statement not found' unless $statements;
    my $after = $statements->[-1];

    my $code_document = PPI::Document->new(\$self->code);
    my $code_statement = $code_document->find_first('PPI::Statement::Sub');

    my @comments;
    my $cursor = $code_statement->first_token->previous_token;
    while (defined $cursor && (ref $cursor eq 'PPI::Token::Comment' || ref $cursor eq 'PPI::Token::Whitespace')) {
        unshift @comments, $cursor;
        $cursor = $cursor->previous_token;
    }

    while (ref $comments[0] eq 'PPI::Token::Whitespace') {
        shift @comments;
    }

    $after->insert_before($_) for @comments;

    $after->insert_before($code_statement);

    my $whitespaces_document = PPI::Document->new(\"\n\n");
    $after->insert_before($_) for @{ $whitespaces_document->find('PPI::Token') };

    $document->save($file);
}

1;