Monkey-Patch-Action-0.05/0000755000175000017500000000000013126717745012621 5ustar u1u1Monkey-Patch-Action-0.05/README0000644000175000017500000001234513126717745013506 0ustar u1u1SYNOPSIS use Monkey::Patch::Action qw(patch_package); package Foo; sub sub1 { say "Foo's sub1" } sub sub2 { say "Foo's sub2, args=", join(",", @_) } sub meth1 { my $self = shift; say "Foo's meth1" } package Bar; our @ISA = qw(Foo); package main; my $h; # handle object my $foo = Foo->new; my $bar = Bar->new; # replacing a subroutine $h = patch_package('Foo', 'sub1', 'replace', sub { "qux" }); Foo::sub1(); # says "qux" undef $h; Foo::sub1(); # says "Foo's sub1" # adding a subroutine $h = patch_package('Foo', 'sub3', 'add', sub { "qux" }); Foo::sub3(); # says "qux" undef $h; Foo::sub3(); # dies # deleting a subroutine $h = patch_package('Foo', 'sub2', 'delete'); Foo::sub2(); # dies undef $h; Foo::sub2(); # says "Foo's sub2, args=" # wrapping a subroutine $h = patch_package('Foo', 'sub2', 'wrap', sub { my $ctx = shift; say "wrapping $ctx->{package}::$ctx->{subname}"; $ctx->{orig}->(@_); } ); Foo::sub2(1,2,3); # says "wrapping Foo::sub2" then "Foo's sub2, args=1,2,3" undef $h; Foo::sub2(1,2,3); # says "Foo's sub2, args=1,2,3" # stacking patches (note: can actually be unapplied in random order) my ($h2, $h3); $h = patch_package('Foo', 'sub1', 'replace', sub { "qux" }); Foo::sub1(); # says "qux" $h2 = patch_package('Foo', 'sub1', 'delete'); Foo::sub1(); # dies $h3 = patch_package('Foo', 'sub1', 'replace', sub { "quux" }); Foo::sub1(); # says "quux" undef $h3; Foo::sub1(); # dies undef $h2; Foo::sub1(); # says "qux" undef $h; Foo::sub1(); # says "Foo's sub1" DESCRIPTION Monkey-patching is the act of modifying a package at runtime: adding a subroutine/method, replacing/deleting/wrapping another, etc. Perl makes it easy to do that, for example: # add a subroutine *{"Target::sub1"} = sub { ... }; # another way, can be done from any file package Target; sub sub2 { ... } # delete a subroutine undef *{"Target::sub3"}; This module makes things even easier by helping you apply a stack of patches and unapply them later in flexible order. FUNCTIONS patch_package($package, $subname, $action, $code, @extra) => HANDLE Patch $package's subroutine named $subname. $action is either: * wrap $subname must already exist. code is required. Your code receives a context hash as its first argument, followed by any arguments the subroutine would have normally gotten. Context hash contains: orig (the original subroutine that is being wrapped), subname, package, extra. * add subname must not already exist. code is required. * replace subname must already exist. code is required. * add_or_replace code is required. * delete code is not needed. Die on error. Function returns a handle object. As soon as you lose the value of the handle (by calling in void context, assigning over the variable, undeffing the variable, letting it go out of scope, etc), the patch is unapplied. Patches can be unapplied in random order, but unapplying a patch where the next patch is a wrapper can lead to an error. Example: first patch (P1) adds a subroutine and second patch (P2) wraps it. If P1 is unapplied before P2, the subroutine is now no longer there, and P2 no longer works. Unapplying P1 after P2 works, of course. FAQ Differences with Monkey::Patch? This module is based on the wonderful Monkey::Patch by Paul Driver. The differences are: * This module adds the ability to add/replace/delete subroutines instead of just wrapping them. * Interface to patch_package() is slightly different (see previous item for the cause). * Using this module, the wrapper receives a context hash instead of just the original subroutine. * Monkey::Patch adds convenience for patching classes and objects. To keep things simple, no such convenience is currently provided by this module. patch_package() *can* patch classes and objects as well (see the next FAQ entry). How to patch classes and objects? Patching a class is basically the same as patching any other package, since Perl implements a class with a package. One thing to note is that to call a parent's method inside your wrapper code, instead of: $self->SUPER::methname(...) you need to do something like: use SUPER; SUPER::find_parent(ref($self), 'methname')->methname(...) Patching an object is also basically patching a class/package, because Perl does not have per-object method like Ruby. But if you just want to provide a modified behavior for a certain object only, you can do something like: patch_package($package, $methname, 'wrap', sub { my $ctx = shift; my $self = shift; my $obj = $ctx->{extra}[0]; no warnings 'numeric'; if ($obj == $self) { # do stuff } $ctx->{orig}->(@_); }, $obj); SEE ALSO Monkey::Patch Monkey-Patch-Action-0.05/dist.ini0000644000175000017500000000031413126717745014263 0ustar u1u1version = 0.05 name=Monkey-Patch-Action [@Author::PERLANCAR] :version=0.55 [Prereqs / TestRequires] Test::More=0.98 [Prereqs] perl=5.010001 strict=0 warnings=0 Exporter=0 Scalar::Util=0 Sub::Delete=0 Monkey-Patch-Action-0.05/Makefile.PL0000644000175000017500000000255613126717745014603 0ustar u1u1# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.008. use strict; use warnings; use 5.010001; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "Wrap/add/replace/delete subs from other package (with restore)", "AUTHOR" => "perlancar ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "Monkey-Patch-Action", "LICENSE" => "perl", "MIN_PERL_VERSION" => "5.010001", "NAME" => "Monkey::Patch::Action", "PREREQ_PM" => { "Exporter" => 0, "Scalar::Util" => 0, "Sub::Delete" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "File::Spec" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Test::More" => "0.98" }, "VERSION" => "0.05", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Exporter" => 0, "File::Spec" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Scalar::Util" => 0, "Sub::Delete" => 0, "Test::More" => "0.98", "strict" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Monkey-Patch-Action-0.05/META.yml0000644000175000017500000003076613126717745014106 0ustar u1u1--- abstract: 'Wrap/add/replace/delete subs from other package (with restore)' author: - 'perlancar ' build_requires: File::Spec: '0' IO::Handle: '0' IPC::Open3: '0' Test::More: '0.98' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Monkey-Patch-Action requires: Exporter: '0' Scalar::Util: '0' Sub::Delete: '0' perl: '5.010001' strict: '0' warnings: '0' resources: bugtracker: https://rt.cpan.org/Public/Dist/Display.html?Name=Monkey-Patch-Action homepage: https://metacpan.org/release/Monkey-Patch-Action repository: git://github.com/sharyanto/perl-Monkey-Patch-Action.git version: '0.05' x_Dist_Zilla: perl: version: '5.024000' plugins: - class: Dist::Zilla::Plugin::GatherDir config: Dist::Zilla::Plugin::GatherDir: exclude_filename: [] exclude_match: [] follow_symlinks: 0 include_dotfiles: 0 prefix: '' prune_directory: [] root: . name: '@Author::PERLANCAR/@Filter/GatherDir' version: '6.008' - class: Dist::Zilla::Plugin::PruneCruft name: '@Author::PERLANCAR/@Filter/PruneCruft' version: '6.008' - class: Dist::Zilla::Plugin::ManifestSkip name: '@Author::PERLANCAR/@Filter/ManifestSkip' version: '6.008' - class: Dist::Zilla::Plugin::MetaYAML name: '@Author::PERLANCAR/@Filter/MetaYAML' version: '6.008' - class: Dist::Zilla::Plugin::License name: '@Author::PERLANCAR/@Filter/License' version: '6.008' - class: Dist::Zilla::Plugin::PodCoverageTests name: '@Author::PERLANCAR/@Filter/PodCoverageTests' version: '6.008' - class: Dist::Zilla::Plugin::PodSyntaxTests name: '@Author::PERLANCAR/@Filter/PodSyntaxTests' version: '6.008' - class: Dist::Zilla::Plugin::ExtraTests name: '@Author::PERLANCAR/@Filter/ExtraTests' version: '6.008' - class: Dist::Zilla::Plugin::ExecDir name: '@Author::PERLANCAR/@Filter/ExecDir' version: '6.008' - class: Dist::Zilla::Plugin::ShareDir name: '@Author::PERLANCAR/@Filter/ShareDir' version: '6.008' - class: Dist::Zilla::Plugin::MakeMaker config: Dist::Zilla::Role::TestRunner: default_jobs: 1 name: '@Author::PERLANCAR/@Filter/MakeMaker' version: '6.008' - class: Dist::Zilla::Plugin::Manifest name: '@Author::PERLANCAR/@Filter/Manifest' version: '6.008' - class: Dist::Zilla::Plugin::ConfirmRelease name: '@Author::PERLANCAR/@Filter/ConfirmRelease' version: '6.008' - class: Dist::Zilla::Plugin::PERLANCAR::BeforeBuild name: '@Author::PERLANCAR/PERLANCAR::BeforeBuild' version: '0.55' - class: Dist::Zilla::Plugin::Rinci::AbstractFromMeta name: '@Author::PERLANCAR/Rinci::AbstractFromMeta' version: '0.09' - class: Dist::Zilla::Plugin::PodnameFromFilename name: '@Author::PERLANCAR/PodnameFromFilename' version: '0.02' - class: Dist::Zilla::Plugin::PERLANCAR::EnsurePrereqToSpec name: '@Author::PERLANCAR/PERLANCAR::EnsurePrereqToSpec' version: '0.04' - class: Dist::Zilla::Plugin::PERLANCAR::MetaResources name: '@Author::PERLANCAR/PERLANCAR::MetaResources' version: '0.03' - class: Dist::Zilla::Plugin::CheckChangeLog name: '@Author::PERLANCAR/CheckChangeLog' version: '0.02' - class: Dist::Zilla::Plugin::CheckMetaResources name: '@Author::PERLANCAR/CheckMetaResources' version: '0.001' - class: Dist::Zilla::Plugin::CopyrightYearFromGit name: '@Author::PERLANCAR/CopyrightYearFromGit' version: '0.003' - class: Dist::Zilla::Plugin::IfBuilt name: '@Author::PERLANCAR/IfBuilt' version: '0.03' - class: Dist::Zilla::Plugin::MetaJSON name: '@Author::PERLANCAR/MetaJSON' version: '6.008' - class: Dist::Zilla::Plugin::MetaConfig name: '@Author::PERLANCAR/MetaConfig' version: '6.008' - class: Dist::Zilla::Plugin::GenShellCompletion name: '@Author::PERLANCAR/GenShellCompletion' version: '0.11' - class: Dist::Zilla::Plugin::Authority name: '@Author::PERLANCAR/Authority' version: '1.009' - class: Dist::Zilla::Plugin::OurDate name: '@Author::PERLANCAR/OurDate' version: '0.03' - class: Dist::Zilla::Plugin::OurDist name: '@Author::PERLANCAR/OurDist' version: '0.02' - class: Dist::Zilla::Plugin::PERLANCAR::OurPkgVersion name: '@Author::PERLANCAR/PERLANCAR::OurPkgVersion' version: '0.04' - class: Dist::Zilla::Plugin::PodWeaver config: Dist::Zilla::Plugin::PodWeaver: finder: - ':InstallModules' - ':ExecFiles' plugins: - class: Pod::Weaver::Plugin::EnsurePod5 name: '@CorePrep/EnsurePod5' version: '4.013' - class: Pod::Weaver::Plugin::H1Nester name: '@CorePrep/H1Nester' version: '4.013' - class: Pod::Weaver::Section::Name name: '@Author::PERLANCAR/Name' version: '4.013' - class: Pod::Weaver::Section::Version name: '@Author::PERLANCAR/Version' version: '4.013' - class: Pod::Weaver::Section::Region name: '@Author::PERLANCAR/prelude' version: '4.013' - class: Pod::Weaver::Section::Generic name: SYNOPSIS version: '4.013' - class: Pod::Weaver::Section::Generic name: DESCRIPTION version: '4.013' - class: Pod::Weaver::Section::Generic name: OVERVIEW version: '4.013' - class: Pod::Weaver::Section::Collect name: ATTRIBUTES version: '4.013' - class: Pod::Weaver::Section::Collect name: METHODS version: '4.013' - class: Pod::Weaver::Section::Collect name: FUNCTIONS version: '4.013' - class: Pod::Weaver::Section::Leftovers name: '@Author::PERLANCAR/Leftovers' version: '4.013' - class: Pod::Weaver::Section::Region name: '@Author::PERLANCAR/postlude' version: '4.013' - class: Pod::Weaver::Section::Completion::GetoptLongComplete name: '@Author::PERLANCAR/Completion::GetoptLongComplete' version: '0.08' - class: Pod::Weaver::Section::Completion::GetoptLongSubcommand name: '@Author::PERLANCAR/Completion::GetoptLongSubcommand' version: '0.04' - class: Pod::Weaver::Section::Completion::GetoptLongMore name: '@Author::PERLANCAR/Completion::GetoptLongMore' version: '0.001' - class: Pod::Weaver::Section::Homepage::DefaultCPAN name: '@Author::PERLANCAR/Homepage::DefaultCPAN' version: '0.05' - class: Pod::Weaver::Section::Source::DefaultGitHub name: '@Author::PERLANCAR/Source::DefaultGitHub' version: '0.07' - class: Pod::Weaver::Section::Bugs::DefaultRT name: '@Author::PERLANCAR/Bugs::DefaultRT' version: '0.06' - class: Pod::Weaver::Section::Authors name: '@Author::PERLANCAR/Authors' version: '4.013' - class: Pod::Weaver::Section::Legal name: '@Author::PERLANCAR/Legal' version: '4.013' - class: Pod::Weaver::Plugin::Rinci name: '@Author::PERLANCAR/Rinci' version: '0.76' - class: Pod::Weaver::Plugin::AppendPrepend name: '@Author::PERLANCAR/AppendPrepend' version: '0.01' - class: Pod::Weaver::Plugin::EnsureUniqueSections name: '@Author::PERLANCAR/EnsureUniqueSections' version: '0.121550' - class: Pod::Weaver::Plugin::SingleEncoding name: '@Author::PERLANCAR/SingleEncoding' version: '4.013' - class: Pod::Weaver::Plugin::PERLANCAR::SortSections name: '@Author::PERLANCAR/PERLANCAR::SortSections' version: '0.06' name: '@Author::PERLANCAR/PodWeaver' version: '4.008' - class: Dist::Zilla::Plugin::PruneFiles name: '@Author::PERLANCAR/PruneFiles' version: '6.008' - class: Dist::Zilla::Plugin::ReadmeFromPod name: '@Author::PERLANCAR/ReadmeFromPod' version: '0.35' - class: Dist::Zilla::Plugin::Rinci::AddPrereqs name: '@Author::PERLANCAR/Rinci::AddPrereqs' version: '0.13' - class: Dist::Zilla::Plugin::Rinci::AddToDb name: '@Author::PERLANCAR/Rinci::AddToDb' version: '0.01' - class: Dist::Zilla::Plugin::Rinci::Validate name: '@Author::PERLANCAR/Rinci::Validate' version: '0.24' - class: Dist::Zilla::Plugin::SetScriptShebang name: '@Author::PERLANCAR/SetScriptShebang' version: '0.01' - class: Dist::Zilla::Plugin::Test::Compile config: Dist::Zilla::Plugin::Test::Compile: bail_out_on_fail: '0' fail_on_warning: author fake_home: 0 filename: t/00-compile.t module_finder: - ':InstallModules' needs_display: 0 phase: test script_finder: - ':PerlExecFiles' skips: [] name: '@Author::PERLANCAR/Test::Compile' version: '2.054' - class: Dist::Zilla::Plugin::Test::Rinci name: '@Author::PERLANCAR/Test::Rinci' version: '0.03' - class: Dist::Zilla::Plugin::UploadToCPAN::WWWPAUSESimple name: '@Author::PERLANCAR/UploadToCPAN::WWWPAUSESimple' version: '0.04' - class: Dist::Zilla::Plugin::EnsureSQLSchemaVersionedTest name: '@Author::PERLANCAR/EnsureSQLSchemaVersionedTest' version: '0.02' - class: Dist::Zilla::Plugin::Acme::CPANLists::Blacklist name: '@Author::PERLANCAR/Acme::CPANLists::Blacklist' version: '0.02' - class: Dist::Zilla::Plugin::Prereqs::EnsureVersion name: '@Author::PERLANCAR/Prereqs::EnsureVersion' version: '0.02' - class: Dist::Zilla::Plugin::Prereqs::CheckCircular name: '@Author::PERLANCAR/Prereqs::CheckCircular' version: '0.004' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: test type: requires name: TestRequires version: '6.008' - class: Dist::Zilla::Plugin::Prereqs config: Dist::Zilla::Plugin::Prereqs: phase: runtime type: requires name: Prereqs version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':InstallModules' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':IncModules' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':TestFiles' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':ExtraTestFiles' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':ExecFiles' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':PerlExecFiles' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':ShareFiles' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':MainModule' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':AllFiles' version: '6.008' - class: Dist::Zilla::Plugin::FinderCode name: ':NoFiles' version: '6.008' zilla: class: Dist::Zilla::Dist::Builder config: is_trial: '0' version: '6.008' x_authority: cpan:PERLANCAR x_serialization_backend: 'YAML::Tiny version 1.69' Monkey-Patch-Action-0.05/t/0000755000175000017500000000000013126717745013064 5ustar u1u1Monkey-Patch-Action-0.05/t/author-pod-syntax.t0000644000175000017500000000045413126717745016662 0ustar u1u1#!perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { print qq{1..0 # SKIP these tests are for testing by the author\n}; exit } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Monkey-Patch-Action-0.05/t/00-compile.t0000644000175000017500000000240513126717745015117 0ustar u1u1use 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.054 use Test::More; plan tests => 2 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'Monkey/Patch/Action.pm', 'Monkey/Patch/Action/Handle.pm' ); # no fake home requested my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); shift @_warnings if @_warnings and $_warnings[0] =~ /^Using .*\bblib/ and not eval { require blib; blib->VERSION('1.01') }; if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') or diag 'got warnings: ', ( Test::More->can('explain') ? Test::More::explain(\@warnings) : join("\n", '', @warnings) ) if $ENV{AUTHOR_TESTING}; Monkey-Patch-Action-0.05/t/01-basics.t0000644000175000017500000001760313126717745014742 0ustar u1u1#!perl use 5.010; use strict; use warnings; use Test::More 0.98; use Monkey::Patch::Action qw(patch_package); package Foo; sub f1 { "Foo's f1" } sub f2 { "Foo's f2, args=".join(",",@_) } sub m1 { my $self = shift; "Foo's m1, args=".join(",",@_) } package Bar; our @ISA = qw(Foo); package main; my @h; test_patch( name => 'unknown action -> dies', patch_args => [Foo => f1 => foo => sub { }], patch_dies => 1, ); test_patch( name => 'add existant -> dies', patch_args => [Foo => f1 => add => sub {}], patch_dies => 1, ); test_patch( name => 'add', patch_args => [Foo => fa => add => sub { "monkey" }], tests_before_patch => [ {func=>'Foo::fa', dies=>1}, ], tests_after_patch => [ {func=>'Foo::fa', res=>"monkey"}, ], ); test_patch( name => 'replace non-existant -> dies', patch_args => [Foo => fr => replace => sub {}], patch_dies => 1, ); test_patch( name => 'replace', patch_args => [Foo => f1 => replace => sub { "duck" }], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"duck"}, ], ); test_patch( name => 'add_or_replace', patches_args => [ [Foo => f1 => add_or_replace => sub { "punch" }], [Foo => fa => add_or_replace => sub { "patch" }], ], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, {func=>'Foo::fa', dies=>1}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"punch"}, {func=>'Foo::fa', res=>"patch"}, ], ); test_patch( name => 'delete mentioning code -> dies', patch_args => [Foo => f1 => delete => sub { }], patch_dies => 1, ); test_patch( name => 'delete', patches_args => [ [Foo => f1 => 'delete'], [Foo => fd => 'delete'], ], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, {func=>'Foo::fd', dies=>1}, ], tests_after_patch => [ {func=>'Foo::f1', dies=>1}, {func=>'Foo::fd', dies=>1}, ], ); test_patch( name => 'wrap non-existant -> dies', patch_args => [Foo => fw => wrap => sub {}], patch_dies => 1, ); test_patch( name => 'wrap', patch_args => [Foo => f1 => wrap => sub { my $ctx = shift; "wrap $ctx->{package} $ctx->{subname} ". join(",", @{$ctx->{extra}}).": ". $ctx->{orig}->(@_); }, 1, 2], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"wrap Foo f1 1,2: Foo's f1"}, ], ); subtest "stacked: wrap1 + wrap2 (wrap2 unapplied first)" => sub { test_patch( patches_args => [ [Foo => f1 => wrap => sub { my $ctx = shift; "wrap1: ".$ctx->{orig}->(@_); }], [Foo => f1 => wrap => sub { my $ctx = shift; "wrap2: ".$ctx->{orig}->(@_); }], ], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"wrap2: wrap1: Foo's f1"}, ], unpatch => 0, ); undef $h[1]; _tests([ {func=>'Foo::f1', res=>"wrap1: Foo's f1"}, ]); unpatch(); _tests([ {func=>'Foo::f1', res=>"Foo's f1"}, ]); }; subtest "stacked: wrap1 + wrap2 (wrap1 unapplied first)" => sub { test_patch( patches_args => [ [Foo => f1 => wrap => sub { my $ctx = shift; "wrap1: ".$ctx->{orig}->(@_); }], [Foo => f1 => wrap => sub { my $ctx = shift; "wrap2: ".$ctx->{orig}->(@_); }], ], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"wrap2: wrap1: Foo's f1"}, ], unpatch => 0, ); undef $h[0]; _tests([ {func=>'Foo::f1', res=>"wrap2: Foo's f1"}, ]); unpatch(); _tests([ {func=>'Foo::f1', res=>"Foo's f1"}, ]); }; subtest "stacked: del + add + wrap (unapply ordered)" => sub { test_patch( patches_args => [ [Foo => f1 => 'delete'], [Foo => f1 => add => sub { "plone" }], [Foo => f1 => wrap => sub { my $ctx = shift; "wrap: ".$ctx->{orig}->(@_); }], ], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"wrap: plone"}, ], unpatch => 0, ); undef $h[2]; _tests([ {func=>'Foo::f1', res=>"plone"}, ]); undef $h[1]; _tests([ {func=>'Foo::f1', dies=>1}, ]); unpatch(); _tests([ {func=>'Foo::f1', res=>"Foo's f1"}, ]); }; subtest "stacked: del + add + wrap (add unapplied -> conflict)" => sub { test_patch( patches_args => [ [Foo => f1 => 'delete'], [Foo => f1 => add => sub { "plone" }], [Foo => f1 => wrap => sub { my $ctx = shift; "wrap: ".($ctx->{orig}->(@_) // "X"); }], ], tests_before_patch => [ {func=>'Foo::f1', res=>"Foo's f1"}, ], tests_after_patch => [ {func=>'Foo::f1', res=>"wrap: plone"}, ], unpatch => 0, ); undef $h[1]; _tests([ {func=>'Foo::f1', res=>"wrap: X"}, ]); unpatch(); _tests([ {func=>'Foo::f1', res=>"Foo's f1"}, ]); }; # XXX test: calling parent's method from wrapper # XXX test: demo patching object DONE_TESTING: done_testing(); sub unpatch { pop @h while @h; } sub _tests { my ($tests, $name) = @_; subtest $name => sub { for my $t (@$tests) { my $code = "$t->{func}(".join(",",map{"'$_'"} @{$t->{args} // []}).")"; my $res; subtest $code => sub { eval "\$res = $code;"; my $e = $@; if ($t->{dies}) { ok($e, "dies"); return; } else { ok(!$e, "doesn't die") or do { diag $e; return }; } if (defined $t->{res}) { is($res, $t->{res}, "result"); } }; } }; } sub test_patch { my %args = @_; subtest $args{name} => sub { _tests($args{tests_before_patch}, "tests before patch") if $args{tests_before_patch}; eval { if ($args{patch_args}) { push @h, patch_package(@{ $args{patch_args} }); } if ($args{patches_args}) { push @h, patch_package(@$_) for @{ $args{patches_args} }; } }; my $e = $@; if ($args{patch_dies}) { ok($e, "patch dies"); return; } else { ok(!$e, "patch doesn't die") or do { diag $e; return }; } _tests($args{tests_after_patch}, "tests after patch") if $args{tests_after_patch}; if ($args{unpatch} // 1) { unpatch(); my $t = $args{tests_after_unpatch} // 1; $t = $args{tests_before_patch} if !ref($t); _tests($t, "tests after unpatch") if $t; } }; } Monkey-Patch-Action-0.05/t/author-pod-coverage.t0000644000175000017500000000053613126717745017130 0ustar u1u1#!perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { print qq{1..0 # SKIP these tests are for testing by the author\n}; exit } } # This file was automatically generated by Dist::Zilla::Plugin::PodCoverageTests. use Test::Pod::Coverage 1.08; use Pod::Coverage::TrustPod; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); Monkey-Patch-Action-0.05/weaver.ini0000644000175000017500000000002513126717745014610 0ustar u1u1[@Author::PERLANCAR] Monkey-Patch-Action-0.05/META.json0000644000175000017500000004526613126717745014257 0ustar u1u1{ "abstract" : "Wrap/add/replace/delete subs from other package (with restore)", "author" : [ "perlancar " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Monkey-Patch-Action", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Pod::Coverage::TrustPod" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08" } }, "runtime" : { "requires" : { "Exporter" : "0", "Scalar::Util" : "0", "Sub::Delete" : "0", "perl" : "5.010001", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Test::More" : "0.98" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=Monkey-Patch-Action" }, "homepage" : "https://metacpan.org/release/Monkey-Patch-Action", "repository" : { "type" : "git", "url" : "git://github.com/sharyanto/perl-Monkey-Patch-Action.git", "web" : "https://github.com/sharyanto/perl-Monkey-Patch-Action" } }, "version" : "0.05", "x_Dist_Zilla" : { "perl" : { "version" : "5.024000" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." } }, "name" : "@Author::PERLANCAR/@Filter/GatherDir", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@Author::PERLANCAR/@Filter/PruneCruft", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::ManifestSkip", "name" : "@Author::PERLANCAR/@Filter/ManifestSkip", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::PERLANCAR/@Filter/MetaYAML", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::PERLANCAR/@Filter/License", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::PodCoverageTests", "name" : "@Author::PERLANCAR/@Filter/PodCoverageTests", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::PERLANCAR/@Filter/PodSyntaxTests", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::ExtraTests", "name" : "@Author::PERLANCAR/@Filter/ExtraTests", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@Author::PERLANCAR/@Filter/ExecDir", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@Author::PERLANCAR/@Filter/ShareDir", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1 } }, "name" : "@Author::PERLANCAR/@Filter/MakeMaker", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::PERLANCAR/@Filter/Manifest", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::PERLANCAR/@Filter/ConfirmRelease", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::PERLANCAR::BeforeBuild", "name" : "@Author::PERLANCAR/PERLANCAR::BeforeBuild", "version" : "0.55" }, { "class" : "Dist::Zilla::Plugin::Rinci::AbstractFromMeta", "name" : "@Author::PERLANCAR/Rinci::AbstractFromMeta", "version" : "0.09" }, { "class" : "Dist::Zilla::Plugin::PodnameFromFilename", "name" : "@Author::PERLANCAR/PodnameFromFilename", "version" : "0.02" }, { "class" : "Dist::Zilla::Plugin::PERLANCAR::EnsurePrereqToSpec", "name" : "@Author::PERLANCAR/PERLANCAR::EnsurePrereqToSpec", "version" : "0.04" }, { "class" : "Dist::Zilla::Plugin::PERLANCAR::MetaResources", "name" : "@Author::PERLANCAR/PERLANCAR::MetaResources", "version" : "0.03" }, { "class" : "Dist::Zilla::Plugin::CheckChangeLog", "name" : "@Author::PERLANCAR/CheckChangeLog", "version" : "0.02" }, { "class" : "Dist::Zilla::Plugin::CheckMetaResources", "name" : "@Author::PERLANCAR/CheckMetaResources", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::CopyrightYearFromGit", "name" : "@Author::PERLANCAR/CopyrightYearFromGit", "version" : "0.003" }, { "class" : "Dist::Zilla::Plugin::IfBuilt", "name" : "@Author::PERLANCAR/IfBuilt", "version" : "0.03" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::PERLANCAR/MetaJSON", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::PERLANCAR/MetaConfig", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::GenShellCompletion", "name" : "@Author::PERLANCAR/GenShellCompletion", "version" : "0.11" }, { "class" : "Dist::Zilla::Plugin::Authority", "name" : "@Author::PERLANCAR/Authority", "version" : "1.009" }, { "class" : "Dist::Zilla::Plugin::OurDate", "name" : "@Author::PERLANCAR/OurDate", "version" : "0.03" }, { "class" : "Dist::Zilla::Plugin::OurDist", "name" : "@Author::PERLANCAR/OurDist", "version" : "0.02" }, { "class" : "Dist::Zilla::Plugin::PERLANCAR::OurPkgVersion", "name" : "@Author::PERLANCAR/PERLANCAR::OurPkgVersion", "version" : "0.04" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.013" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Author::PERLANCAR/Name", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Author::PERLANCAR/Version", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::PERLANCAR/prelude", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Author::PERLANCAR/Leftovers", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::PERLANCAR/postlude", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Completion::GetoptLongComplete", "name" : "@Author::PERLANCAR/Completion::GetoptLongComplete", "version" : "0.08" }, { "class" : "Pod::Weaver::Section::Completion::GetoptLongSubcommand", "name" : "@Author::PERLANCAR/Completion::GetoptLongSubcommand", "version" : "0.04" }, { "class" : "Pod::Weaver::Section::Completion::GetoptLongMore", "name" : "@Author::PERLANCAR/Completion::GetoptLongMore", "version" : "0.001" }, { "class" : "Pod::Weaver::Section::Homepage::DefaultCPAN", "name" : "@Author::PERLANCAR/Homepage::DefaultCPAN", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Source::DefaultGitHub", "name" : "@Author::PERLANCAR/Source::DefaultGitHub", "version" : "0.07" }, { "class" : "Pod::Weaver::Section::Bugs::DefaultRT", "name" : "@Author::PERLANCAR/Bugs::DefaultRT", "version" : "0.06" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Author::PERLANCAR/Authors", "version" : "4.013" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Author::PERLANCAR/Legal", "version" : "4.013" }, { "class" : "Pod::Weaver::Plugin::Rinci", "name" : "@Author::PERLANCAR/Rinci", "version" : "0.76" }, { "class" : "Pod::Weaver::Plugin::AppendPrepend", "name" : "@Author::PERLANCAR/AppendPrepend", "version" : "0.01" }, { "class" : "Pod::Weaver::Plugin::EnsureUniqueSections", "name" : "@Author::PERLANCAR/EnsureUniqueSections", "version" : "0.121550" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Author::PERLANCAR/SingleEncoding", "version" : "4.013" }, { "class" : "Pod::Weaver::Plugin::PERLANCAR::SortSections", "name" : "@Author::PERLANCAR/PERLANCAR::SortSections", "version" : "0.06" } ] } }, "name" : "@Author::PERLANCAR/PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::PruneFiles", "name" : "@Author::PERLANCAR/PruneFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::ReadmeFromPod", "name" : "@Author::PERLANCAR/ReadmeFromPod", "version" : "0.35" }, { "class" : "Dist::Zilla::Plugin::Rinci::AddPrereqs", "name" : "@Author::PERLANCAR/Rinci::AddPrereqs", "version" : "0.13" }, { "class" : "Dist::Zilla::Plugin::Rinci::AddToDb", "name" : "@Author::PERLANCAR/Rinci::AddToDb", "version" : "0.01" }, { "class" : "Dist::Zilla::Plugin::Rinci::Validate", "name" : "@Author::PERLANCAR/Rinci::Validate", "version" : "0.24" }, { "class" : "Dist::Zilla::Plugin::SetScriptShebang", "name" : "@Author::PERLANCAR/SetScriptShebang", "version" : "0.01" }, { "class" : "Dist::Zilla::Plugin::Test::Compile", "config" : { "Dist::Zilla::Plugin::Test::Compile" : { "bail_out_on_fail" : 0, "fail_on_warning" : "author", "fake_home" : 0, "filename" : "t/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "test", "script_finder" : [ ":PerlExecFiles" ], "skips" : [] } }, "name" : "@Author::PERLANCAR/Test::Compile", "version" : "2.054" }, { "class" : "Dist::Zilla::Plugin::Test::Rinci", "name" : "@Author::PERLANCAR/Test::Rinci", "version" : "0.03" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN::WWWPAUSESimple", "name" : "@Author::PERLANCAR/UploadToCPAN::WWWPAUSESimple", "version" : "0.04" }, { "class" : "Dist::Zilla::Plugin::EnsureSQLSchemaVersionedTest", "name" : "@Author::PERLANCAR/EnsureSQLSchemaVersionedTest", "version" : "0.02" }, { "class" : "Dist::Zilla::Plugin::Acme::CPANLists::Blacklist", "name" : "@Author::PERLANCAR/Acme::CPANLists::Blacklist", "version" : "0.02" }, { "class" : "Dist::Zilla::Plugin::Prereqs::EnsureVersion", "name" : "@Author::PERLANCAR/Prereqs::EnsureVersion", "version" : "0.02" }, { "class" : "Dist::Zilla::Plugin::Prereqs::CheckCircular", "name" : "@Author::PERLANCAR/Prereqs::CheckCircular", "version" : "0.004" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "test", "type" : "requires" } }, "name" : "TestRequires", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "requires" } }, "name" : "Prereqs", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.008" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.008" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.008" } }, "x_authority" : "cpan:PERLANCAR", "x_serialization_backend" : "Cpanel::JSON::XS version 3.0217" } Monkey-Patch-Action-0.05/MANIFEST0000644000175000017500000000045413126717745013755 0ustar u1u1# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.008. Changes LICENSE MANIFEST META.json META.yml Makefile.PL README dist.ini lib/Monkey/Patch/Action.pm lib/Monkey/Patch/Action/Handle.pm t/00-compile.t t/01-basics.t t/author-pod-coverage.t t/author-pod-syntax.t weaver.ini Monkey-Patch-Action-0.05/lib/0000755000175000017500000000000013126717745013367 5ustar u1u1Monkey-Patch-Action-0.05/lib/Monkey/0000755000175000017500000000000013126717745014631 5ustar u1u1Monkey-Patch-Action-0.05/lib/Monkey/Patch/0000755000175000017500000000000013126717745015670 5ustar u1u1Monkey-Patch-Action-0.05/lib/Monkey/Patch/Action.pm0000644000175000017500000001667213126717745017457 0ustar u1u1package Monkey::Patch::Action; use 5.010001; use warnings; use strict; our $VERSION = '0.05'; # VERSION use Monkey::Patch::Action::Handle; use Exporter qw(import); our @EXPORT_OK = qw(patch_package); our %EXPORT_TAGS = (all => \@EXPORT_OK); sub patch_package { my ($package, $subname, $action, $code, @extra) = @_; die "Please specify action" unless $action; if ($action eq 'delete') { die "code not needed for 'delete' action" if $code; } else { die "Please specify code" unless $code; } my $name = "$package\::$subname"; my $type; if ($action eq 'add') { die "Adding $name: must not already exist" if defined(&$name); $type = 'sub'; } elsif ($action eq 'replace') { die "Replacing $name: must already exist" unless defined(&$name); $type = 'sub'; } elsif ($action eq 'add_or_replace') { $type = 'sub'; } elsif ($action eq 'wrap') { die "Wrapping $name: must already exist" unless defined(&$name); $type = 'wrap'; } elsif ($action eq 'delete') { $type = 'delete'; } else { die "Unknown action '$action', please use either ". "wrap/add/replace/add_or_replace/delete"; } my @caller = caller(0); Monkey::Patch::Action::Handle->new( package => $package, subname => $subname, extra => \@extra, patcher => \@caller, code => $code, -type => $type, ); } 1; # ABSTRACT: Wrap/add/replace/delete subs from other package (with restore) __END__ =pod =encoding UTF-8 =head1 NAME Monkey::Patch::Action - Wrap/add/replace/delete subs from other package (with restore) =head1 VERSION This document describes version 0.05 of Monkey::Patch::Action (from Perl distribution Monkey-Patch-Action), released on 2017-07-04. =head1 SYNOPSIS use Monkey::Patch::Action qw(patch_package); package Foo; sub sub1 { say "Foo's sub1" } sub sub2 { say "Foo's sub2, args=", join(",", @_) } sub meth1 { my $self = shift; say "Foo's meth1" } package Bar; our @ISA = qw(Foo); package main; my $h; # handle object my $foo = Foo->new; my $bar = Bar->new; # replacing a subroutine $h = patch_package('Foo', 'sub1', 'replace', sub { "qux" }); Foo::sub1(); # says "qux" undef $h; Foo::sub1(); # says "Foo's sub1" # adding a subroutine $h = patch_package('Foo', 'sub3', 'add', sub { "qux" }); Foo::sub3(); # says "qux" undef $h; Foo::sub3(); # dies # deleting a subroutine $h = patch_package('Foo', 'sub2', 'delete'); Foo::sub2(); # dies undef $h; Foo::sub2(); # says "Foo's sub2, args=" # wrapping a subroutine $h = patch_package('Foo', 'sub2', 'wrap', sub { my $ctx = shift; say "wrapping $ctx->{package}::$ctx->{subname}"; $ctx->{orig}->(@_); } ); Foo::sub2(1,2,3); # says "wrapping Foo::sub2" then "Foo's sub2, args=1,2,3" undef $h; Foo::sub2(1,2,3); # says "Foo's sub2, args=1,2,3" # stacking patches (note: can actually be unapplied in random order) my ($h2, $h3); $h = patch_package('Foo', 'sub1', 'replace', sub { "qux" }); Foo::sub1(); # says "qux" $h2 = patch_package('Foo', 'sub1', 'delete'); Foo::sub1(); # dies $h3 = patch_package('Foo', 'sub1', 'replace', sub { "quux" }); Foo::sub1(); # says "quux" undef $h3; Foo::sub1(); # dies undef $h2; Foo::sub1(); # says "qux" undef $h; Foo::sub1(); # says "Foo's sub1" =head1 DESCRIPTION Monkey-patching is the act of modifying a package at runtime: adding a subroutine/method, replacing/deleting/wrapping another, etc. Perl makes it easy to do that, for example: # add a subroutine *{"Target::sub1"} = sub { ... }; # another way, can be done from any file package Target; sub sub2 { ... } # delete a subroutine undef *{"Target::sub3"}; This module makes things even easier by helping you apply a stack of patches and unapply them later in flexible order. =head1 FUNCTIONS =head2 patch_package($package, $subname, $action, $code, @extra) => HANDLE Patch C<$package>'s subroutine named C<$subname>. C<$action> is either: =over 4 =item * C C<$subname> must already exist. C is required. Your code receives a context hash as its first argument, followed by any arguments the subroutine would have normally gotten. Context hash contains: C (the original subroutine that is being wrapped), C, C, C. =item * C C must not already exist. C is required. =item * C C must already exist. C is required. =item * C C is required. =item * C C is not needed. =back Die on error. Function returns a handle object. As soon as you lose the value of the handle (by calling in void context, assigning over the variable, undeffing the variable, letting it go out of scope, etc), the patch is unapplied. Patches can be unapplied in random order, but unapplying a patch where the next patch is a wrapper can lead to an error. Example: first patch (P1) adds a subroutine and second patch (P2) wraps it. If P1 is unapplied before P2, the subroutine is now no longer there, and P2 no longer works. Unapplying P1 after P2 works, of course. =head1 FAQ =head2 Differences with Monkey::Patch? This module is based on the wonderful L by Paul Driver. The differences are: =over 4 =item * This module adds the ability to add/replace/delete subroutines instead of just wrapping them. =item * Interface to patch_package() is slightly different (see previous item for the cause). =item * Using this module, the wrapper receives a context hash instead of just the original subroutine. =item * Monkey::Patch adds convenience for patching classes and objects. To keep things simple, no such convenience is currently provided by this module. C *can* patch classes and objects as well (see the next FAQ entry). =back =head2 How to patch classes and objects? Patching a class is basically the same as patching any other package, since Perl implements a class with a package. One thing to note is that to call a parent's method inside your wrapper code, instead of: $self->SUPER::methname(...) you need to do something like: use SUPER; SUPER::find_parent(ref($self), 'methname')->methname(...) Patching an object is also basically patching a class/package, because Perl does not have per-object method like Ruby. But if you just want to provide a modified behavior for a certain object only, you can do something like: patch_package($package, $methname, 'wrap', sub { my $ctx = shift; my $self = shift; my $obj = $ctx->{extra}[0]; no warnings 'numeric'; if ($obj == $self) { # do stuff } $ctx->{orig}->(@_); }, $obj); =head1 HOMEPAGE Please visit the project's homepage at L. =head1 SOURCE Source repository is at L. =head1 BUGS Please report any bugs or feature requests on the bugtracker website L When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 SEE ALSO L =head1 AUTHOR perlancar =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2017, 2012 by perlancar@cpan.org. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Monkey-Patch-Action-0.05/lib/Monkey/Patch/Action/0000755000175000017500000000000013126717745017105 5ustar u1u1Monkey-Patch-Action-0.05/lib/Monkey/Patch/Action/Handle.pm0000644000175000017500000000732613126717745020646 0ustar u1u1package Monkey::Patch::Action::Handle; use 5.010; use strict; use warnings; use Scalar::Util qw(weaken); use Sub::Delete; our $VERSION = '0.05'; # VERSION my %stacks; sub __find_previous { my ($stack, $code) = @_; state $empty = sub {}; for my $i (1..$#$stack) { if ($stack->[$i][1] == $code) { return $stack->[$i-1][2] // $stack->[$i-1][1]; } } $empty; } sub new { my ($class, %args) = @_; my $type = $args{-type}; delete $args{-type}; my $code = $args{code}; my $name = "$args{package}::$args{subname}"; my $stack; if (!$stacks{$name}) { $stacks{$name} = []; push @{$stacks{$name}}, [sub => \&$name] if defined(&$name); } $stack = $stacks{$name}; my $self = bless \%args, $class; no strict 'refs'; no warnings 'redefine'; if ($type eq 'sub') { push @$stack, [$type => $code]; *$name = $code; } elsif ($type eq 'delete') { $code = sub {}; $args{code} = $code; push @$stack, [$type, $code]; delete_sub $name; } elsif ($type eq 'wrap') { weaken($self); my $wrapper = sub { my $ctx = { package => $self->{package}, subname => $self->{subname}, extra => $self->{extra}, orig => __find_previous($stack, $self->{code}), }; unshift @_, $ctx; goto &{$self->{code}}; }; push @$stack, [$type => $code => $wrapper]; *$name = $wrapper; } $self; } sub DESTROY { my $self = shift; my $name = "$self->{package}::$self->{subname}"; my $stack = $stacks{$name}; my $code = $self->{code}; for my $i (0..$#$stack) { if($stack->[$i][1] == $code) { if ($stack->[$i+1]) { # check conflict if ($stack->[$i+1][0] eq 'wrap' && ($i == 0 || $stack->[$i-1][0] eq 'delete')) { my $p = $self->{patcher}; warn "Warning: unapplying patch to $name ". "(applied in $p->[1]:$p->[2]) before a wrapping patch"; } } no strict 'refs'; if ($i == @$stack-1) { if ($i) { no warnings 'redefine'; if ($stack->[$i-1][0] eq 'delete') { delete_sub $name; } else { *$name = $stack->[$i-1][2] // $stack->[$i-1][1]; } } else { delete_sub $name; } } splice @$stack, $i, 1; last; } } } 1; __END__ =pod =encoding UTF-8 =head1 NAME Monkey::Patch::Action::Handle =head1 VERSION This document describes version 0.05 of Monkey::Patch::Action::Handle (from Perl distribution Monkey-Patch-Action), released on 2017-07-04. =for Pod::Coverage .* =head1 HOMEPAGE Please visit the project's homepage at L. =head1 SOURCE Source repository is at L. =head1 BUGS Please report any bugs or feature requests on the bugtracker website L When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 AUTHOR perlancar =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2017, 2012 by perlancar@cpan.org. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Monkey-Patch-Action-0.05/LICENSE0000644000175000017500000004372113126717745013635 0ustar u1u1This software is copyright (c) 2017, 2012 by perlancar@cpan.org. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2017, 2012 by perlancar@cpan.org. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2017, 2012 by perlancar@cpan.org. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Monkey-Patch-Action-0.05/Changes0000644000175000017500000000113313126717745014112 0ustar u1u10.05 2017-07-04 (PERLANCAR) - No functional changes. - [build] Rebuild to use Makefile.PL instead of Build.PL. 0.04 2012-12-14 (SHARYANTO) - No functional changes. Revert 0.03 (warning is good). 0.03 2012-12-14 (SHARYANTO) - No functional changes. Shut up warning about prototype mismatch (probably temporary). 0.02 2012-08-30 (SHARYANTO) - Rename dist from Alt-Monkey-Patch-SHARYANTO to Monkey-Patch-Action, this is not an Alt module (incompatible interface). 0.01 2012-08-03 (SHARYANTO) - First release.