-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMonkeyPatch.pm
executable file
·79 lines (62 loc) · 1.52 KB
/
MonkeyPatch.pm
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
package MonkeyPatch;
use strict;
use warnings;
no strict 'refs';
no warnings qw/redefine syntax/;
our %FUNCTIONS_PATCHED = ();
sub patch {
my %param = ();
if (scalar @_ == 1) {
%param = ( $_[0] => sub {} );
} else {
%param = @_;
}
for my $name (keys %param) {
my $sub = $param{$name};
$name = findGlobNameByRef($name);
if (!defined($FUNCTIONS_PATCHED{$name})) {
$FUNCTIONS_PATCHED{$name} = \&{*{$name}};
}
*{$name} = $sub || sub {};
}
}
sub findGlobNameByRef {
my ($functionRef) = @_;
if ($functionRef =~ /^CODE\([\da-fx]+\)/) {
foreach my $globName (keys %::) {
my $globRef = \&{$::{$globName}};
if ($functionRef eq $globRef) {
if (index( $globName, '::' ) == -1) {
$globName = 'main::'.$globName;
}
return $globName;
}
}
}
return $functionRef;
}
sub runOriginal {
my $name = shift;
$name = findGlobNameByRef($name);
if (defined($FUNCTIONS_PATCHED{$name})) {
return &{$FUNCTIONS_PATCHED{$name}}(@_);
} else {
return *{$name}->(@_);
}
}
sub unpatch {
my @names = @_;
for my $name (@names) {
$name = findGlobNameByRef($name);
if (defined($FUNCTIONS_PATCHED{$name})) {
*{$name} = \&{$FUNCTIONS_PATCHED{$name}};
$FUNCTIONS_PATCHED{$name} = undef;
delete $FUNCTIONS_PATCHED{$name};
}
}
}
sub unpatchAll {
unpatch(keys %FUNCTIONS_PATCHED);
%FUNCTIONS_PATCHED = ();
}
1;