??????????????????????????????? ??????????????????????????????? ??????????????????????????????? >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>. ??????????????????????????????? ??????????????????????????????? ??????????????????????????????? ??????????????????????????????? ??????????????????????????????? ??????????????????????????????? >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< PK!íßA))perl5/ExtUtils/MM_DOS.pmnuÏÃ6Ç$package ExtUtils::MM_DOS; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Any; require ExtUtils::MM_Unix; our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix ); =head1 NAME ExtUtils::MM_DOS - DOS specific subclass of ExtUtils::MM_Unix =head1 SYNOPSIS Don't use this module directly. Use ExtUtils::MM and let it choose. =head1 DESCRIPTION This is a subclass of L which contains functionality for DOS. Unless otherwise stated, it works just like ExtUtils::MM_Unix. =head2 Overridden methods =over 4 =item os_flavor =cut sub os_flavor { return('DOS'); } =item B Generates Foo__Bar.3 style man page names =cut sub replace_manpage_separator { my($self, $man) = @_; $man =~ s,/+,__,g; return $man; } =item xs_static_lib_is_xs =cut sub xs_static_lib_is_xs { return 1; } =back =head1 AUTHOR Michael G Schwern with code from ExtUtils::MM_Unix =head1 SEE ALSO L, L =cut 1; PK!¹! Üu!u!perl5/ExtUtils/Packlist.pmnuÏÃ6Ç$package ExtUtils::Packlist; use 5.00503; use strict; use Carp qw(); use Config; use vars qw($VERSION $Relocations); $VERSION = '2.06'; $VERSION = eval $VERSION; # Used for generating filehandle globs. IO::File might not be available! my $fhname = "FH1"; =begin _undocumented =over =item mkfh() Make a filehandle. Same kind of idea as Symbol::gensym(). =cut sub mkfh() { no strict; local $^W; my $fh = \*{$fhname++}; use strict; return($fh); } =item __find_relocations Works out what absolute paths in the configuration have been located at run time relative to $^X, and generates a regexp that matches them =back =end _undocumented =cut sub __find_relocations { my %paths; while (my ($raw_key, $raw_val) = each %Config) { my $exp_key = $raw_key . "exp"; next unless exists $Config{$exp_key}; next unless $raw_val =~ m!\.\.\./!; $paths{$Config{$exp_key}}++; } # Longest prefixes go first in the alternatives my $alternations = join "|", map {quotemeta $_} sort {length $b <=> length $a} keys %paths; qr/^($alternations)/o; } sub new($$) { my ($class, $packfile) = @_; $class = ref($class) || $class; my %self; tie(%self, $class, $packfile); return(bless(\%self, $class)); } sub TIEHASH { my ($class, $packfile) = @_; my $self = { packfile => $packfile }; bless($self, $class); $self->read($packfile) if (defined($packfile) && -f $packfile); return($self); } sub STORE { $_[0]->{data}->{$_[1]} = $_[2]; } sub FETCH { return($_[0]->{data}->{$_[1]}); } sub FIRSTKEY { my $reset = scalar(keys(%{$_[0]->{data}})); return(each(%{$_[0]->{data}})); } sub NEXTKEY { return(each(%{$_[0]->{data}})); } sub EXISTS { return(exists($_[0]->{data}->{$_[1]})); } sub DELETE { return(delete($_[0]->{data}->{$_[1]})); } sub CLEAR { %{$_[0]->{data}} = (); } sub DESTROY { } sub read($;$) { my ($self, $packfile) = @_; $self = tied(%$self) || $self; if (defined($packfile)) { $self->{packfile} = $packfile; } else { $packfile = $self->{packfile}; } Carp::croak("No packlist filename specified") if (! defined($packfile)); my $fh = mkfh(); open($fh, "<$packfile") || Carp::croak("Can't open file $packfile: $!"); $self->{data} = {}; my ($line); while (defined($line = <$fh>)) { chomp $line; my ($key, $data) = $line; if ($key =~ /^(.*?)( \w+=.*)$/) { $key = $1; $data = { map { split('=', $_) } split(' ', $2)}; if ($Config{userelocatableinc} && $data->{relocate_as}) { require File::Spec; require Cwd; my ($vol, $dir) = File::Spec->splitpath($packfile); my $newpath = File::Spec->catpath($vol, $dir, $data->{relocate_as}); $key = Cwd::realpath($newpath); } } $key =~ s!/\./!/!g; # Some .packlists have spurious '/./' bits in the paths $self->{data}->{$key} = $data; } close($fh); } sub write($;$) { my ($self, $packfile) = @_; $self = tied(%$self) || $self; if (defined($packfile)) { $self->{packfile} = $packfile; } else { $packfile = $self->{packfile}; } Carp::croak("No packlist filename specified") if (! defined($packfile)); my $fh = mkfh(); open($fh, ">$packfile") || Carp::croak("Can't open file $packfile: $!"); foreach my $key (sort(keys(%{$self->{data}}))) { my $data = $self->{data}->{$key}; if ($Config{userelocatableinc}) { $Relocations ||= __find_relocations(); if ($packfile =~ $Relocations) { # We are writing into a subdirectory of a run-time relocated # path. Figure out if the this file is also within a subdir. my $prefix = $1; if (File::Spec->no_upwards(File::Spec->abs2rel($key, $prefix))) { # The relocated path is within the found prefix my $packfile_prefix; (undef, $packfile_prefix) = File::Spec->splitpath($packfile); my $relocate_as = File::Spec->abs2rel($key, $packfile_prefix); if (!ref $data) { $data = {}; } $data->{relocate_as} = $relocate_as; } } } print $fh ("$key"); if (ref($data)) { foreach my $k (sort(keys(%$data))) { print $fh (" $k=$data->{$k}"); } } print $fh ("\n"); } close($fh); } sub validate($;$) { my ($self, $remove) = @_; $self = tied(%$self) || $self; my @missing; foreach my $key (sort(keys(%{$self->{data}}))) { if (! -e $key) { push(@missing, $key); delete($self->{data}{$key}) if ($remove); } } return(@missing); } sub packlist_file($) { my ($self) = @_; $self = tied(%$self) || $self; return($self->{packfile}); } 1; __END__ =head1 NAME ExtUtils::Packlist - manage .packlist files =head1 SYNOPSIS use ExtUtils::Packlist; my ($pl) = ExtUtils::Packlist->new('.packlist'); $pl->read('/an/old/.packlist'); my @missing_files = $pl->validate(); $pl->write('/a/new/.packlist'); $pl->{'/some/file/name'}++; or $pl->{'/some/other/file/name'} = { type => 'file', from => '/some/file' }; =head1 DESCRIPTION ExtUtils::Packlist provides a standard way to manage .packlist files. Functions are provided to read and write .packlist files. The original .packlist format is a simple list of absolute pathnames, one per line. In addition, this package supports an extended format, where as well as a filename each line may contain a list of attributes in the form of a space separated list of key=value pairs. This is used by the installperl script to differentiate between files and links, for example. =head1 USAGE The hash reference returned by the new() function can be used to examine and modify the contents of the .packlist. Items may be added/deleted from the .packlist by modifying the hash. If the value associated with a hash key is a scalar, the entry written to the .packlist by any subsequent write() will be a simple filename. If the value is a hash, the entry written will be the filename followed by the key=value pairs from the hash. Reading back the .packlist will recreate the original entries. =head1 FUNCTIONS =over 4 =item new() This takes an optional parameter, the name of a .packlist. If the file exists, it will be opened and the contents of the file will be read. The new() method returns a reference to a hash. This hash holds an entry for each line in the .packlist. In the case of old-style .packlists, the value associated with each key is undef. In the case of new-style .packlists, the value associated with each key is a hash containing the key=value pairs following the filename in the .packlist. =item read() This takes an optional parameter, the name of the .packlist to be read. If no file is specified, the .packlist specified to new() will be read. If the .packlist does not exist, Carp::croak will be called. =item write() This takes an optional parameter, the name of the .packlist to be written. If no file is specified, the .packlist specified to new() will be overwritten. =item validate() This checks that every file listed in the .packlist actually exists. If an argument which evaluates to true is given, any missing files will be removed from the internal hash. The return value is a list of the missing files, which will be empty if they all exist. =item packlist_file() This returns the name of the associated .packlist file =back =head1 EXAMPLE Here's C, a little utility to cleanly remove an installed module. #!/usr/local/bin/perl -w use strict; use IO::Dir; use ExtUtils::Packlist; use ExtUtils::Installed; sub emptydir($) { my ($dir) = @_; my $dh = IO::Dir->new($dir) || return(0); my @count = $dh->read(); $dh->close(); return(@count == 2 ? 1 : 0); } # Find all the installed packages print("Finding all installed modules...\n"); my $installed = ExtUtils::Installed->new(); foreach my $module (grep(!/^Perl$/, $installed->modules())) { my $version = $installed->version($module) || "???"; print("Found module $module Version $version\n"); print("Do you want to delete $module? [n] "); my $r = ; chomp($r); if ($r && $r =~ /^y/i) { # Remove all the files foreach my $file (sort($installed->files($module))) { print("rm $file\n"); unlink($file); } my $pf = $installed->packlist($module)->packlist_file(); print("rm $pf\n"); unlink($pf); foreach my $dir (sort($installed->directory_tree($module))) { if (emptydir($dir)) { print("rmdir $dir\n"); rmdir($dir); } } } } =head1 AUTHOR Alan Burlison =cut PK!t2âiúúperl5/ExtUtils/MM_VOS.pmnuÏÃ6Ç$package ExtUtils::MM_VOS; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Unix; our @ISA = qw(ExtUtils::MM_Unix); =head1 NAME ExtUtils::MM_VOS - VOS specific subclass of ExtUtils::MM_Unix =head1 SYNOPSIS Don't use this module directly. Use ExtUtils::MM and let it choose. =head1 DESCRIPTION This is a subclass of L which contains functionality for VOS. Unless otherwise stated it works just like ExtUtils::MM_Unix. =head2 Overridden methods =head3 extra_clean_files Cleanup VOS core files =cut sub extra_clean_files { return qw(*.kp); } =head1 AUTHOR Michael G Schwern with code from ExtUtils::MM_Unix =head1 SEE ALSO L =cut 1; PK! €ž� � perl5/ExtUtils/MM_OS2.pmnuÏÃ6Ç$package ExtUtils::MM_OS2; use strict; use warnings; use ExtUtils::MakeMaker qw(neatvalue); use File::Spec; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Any; require ExtUtils::MM_Unix; our @ISA = qw(ExtUtils::MM_Any ExtUtils::MM_Unix); =pod =head1 NAME ExtUtils::MM_OS2 - methods to override UN*X behaviour in ExtUtils::MakeMaker =head1 SYNOPSIS use ExtUtils::MM_OS2; # Done internally by ExtUtils::MakeMaker if needed =head1 DESCRIPTION See L for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. =head1 METHODS =over 4 =item init_dist Define TO_UNIX to convert OS2 linefeeds to Unix style. =cut sub init_dist { my($self) = @_; $self->{TO_UNIX} ||= <<'MAKE_TEXT'; $(NOECHO) $(TEST_F) tmp.zip && $(RM_F) tmp.zip; $(ZIP) -ll -mr tmp.zip $(DISTVNAME) && unzip -o tmp.zip && $(RM_F) tmp.zip MAKE_TEXT $self->SUPER::init_dist; } sub dlsyms { my($self,%attribs) = @_; if ($self->{IMPORTS} && %{$self->{IMPORTS}}) { # Make import files (needed for static build) -d 'tmp_imp' or mkdir 'tmp_imp', 0777 or die "Can't mkdir tmp_imp"; open my $imp, '>', 'tmpimp.imp' or die "Can't open tmpimp.imp"; foreach my $name (sort keys %{$self->{IMPORTS}}) { my $exp = $self->{IMPORTS}->{$name}; my ($lib, $id) = ($exp =~ /(.*)\.(.*)/) or die "Malformed IMPORT `$exp'"; print $imp "$name $lib $id ?\n"; } close $imp or die "Can't close tmpimp.imp"; # print "emximp -o tmpimp$Config::Config{lib_ext} tmpimp.imp\n"; system "emximp -o tmpimp$Config::Config{lib_ext} tmpimp.imp" and die "Cannot make import library: $!, \$?=$?"; # May be running under miniperl, so have no glob... eval { unlink ; 1 } or system "rm tmp_imp/*"; system "cd tmp_imp; $Config::Config{ar} x ../tmpimp$Config::Config{lib_ext}" and die "Cannot extract import objects: $!, \$?=$?"; } return '' if $self->{SKIPHASH}{'dynamic'}; $self->xs_dlsyms_iterator(\%attribs); } sub xs_dlsyms_ext { '.def'; } sub xs_dlsyms_extra { join '', map { qq{, "$_" => "\$($_)"} } qw(VERSION DISTNAME INSTALLDIRS); } sub static_lib_pure_cmd { my($self) = @_; my $old = $self->SUPER::static_lib_pure_cmd; return $old unless $self->{IMPORTS} && %{$self->{IMPORTS}}; $old . <<'EOC'; $(AR) $(AR_STATIC_ARGS) "$@" tmp_imp/* $(RANLIB) "$@" EOC } sub replace_manpage_separator { my($self,$man) = @_; $man =~ s,/+,.,g; $man; } sub maybe_command { my($self,$file) = @_; $file =~ s,[/\\]+,/,g; return $file if -x $file && ! -d _; return "$file.exe" if -x "$file.exe" && ! -d _; return "$file.cmd" if -x "$file.cmd" && ! -d _; return; } =item init_linker =cut sub init_linker { my $self = shift; $self->{PERL_ARCHIVE} = "\$(PERL_INC)/libperl\$(LIB_EXT)"; $self->{PERL_ARCHIVEDEP} ||= ''; $self->{PERL_ARCHIVE_AFTER} = $OS2::is_aout ? '' : '$(PERL_INC)/libperl_override$(LIB_EXT)'; $self->{EXPORT_LIST} = '$(BASEEXT).def'; } =item os_flavor OS/2 is OS/2 =cut sub os_flavor { return('OS/2'); } =item xs_static_lib_is_xs =cut sub xs_static_lib_is_xs { return 1; } =back =cut 1; PK!‡8Óperl5/ExtUtils/Command/MM.pmnuÏÃ6Ç$package ExtUtils::Command::MM; require 5.006; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(test_harness pod2man perllocal_install uninstall warn_if_old_packlist test_s cp_nonempty); our $VERSION = '7.50'; $VERSION =~ tr/_//d; my $Is_VMS = $^O eq 'VMS'; sub mtime { no warnings 'redefine'; local $@; *mtime = (eval { require Time::HiRes } && defined &Time::HiRes::stat) ? sub { (Time::HiRes::stat($_[0]))[9] } : sub { ( stat($_[0]))[9] } ; goto &mtime; } =head1 NAME ExtUtils::Command::MM - Commands for the MM's to use in Makefiles =head1 SYNOPSIS perl "-MExtUtils::Command::MM" -e "function" "--" arguments... =head1 DESCRIPTION B The interface is not stable. ExtUtils::Command::MM encapsulates code which would otherwise have to be done with large "one" liners. Any $(FOO) used in the examples are make variables, not Perl. =over 4 =item B test_harness($verbose, @test_libs); Runs the tests on @ARGV via Test::Harness passing through the $verbose flag. Any @test_libs will be unshifted onto the test's @INC. @test_libs are run in alphabetical order. =cut sub test_harness { require Test::Harness; require File::Spec; $Test::Harness::verbose = shift; # Because Windows doesn't do this for us and listing all the *.t files # out on the command line can blow over its exec limit. require ExtUtils::Command; my @argv = ExtUtils::Command::expand_wildcards(@ARGV); local @INC = @INC; unshift @INC, map { File::Spec->rel2abs($_) } @_; Test::Harness::runtests(sort { lc $a cmp lc $b } @argv); } =item B pod2man( '--option=value', $podfile1 => $manpage1, $podfile2 => $manpage2, ... ); # or args on @ARGV pod2man() is a function performing most of the duties of the pod2man program. Its arguments are exactly the same as pod2man as of 5.8.0 with the addition of: --perm_rw octal permission to set the resulting manpage to And the removal of: --verbose/-v --help/-h If no arguments are given to pod2man it will read from @ARGV. If Pod::Man is unavailable, this function will warn and return undef. =cut sub pod2man { local @ARGV = @_ ? @_ : @ARGV; { local $@; if( !eval { require Pod::Man } ) { warn "Pod::Man is not available: $@". "Man pages will not be generated during this install.\n"; return 0; } } require Getopt::Long; # We will cheat and just use Getopt::Long. We fool it by putting # our arguments into @ARGV. Should be safe. my %options = (); Getopt::Long::config ('bundling_override'); Getopt::Long::GetOptions (\%options, 'section|s=s', 'release|r=s', 'center|c=s', 'date|d=s', 'fixed=s', 'fixedbold=s', 'fixeditalic=s', 'fixedbolditalic=s', 'official|o', 'quotes|q=s', 'lax|l', 'name|n=s', 'perm_rw=i', 'utf8|u' ); delete $options{utf8} unless $Pod::Man::VERSION >= 2.17; # If there's no files, don't bother going further. return 0 unless @ARGV; # Official sets --center, but don't override things explicitly set. if ($options{official} && !defined $options{center}) { $options{center} = q[Perl Programmer's Reference Guide]; } # This isn't a valid Pod::Man option and is only accepted for backwards # compatibility. delete $options{lax}; my $count = scalar @ARGV / 2; my $plural = $count == 1 ? 'document' : 'documents'; print "Manifying $count pod $plural\n"; do {{ # so 'next' works my ($pod, $man) = splice(@ARGV, 0, 2); next if ((-e $man) && (mtime($man) > mtime($pod)) && (mtime($man) > mtime("Makefile"))); my $parser = Pod::Man->new(%options); $parser->parse_from_file($pod, $man) or do { warn("Could not install $man\n"); next }; if (exists $options{perm_rw}) { chmod(oct($options{perm_rw}), $man) or do { warn("chmod $options{perm_rw} $man: $!\n"); next }; } }} while @ARGV; return 1; } =item B perl "-MExtUtils::Command::MM" -e warn_if_old_packlist Displays a warning that an old packlist file was found. Reads the filename from @ARGV. =cut sub warn_if_old_packlist { my $packlist = $ARGV[0]; return unless -f $packlist; print <<"PACKLIST_WARNING"; WARNING: I have found an old package in $packlist. Please make sure the two installations are not conflicting PACKLIST_WARNING } =item B perl "-MExtUtils::Command::MM" -e perllocal_install ... # VMS only, key|value pairs come on STDIN perl "-MExtUtils::Command::MM" -e perllocal_install < | ... Prints a fragment of POD suitable for appending to perllocal.pod. Arguments are read from @ARGV. 'type' is the type of what you're installing. Usually 'Module'. 'module name' is simply the name of your module. (Foo::Bar) Key/value pairs are extra information about the module. Fields include: installed into which directory your module was out into LINKTYPE dynamic or static linking VERSION module version number EXE_FILES any executables installed in a space separated list =cut sub perllocal_install { my($type, $name) = splice(@ARGV, 0, 2); # VMS feeds args as a piped file on STDIN since it usually can't # fit all the args on a single command line. my @mod_info = $Is_VMS ? split /\|/, : @ARGV; my $pod; my $time = gmtime($ENV{SOURCE_DATE_EPOCH} || time); $pod = sprintf <<'POD', scalar($time), $type, $name, $name; =head2 %s: C<%s> L<%s|%s> =over 4 POD do { my($key, $val) = splice(@mod_info, 0, 2); $pod .= < POD } while(@mod_info); $pod .= "=back\n\n"; $pod =~ s/^ //mg; print $pod; return 1; } =item B perl "-MExtUtils::Command::MM" -e uninstall A wrapper around ExtUtils::Install::uninstall(). Warns that uninstallation is deprecated and doesn't actually perform the uninstallation. =cut sub uninstall { my($packlist) = shift @ARGV; require ExtUtils::Install; print <<'WARNING'; Uninstall is unsafe and deprecated, the uninstallation was not performed. We will show what would have been done. WARNING ExtUtils::Install::uninstall($packlist, 1, 1); print <<'WARNING'; Uninstall is unsafe and deprecated, the uninstallation was not performed. Please check the list above carefully, there may be errors. Remove the appropriate files manually. Sorry for the inconvenience. WARNING } =item B perl "-MExtUtils::Command::MM" -e test_s Tests if a file exists and is not empty (size > 0). I with 0 if it does, 1 if it does not. =cut sub test_s { exit(-s $ARGV[0] ? 0 : 1); } =item B perl "-MExtUtils::Command::MM" -e cp_nonempty Tests if the source file exists and is not empty (size > 0). If it is not empty it copies it to the given destination with the given permissions. =back =cut sub cp_nonempty { my @args = @ARGV; return 0 unless -s $args[0]; require ExtUtils::Command; { local @ARGV = @args[0,1]; ExtUtils::Command::cp(@ARGV); } { local @ARGV = @args[2,1]; ExtUtils::Command::chmod(@ARGV); } } 1; PK!6ÕFN›C›Cperl5/ExtUtils/MM_Any.pmnuÏÃ6Ç$package ExtUtils::MM_Any; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use Carp; use File::Spec; use File::Basename; BEGIN { our @ISA = qw(File::Spec); } # We need $Verbose use ExtUtils::MakeMaker qw($Verbose neatvalue _sprintf562); use ExtUtils::MakeMaker::Config; # So we don't have to keep calling the methods over and over again, # we have these globals to cache the values. Faster and shrtr. my $Curdir = __PACKAGE__->curdir; #my $Updir = __PACKAGE__->updir; my $METASPEC_URL = 'https://metacpan.org/pod/CPAN::Meta::Spec'; my $METASPEC_V = 2; =head1 NAME ExtUtils::MM_Any - Platform-agnostic MM methods =head1 SYNOPSIS FOR INTERNAL USE ONLY! package ExtUtils::MM_SomeOS; # Temporarily, you have to subclass both. Put MM_Any first. require ExtUtils::MM_Any; require ExtUtils::MM_Unix; @ISA = qw(ExtUtils::MM_Any ExtUtils::Unix); =head1 DESCRIPTION B ExtUtils::MM_Any is a superclass for the ExtUtils::MM_* set of modules. It contains methods which are either inherently cross-platform or are written in a cross-platform manner. Subclass off of ExtUtils::MM_Any I L. This is a temporary solution. B =head1 METHODS Any methods marked I must be implemented by subclasses. =head2 Cross-platform helper methods These are methods which help writing cross-platform code. =head3 os_flavor I my @os_flavor = $mm->os_flavor; @os_flavor is the style of operating system this is, usually corresponding to the MM_*.pm file we're using. The first element of @os_flavor is the major family (ie. Unix, Windows, VMS, OS/2, etc...) and the rest are sub families. Some examples: Cygwin98 ('Unix', 'Cygwin', 'Cygwin9x') Windows ('Win32') Win98 ('Win32', 'Win9x') Linux ('Unix', 'Linux') MacOS X ('Unix', 'Darwin', 'MacOS', 'MacOS X') OS/2 ('OS/2') This is used to write code for styles of operating system. See os_flavor_is() for use. =head3 os_flavor_is my $is_this_flavor = $mm->os_flavor_is($this_flavor); my $is_this_flavor = $mm->os_flavor_is(@one_of_these_flavors); Checks to see if the current operating system is one of the given flavors. This is useful for code like: if( $mm->os_flavor_is('Unix') ) { $out = `foo 2>&1`; } else { $out = `foo`; } =cut sub os_flavor_is { my $self = shift; my %flavors = map { ($_ => 1) } $self->os_flavor; return (grep { $flavors{$_} } @_) ? 1 : 0; } =head3 can_load_xs my $can_load_xs = $self->can_load_xs; Returns true if we have the ability to load XS. This is important because miniperl, used to build XS modules in the core, can not load XS. =cut sub can_load_xs { return defined &DynaLoader::boot_DynaLoader ? 1 : 0; } =head3 can_run use ExtUtils::MM; my $runnable = MM->can_run($Config{make}); If called in a scalar context it will return the full path to the binary you asked for if it was found, or C if it was not. If called in a list context, it will return a list of the full paths to instances of the binary where found in C, or an empty list if it was not found. Copied from L, but modified into a method (and removed C<$INSTANCES> capability). =cut sub can_run { my ($self, $command) = @_; # a lot of VMS executables have a symbol defined # check those first if ( $^O eq 'VMS' ) { require VMS::DCLsym; my $syms = VMS::DCLsym->new; return $command if scalar $syms->getsym( uc $command ); } my @possibles; if( File::Spec->file_name_is_absolute($command) ) { return $self->maybe_command($command); } else { for my $dir ( File::Spec->path, File::Spec->curdir ) { next if ! $dir || ! -d $dir; my $abs = File::Spec->catfile($self->os_flavor_is('Win32') ? Win32::GetShortPathName( $dir ) : $dir, $command); push @possibles, $abs if $abs = $self->maybe_command($abs); } } return @possibles if wantarray; return shift @possibles; } =head3 can_redirect_error $useredirect = MM->can_redirect_error; True if on an OS where qx operator (or backticks) can redirect C onto C. =cut sub can_redirect_error { my $self = shift; $self->os_flavor_is('Unix') or ($self->os_flavor_is('Win32') and !$self->os_flavor_is('Win9x')) or $self->os_flavor_is('OS/2') } =head3 is_make_type my $is_dmake = $self->is_make_type('dmake'); Returns true if C<< $self->make >> is the given type; possibilities are: gmake GNU make dmake nmake bsdmake BSD pmake-derived =cut my %maketype2true; # undocumented - so t/cd.t can still do its thing sub _clear_maketype_cache { %maketype2true = () } sub is_make_type { my($self, $type) = @_; return $maketype2true{$type} if defined $maketype2true{$type}; (undef, undef, my $make_basename) = $self->splitpath($self->make); return $maketype2true{$type} = 1 if $make_basename =~ /\b$type\b/i; # executable's filename return $maketype2true{$type} = 0 if $make_basename =~ /\b[gdn]make\b/i; # Never fall through for dmake/nmake/gmake # now have to run with "-v" and guess my $redirect = $self->can_redirect_error ? '2>&1' : ''; my $make = $self->make || $self->{MAKE}; my $minus_v = `"$make" -v $redirect`; return $maketype2true{$type} = 1 if $type eq 'gmake' and $minus_v =~ /GNU make/i; return $maketype2true{$type} = 1 if $type eq 'bsdmake' and $minus_v =~ /^usage: make \[-BeikNnqrstWwX\]/im; $maketype2true{$type} = 0; # it wasn't whatever you asked } =head3 can_dep_space my $can_dep_space = $self->can_dep_space; Returns true if C can handle (probably by quoting) dependencies that contain a space. Currently known true for GNU make, false for BSD pmake derivative. =cut my $cached_dep_space; sub can_dep_space { my $self = shift; return $cached_dep_space if defined $cached_dep_space; return $cached_dep_space = 1 if $self->is_make_type('gmake'); return $cached_dep_space = 0 if $self->is_make_type('dmake'); # only on W32 return $cached_dep_space = 0 if $self->is_make_type('bsdmake'); return $cached_dep_space = 0; # assume no } =head3 quote_dep $text = $mm->quote_dep($text); Method that protects Makefile single-value constants (mainly filenames), so that make will still treat them as single values even if they inconveniently have spaces in. If the make program being used cannot achieve such protection and the given text would need it, throws an exception. =cut sub quote_dep { my ($self, $arg) = @_; die <can_dep_space; Tried to use make dependency with space for make that can't: '$arg' EOF $arg =~ s/( )/\\$1/g; # how GNU make does it return $arg; } =head3 split_command my @cmds = $MM->split_command($cmd, @args); Most OS have a maximum command length they can execute at once. Large modules can easily generate commands well past that limit. Its necessary to split long commands up into a series of shorter commands. C will return a series of @cmds each processing part of the args. Collectively they will process all the arguments. Each individual line in @cmds will not be longer than the $self->max_exec_len being careful to take into account macro expansion. $cmd should include any switches and repeated initial arguments. If no @args are given, no @cmds will be returned. Pairs of arguments will always be preserved in a single command, this is a heuristic for things like pm_to_blib and pod2man which work on pairs of arguments. This makes things like this safe: $self->split_command($cmd, %pod2man); =cut sub split_command { my($self, $cmd, @args) = @_; my @cmds = (); return(@cmds) unless @args; # If the command was given as a here-doc, there's probably a trailing # newline. chomp $cmd; # set aside 30% for macro expansion. my $len_left = int($self->max_exec_len * 0.70); $len_left -= length $self->_expand_macros($cmd); do { my $arg_str = ''; my @next_args; while( @next_args = splice(@args, 0, 2) ) { # Two at a time to preserve pairs. my $next_arg_str = "\t ". join ' ', @next_args, "\n"; if( !length $arg_str ) { $arg_str .= $next_arg_str } elsif( length($arg_str) + length($next_arg_str) > $len_left ) { unshift @args, @next_args; last; } else { $arg_str .= $next_arg_str; } } chop $arg_str; push @cmds, $self->escape_newlines("$cmd \n$arg_str"); } while @args; return @cmds; } sub _expand_macros { my($self, $cmd) = @_; $cmd =~ s{\$\((\w+)\)}{ defined $self->{$1} ? $self->{$1} : "\$($1)" }e; return $cmd; } =head3 make_type Returns a suitable string describing the type of makefile being written. =cut # override if this isn't suitable! sub make_type { return 'Unix-style'; } =head3 stashmeta my @recipelines = $MM->stashmeta($text, $file); Generates a set of C<@recipelines> which will result in the literal C<$text> ending up in literal C<$file> when the recipe is executed. Call it once, with all the text you want in C<$file>. Make macros will not be expanded, so the locations will be fixed at configure-time, not at build-time. =cut sub stashmeta { my($self, $text, $file) = @_; $self->echo($text, $file, { allow_variables => 0, append => 0 }); } =head3 echo my @commands = $MM->echo($text); my @commands = $MM->echo($text, $file); my @commands = $MM->echo($text, $file, \%opts); Generates a set of @commands which print the $text to a $file. If $file is not given, output goes to STDOUT. If $opts{append} is true the $file will be appended to rather than overwritten. Default is to overwrite. If $opts{allow_variables} is true, make variables of the form C<$(...)> will not be escaped. Other C<$> will. Default is to escape all C<$>. Example of use: my $make = join '', map "\t$_\n", $MM->echo($text, $file); =cut sub echo { my($self, $text, $file, $opts) = @_; # Compatibility with old options if( !ref $opts ) { my $append = $opts; $opts = { append => $append || 0 }; } $opts->{allow_variables} = 0 unless defined $opts->{allow_variables}; my $ql_opts = { allow_variables => $opts->{allow_variables} }; my @cmds = map { '$(NOECHO) $(ECHO) '.$self->quote_literal($_, $ql_opts) } split /\n/, $text; if( $file ) { my $redirect = $opts->{append} ? '>>' : '>'; $cmds[0] .= " $redirect $file"; $_ .= " >> $file" foreach @cmds[1..$#cmds]; } return @cmds; } =head3 wraplist my $args = $mm->wraplist(@list); Takes an array of items and turns them into a well-formatted list of arguments. In most cases this is simply something like: FOO \ BAR \ BAZ =cut sub wraplist { my $self = shift; return join " \\\n\t", @_; } =head3 maketext_filter my $filter_make_text = $mm->maketext_filter($make_text); The text of the Makefile is run through this method before writing to disk. It allows systems a chance to make portability fixes to the Makefile. By default it does nothing. This method is protected and not intended to be called outside of MakeMaker. =cut sub maketext_filter { return $_[1] } =head3 cd I my $subdir_cmd = $MM->cd($subdir, @cmds); This will generate a make fragment which runs the @cmds in the given $dir. The rough equivalent to this, except cross platform. cd $subdir && $cmd Currently $dir can only go down one level. "foo" is fine. "foo/bar" is not. "../foo" is right out. The resulting $subdir_cmd has no leading tab nor trailing newline. This makes it easier to embed in a make string. For example. my $make = sprintf <<'CODE', $subdir_cmd; foo : $(ECHO) what %s $(ECHO) mouche CODE =head3 oneliner I my $oneliner = $MM->oneliner($perl_code); my $oneliner = $MM->oneliner($perl_code, \@switches); This will generate a perl one-liner safe for the particular platform you're on based on the given $perl_code and @switches (a -e is assumed) suitable for using in a make target. It will use the proper shell quoting and escapes. $(PERLRUN) will be used as perl. Any newlines in $perl_code will be escaped. Leading and trailing newlines will be stripped. Makes this idiom much easier: my $code = $MM->oneliner(<<'CODE', [...switches...]); some code here another line here CODE Usage might be something like: # an echo emulation $oneliner = $MM->oneliner('print "Foo\n"'); $make = '$oneliner > somefile'; Dollar signs in the $perl_code will be protected from make using the C method, unless they are recognised as being a make variable, C<$(varname)>, in which case they will be left for make to expand. Remember to quote make macros else it might be used as a bareword. For example: # Assign the value of the $(VERSION_FROM) make macro to $vf. $oneliner = $MM->oneliner('$vf = "$(VERSION_FROM)"'); Its currently very simple and may be expanded sometime in the figure to include more flexible code and switches. =head3 quote_literal I my $safe_text = $MM->quote_literal($text); my $safe_text = $MM->quote_literal($text, \%options); This will quote $text so it is interpreted literally in the shell. For example, on Unix this would escape any single-quotes in $text and put single-quotes around the whole thing. If $options{allow_variables} is true it will leave C<'$(FOO)'> make variables untouched. If false they will be escaped like any other C<$>. Defaults to true. =head3 escape_dollarsigns my $escaped_text = $MM->escape_dollarsigns($text); Escapes stray C<$> so they are not interpreted as make variables. It lets by C<$(...)>. =cut sub escape_dollarsigns { my($self, $text) = @_; # Escape dollar signs which are not starting a variable $text =~ s{\$ (?!\() }{\$\$}gx; return $text; } =head3 escape_all_dollarsigns my $escaped_text = $MM->escape_all_dollarsigns($text); Escapes all C<$> so they are not interpreted as make variables. =cut sub escape_all_dollarsigns { my($self, $text) = @_; # Escape dollar signs $text =~ s{\$}{\$\$}gx; return $text; } =head3 escape_newlines I my $escaped_text = $MM->escape_newlines($text); Shell escapes newlines in $text. =head3 max_exec_len I my $max_exec_len = $MM->max_exec_len; Calculates the maximum command size the OS can exec. Effectively, this is the max size of a shell command line. =for _private $self->{_MAX_EXEC_LEN} is set by this method, but only for testing purposes. =head3 make my $make = $MM->make; Returns the make variant we're generating the Makefile for. This attempts to do some normalization on the information from %Config or the user. =cut sub make { my $self = shift; my $make = lc $self->{MAKE}; # Truncate anything like foomake6 to just foomake. $make =~ s/^(\w+make).*/$1/; # Turn gnumake into gmake. $make =~ s/^gnu/g/; return $make; } =head2 Targets These are methods which produce make targets. =head3 all_target Generate the default target 'all'. =cut sub all_target { my $self = shift; return <<'MAKE_EXT'; all :: pure_all $(NOECHO) $(NOOP) MAKE_EXT } =head3 blibdirs_target my $make_frag = $mm->blibdirs_target; Creates the blibdirs target which creates all the directories we use in blib/. The blibdirs.ts target is deprecated. Depend on blibdirs instead. =cut sub _xs_list_basenames { my ($self) = @_; map { (my $b = $_) =~ s/\.xs$//; $b } sort keys %{ $self->{XS} }; } sub blibdirs_target { my $self = shift; my @dirs = map { uc "\$(INST_$_)" } qw(libdir archlib autodir archautodir bin script man1dir man3dir ); if ($self->{XSMULTI}) { for my $ext ($self->_xs_list_basenames) { my ($v, $d, $f) = File::Spec->splitpath($ext); my @d = File::Spec->splitdir($d); shift @d if $d[0] eq 'lib'; push @dirs, $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f); } } my @exists = map { $_.'$(DFSEP).exists' } @dirs; my $make = sprintf <<'MAKE', join(' ', @exists); blibdirs : %s $(NOECHO) $(NOOP) # Backwards compat with 6.18 through 6.25 blibdirs.ts : blibdirs $(NOECHO) $(NOOP) MAKE $make .= $self->dir_target(@dirs); return $make; } =head3 clean (o) Defines the clean target. =cut sub clean { # --- Cleanup and Distribution Sections --- my($self, %attribs) = @_; my @m; push(@m, ' # Delete temporary files but do not touch installed files. We don\'t delete # the Makefile here so a later make realclean still has a makefile to use. clean :: clean_subdirs '); my @files = sort values %{$self->{XS}}; # .c files from *.xs files push @files, map { my $file = $_; map { $file.$_ } $self->{OBJ_EXT}, qw(.def _def.old .bs .bso .exp .base); } $self->_xs_list_basenames; my @dirs = qw(blib); # Normally these are all under blib but they might have been # redefined. # XXX normally this would be a good idea, but the Perl core sets # INST_LIB = ../../lib rather than actually installing the files. # So a "make clean" in an ext/ directory would blow away lib. # Until the core is adjusted let's leave this out. # push @dirs, qw($(INST_ARCHLIB) $(INST_LIB) # $(INST_BIN) $(INST_SCRIPT) # $(INST_MAN1DIR) $(INST_MAN3DIR) # $(INST_LIBDIR) $(INST_ARCHLIBDIR) $(INST_AUTODIR) # $(INST_STATIC) $(INST_DYNAMIC) # ); if( $attribs{FILES} ) { # Use @dirs because we don't know what's in here. push @dirs, ref $attribs{FILES} ? @{$attribs{FILES}} : split /\s+/, $attribs{FILES} ; } push(@files, qw[$(MAKE_APERL_FILE) MYMETA.json MYMETA.yml perlmain.c tmon.out mon.out so_locations blibdirs.ts pm_to_blib pm_to_blib.ts *$(OBJ_EXT) *$(LIB_EXT) perl.exe perl perl$(EXE_EXT) $(BOOTSTRAP) $(BASEEXT).bso $(BASEEXT).def lib$(BASEEXT).def $(BASEEXT).exp $(BASEEXT).x ]); push(@files, $self->catfile('$(INST_ARCHAUTODIR)','extralibs.all')); push(@files, $self->catfile('$(INST_ARCHAUTODIR)','extralibs.ld')); # core files if ($^O eq 'vos') { push(@files, qw[perl*.kp]); } else { push(@files, qw[core core.*perl.*.? *perl.core]); } push(@files, map { "core." . "[0-9]"x$_ } (1..5)); # OS specific things to clean up. Use @dirs since we don't know # what might be in here. push @dirs, $self->extra_clean_files; # Occasionally files are repeated several times from different sources { my(%f) = map { ($_ => 1) } @files; @files = sort keys %f; } { my(%d) = map { ($_ => 1) } @dirs; @dirs = sort keys %d; } push @m, map "\t$_\n", $self->split_command('- $(RM_F)', @files); push @m, map "\t$_\n", $self->split_command('- $(RM_RF)', @dirs); # Leave Makefile.old around for realclean push @m, <<'MAKE'; $(NOECHO) $(RM_F) $(MAKEFILE_OLD) - $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) $(DEV_NULL) MAKE push(@m, "\t$attribs{POSTOP}\n") if $attribs{POSTOP}; join("", @m); } =head3 clean_subdirs_target my $make_frag = $MM->clean_subdirs_target; Returns the clean_subdirs target. This is used by the clean target to call clean on any subdirectories which contain Makefiles. =cut sub clean_subdirs_target { my($self) = shift; # No subdirectories, no cleaning. return <<'NOOP_FRAG' unless @{$self->{DIR}}; clean_subdirs : $(NOECHO) $(NOOP) NOOP_FRAG my $clean = "clean_subdirs :\n"; for my $dir (@{$self->{DIR}}) { my $subclean = $self->oneliner(sprintf <<'CODE', $dir); exit 0 unless chdir '%s'; system '$(MAKE) clean' if -f '$(FIRST_MAKEFILE)'; CODE $clean .= "\t$subclean\n"; } return $clean; } =head3 dir_target my $make_frag = $mm->dir_target(@directories); Generates targets to create the specified directories and set its permission to PERM_DIR. Because depending on a directory to just ensure it exists doesn't work too well (the modified time changes too often) dir_target() creates a .exists file in the created directory. It is this you should depend on. For portability purposes you should use the $(DIRFILESEP) macro rather than a '/' to separate the directory from the file. yourdirectory$(DIRFILESEP).exists =cut sub dir_target { my($self, @dirs) = @_; my $make = ''; foreach my $dir (@dirs) { $make .= sprintf <<'MAKE', ($dir) x 4; %s$(DFSEP).exists :: Makefile.PL $(NOECHO) $(MKPATH) %s $(NOECHO) $(CHMOD) $(PERM_DIR) %s $(NOECHO) $(TOUCH) %s$(DFSEP).exists MAKE } return $make; } =head3 distdir Defines the scratch directory target that will hold the distribution before tar-ing (or shar-ing). =cut # For backwards compatibility. *dist_dir = *distdir; sub distdir { my($self) = shift; my $meta_target = $self->{NO_META} ? '' : 'distmeta'; my $sign_target = !$self->{SIGN} ? '' : 'distsignature'; return sprintf <<'MAKE_FRAG', $meta_target, $sign_target; create_distdir : $(RM_RF) $(DISTVNAME) $(PERLRUN) "-MExtUtils::Manifest=manicopy,maniread" \ -e "manicopy(maniread(),'$(DISTVNAME)', '$(DIST_CP)');" distdir : create_distdir %s %s $(NOECHO) $(NOOP) MAKE_FRAG } =head3 dist_test Defines a target that produces the distribution in the scratch directory, and runs 'perl Makefile.PL; make ;make test' in that subdirectory. =cut sub dist_test { my($self) = shift; my $mpl_args = join " ", map qq["$_"], @ARGV; my $test = $self->cd('$(DISTVNAME)', '$(ABSPERLRUN) Makefile.PL '.$mpl_args, '$(MAKE) $(PASTHRU)', '$(MAKE) test $(PASTHRU)' ); return sprintf <<'MAKE_FRAG', $test; disttest : distdir %s MAKE_FRAG } =head3 xs_dlsyms_arg Returns command-line arg(s) to linker for file listing dlsyms to export. Defaults to returning empty string, can be overridden by e.g. AIX. =cut sub xs_dlsyms_arg { return ''; } =head3 xs_dlsyms_ext Returns file-extension for C method's output file, including any "." character. =cut sub xs_dlsyms_ext { die "Pure virtual method"; } =head3 xs_dlsyms_extra Returns any extra text to be prepended to the C<$extra> argument of C. =cut sub xs_dlsyms_extra { ''; } =head3 xs_dlsyms_iterator Iterates over necessary shared objects, calling C method for each with appropriate arguments. =cut sub xs_dlsyms_iterator { my ($self, $attribs) = @_; if ($self->{XSMULTI}) { my @m; for my $ext ($self->_xs_list_basenames) { my @parts = File::Spec->splitdir($ext); shift @parts if $parts[0] eq 'lib'; my $name = join '::', @parts; push @m, $self->xs_make_dlsyms( $attribs, $ext . $self->xs_dlsyms_ext, "$ext.xs", $name, $parts[-1], {}, [], {}, [], $self->xs_dlsyms_extra . q!, 'FILE' => ! . neatvalue($ext), ); } return join "\n", @m; } else { return $self->xs_make_dlsyms( $attribs, $self->{BASEEXT} . $self->xs_dlsyms_ext, 'Makefile.PL', $self->{NAME}, $self->{DLBASE}, $attribs->{DL_FUNCS} || $self->{DL_FUNCS} || {}, $attribs->{FUNCLIST} || $self->{FUNCLIST} || [], $attribs->{IMPORTS} || $self->{IMPORTS} || {}, $attribs->{DL_VARS} || $self->{DL_VARS} || [], $self->xs_dlsyms_extra, ); } } =head3 xs_make_dlsyms $self->xs_make_dlsyms( \%attribs, # hashref from %attribs in caller "$self->{BASEEXT}.def", # output file for Makefile target 'Makefile.PL', # dependency $self->{NAME}, # shared object's "name" $self->{DLBASE}, # last ::-separated part of name $attribs{DL_FUNCS} || $self->{DL_FUNCS} || {}, # various params $attribs{FUNCLIST} || $self->{FUNCLIST} || [], $attribs{IMPORTS} || $self->{IMPORTS} || {}, $attribs{DL_VARS} || $self->{DL_VARS} || [], # optional extra param that will be added as param to Mksymlists ); Utility method that returns Makefile snippet to call C. =cut sub xs_make_dlsyms { my ($self, $attribs, $target, $dep, $name, $dlbase, $funcs, $funclist, $imports, $vars, $extra) = @_; my @m = ( "\n$target: $dep\n", q! $(PERLRUN) -MExtUtils::Mksymlists \\ -e "Mksymlists('NAME'=>\"!, $name, q!\", 'DLBASE' => '!,$dlbase, # The above two lines quoted differently to work around # a bug in the 4DOS/4NT command line interpreter. The visible # result of the bug was files named q('extension_name',) *with the # single quotes and the comma* in the extension build directories. q!', 'DL_FUNCS' => !,neatvalue($funcs), q!, 'FUNCLIST' => !,neatvalue($funclist), q!, 'IMPORTS' => !,neatvalue($imports), q!, 'DL_VARS' => !, neatvalue($vars) ); push @m, $extra if defined $extra; push @m, qq!);"\n!; join '', @m; } =head3 dynamic (o) Defines the dynamic target. =cut sub dynamic { # --- Dynamic Loading Sections --- my($self) = shift; ' dynamic :: $(FIRST_MAKEFILE) config $(INST_BOOT) $(INST_DYNAMIC) $(NOECHO) $(NOOP) '; } =head3 makemakerdflt_target my $make_frag = $mm->makemakerdflt_target Returns a make fragment with the makemakerdeflt_target specified. This target is the first target in the Makefile, is the default target and simply points off to 'all' just in case any make variant gets confused or something gets snuck in before the real 'all' target. =cut sub makemakerdflt_target { return <<'MAKE_FRAG'; makemakerdflt : all $(NOECHO) $(NOOP) MAKE_FRAG } =head3 manifypods_target my $manifypods_target = $self->manifypods_target; Generates the manifypods target. This target generates man pages from all POD files in MAN1PODS and MAN3PODS. =cut sub manifypods_target { my($self) = shift; my $man1pods = ''; my $man3pods = ''; my $dependencies = ''; # populate manXpods & dependencies: foreach my $name (sort keys %{$self->{MAN1PODS}}, sort keys %{$self->{MAN3PODS}}) { $dependencies .= " \\\n\t$name"; } my $manify = <{"MAN${num}PODS"}; my $p2m = sprintf <<'CMD', "\$(MAN${num}SECTION)", "$]" > 5.008 ? " -u" : ""; $(NOECHO) $(POD2MAN) --section=%s --perm_rw=$(PERM_RW)%s CMD push @man_cmds, $self->split_command($p2m, map {($_,$pods->{$_})} sort keys %$pods); } $manify .= "\t\$(NOECHO) \$(NOOP)\n" unless @man_cmds; $manify .= join '', map { "$_\n" } @man_cmds; return $manify; } { my $has_cpan_meta; sub _has_cpan_meta { return $has_cpan_meta if defined $has_cpan_meta; return $has_cpan_meta = !!eval { require CPAN::Meta; CPAN::Meta->VERSION(2.112150); 1; }; } } =head3 metafile_target my $target = $mm->metafile_target; Generate the metafile target. Writes the file META.yml (YAML encoded meta-data) and META.json (JSON encoded meta-data) about the module in the distdir. The format follows Module::Build's as closely as possible. =cut sub metafile_target { my $self = shift; return <<'MAKE_FRAG' if $self->{NO_META} or ! _has_cpan_meta(); metafile : $(NOECHO) $(NOOP) MAKE_FRAG my $metadata = $self->metafile_data( $self->{META_ADD} || {}, $self->{META_MERGE} || {}, ); my $meta = $self->_fix_metadata_before_conversion( $metadata ); my @write_metayml = $self->stashmeta( $meta->as_string({version => "1.4"}), 'META_new.yml' ); my @write_metajson = $self->stashmeta( $meta->as_string({version => "2.0"}), 'META_new.json' ); my $metayml = join("\n\t", @write_metayml); my $metajson = join("\n\t", @write_metajson); return sprintf <<'MAKE_FRAG', $metayml, $metajson; metafile : create_distdir $(NOECHO) $(ECHO) Generating META.yml %s -$(NOECHO) $(MV) META_new.yml $(DISTVNAME)/META.yml $(NOECHO) $(ECHO) Generating META.json %s -$(NOECHO) $(MV) META_new.json $(DISTVNAME)/META.json MAKE_FRAG } =begin private =head3 _fix_metadata_before_conversion $mm->_fix_metadata_before_conversion( \%metadata ); Fixes errors in the metadata before it's handed off to L for conversion. This hopefully results in something that can be used further on, no guarantee is made though. =end private =cut sub _fix_metadata_before_conversion { my ( $self, $metadata ) = @_; # we should never be called unless this already passed but # prefer to be defensive in case somebody else calls this return unless _has_cpan_meta; my $bad_version = $metadata->{version} && !CPAN::Meta::Validator->new->version( 'version', $metadata->{version} ); # just delete all invalid versions if( $bad_version ) { warn "Can't parse version '$metadata->{version}'\n"; $metadata->{version} = ''; } my $validator2 = CPAN::Meta::Validator->new( $metadata ); my @errors; push @errors, $validator2->errors if !$validator2->is_valid; my $validator14 = CPAN::Meta::Validator->new( { %$metadata, 'meta-spec' => { version => 1.4 }, } ); push @errors, $validator14->errors if !$validator14->is_valid; # fix non-camelcase custom resource keys (only other trick we know) for my $error ( @errors ) { my ( $key ) = ( $error =~ /Custom resource '(.*)' must be in CamelCase./ ); next if !$key; # first try to remove all non-alphabetic chars ( my $new_key = $key ) =~ s/[^_a-zA-Z]//g; # if that doesn't work, uppercase first one $new_key = ucfirst $new_key if !$validator14->custom_1( $new_key ); # copy to new key if that worked $metadata->{resources}{$new_key} = $metadata->{resources}{$key} if $validator14->custom_1( $new_key ); # and delete old one in any case delete $metadata->{resources}{$key}; } # paper over validation issues, but still complain, necessary because # there's no guarantee that the above will fix ALL errors my $meta = eval { CPAN::Meta->create( $metadata, { lazy_validation => 1 } ) }; warn $@ if $@ and $@ !~ /encountered CODE.*, but JSON can only represent references to arrays or hashes/; # use the original metadata straight if the conversion failed # or if it can't be stringified. if( !$meta || !eval { $meta->as_string( { version => $METASPEC_V } ) } || !eval { $meta->as_string } ) { $meta = bless $metadata, 'CPAN::Meta'; } my $now_license = $meta->as_struct({ version => 2 })->{license}; if ($self->{LICENSE} and $self->{LICENSE} ne 'unknown' and @{$now_license} == 1 and $now_license->[0] eq 'unknown' ) { warn "Invalid LICENSE value '$self->{LICENSE}' ignored\n"; } $meta; } =begin private =head3 _sort_pairs my @pairs = _sort_pairs($sort_sub, \%hash); Sorts the pairs of a hash based on keys ordered according to C<$sort_sub>. =end private =cut sub _sort_pairs { my $sort = shift; my $pairs = shift; return map { $_ => $pairs->{$_} } sort $sort keys %$pairs; } # Taken from Module::Build::Base sub _hash_merge { my ($self, $h, $k, $v) = @_; if (ref $h->{$k} eq 'ARRAY') { push @{$h->{$k}}, ref $v ? @$v : $v; } elsif (ref $h->{$k} eq 'HASH') { $self->_hash_merge($h->{$k}, $_, $v->{$_}) foreach keys %$v; } else { $h->{$k} = $v; } } =head3 metafile_data my $metadata_hashref = $mm->metafile_data(\%meta_add, \%meta_merge); Returns the data which MakeMaker turns into the META.yml file and the META.json file. It is always in version 2.0 of the format. Values of %meta_add will overwrite any existing metadata in those keys. %meta_merge will be merged with them. =cut sub metafile_data { my $self = shift; my($meta_add, $meta_merge) = @_; $meta_add ||= {}; $meta_merge ||= {}; my $version = _normalize_version($self->{VERSION}); my $release_status = ($version =~ /_/) ? 'unstable' : 'stable'; my %meta = ( # required abstract => $self->{ABSTRACT} || 'unknown', author => defined($self->{AUTHOR}) ? $self->{AUTHOR} : ['unknown'], dynamic_config => 1, generated_by => "ExtUtils::MakeMaker version $ExtUtils::MakeMaker::VERSION", license => [ $self->{LICENSE} || 'unknown' ], 'meta-spec' => { url => $METASPEC_URL, version => $METASPEC_V, }, name => $self->{DISTNAME}, release_status => $release_status, version => $version, # optional no_index => { directory => [qw(t inc)] }, ); $self->_add_requirements_to_meta(\%meta); if (!eval { require JSON::PP; require CPAN::Meta::Converter; CPAN::Meta::Converter->VERSION(2.141170) }) { return \%meta; } # needs to be based on the original version my $v1_add = _metaspec_version($meta_add) !~ /^2/; my ($add_v, $merge_v) = map _metaspec_version($_), $meta_add, $meta_merge; for my $frag ($meta_add, $meta_merge) { my $def_v = $frag == $meta_add ? $merge_v : $add_v; $frag = CPAN::Meta::Converter->new($frag, default_version => $def_v)->upgrade_fragment; } # if we upgraded a 1.x _ADD fragment, we gave it a prereqs key that # will override all prereqs, which is more than the user asked for; # instead, we'll go inside the prereqs and override all those while( my($key, $val) = each %$meta_add ) { if ($v1_add and $key eq 'prereqs') { $meta{$key}{$_} = $val->{$_} for keys %$val; } elsif ($key ne 'meta-spec') { $meta{$key} = $val; } } while( my($key, $val) = each %$meta_merge ) { next if $key eq 'meta-spec'; $self->_hash_merge(\%meta, $key, $val); } return \%meta; } =begin private =cut sub _add_requirements_to_meta { my ( $self, $meta ) = @_; # Check the original args so we can tell between the user setting it # to an empty hash and it just being initialized. $meta->{prereqs}{configure}{requires} = $self->{ARGS}{CONFIGURE_REQUIRES} ? $self->{CONFIGURE_REQUIRES} : { 'ExtUtils::MakeMaker' => 0, }; $meta->{prereqs}{build}{requires} = $self->{ARGS}{BUILD_REQUIRES} ? $self->{BUILD_REQUIRES} : { 'ExtUtils::MakeMaker' => 0, }; $meta->{prereqs}{test}{requires} = $self->{TEST_REQUIRES} if $self->{ARGS}{TEST_REQUIRES}; $meta->{prereqs}{runtime}{requires} = $self->{PREREQ_PM} if $self->{ARGS}{PREREQ_PM}; $meta->{prereqs}{runtime}{requires}{perl} = _normalize_version($self->{MIN_PERL_VERSION}) if $self->{MIN_PERL_VERSION}; } # spec version of given fragment - if not given, assume 1.4 sub _metaspec_version { my ( $meta ) = @_; return $meta->{'meta-spec'}->{version} if defined $meta->{'meta-spec'} and defined $meta->{'meta-spec'}->{version}; return '1.4'; } sub _add_requirements_to_meta_v1_4 { my ( $self, $meta ) = @_; # Check the original args so we can tell between the user setting it # to an empty hash and it just being initialized. if( $self->{ARGS}{CONFIGURE_REQUIRES} ) { $meta->{configure_requires} = $self->{CONFIGURE_REQUIRES}; } else { $meta->{configure_requires} = { 'ExtUtils::MakeMaker' => 0, }; } if( $self->{ARGS}{BUILD_REQUIRES} ) { $meta->{build_requires} = $self->{BUILD_REQUIRES}; } else { $meta->{build_requires} = { 'ExtUtils::MakeMaker' => 0, }; } if( $self->{ARGS}{TEST_REQUIRES} ) { $meta->{build_requires} = { %{ $meta->{build_requires} }, %{ $self->{TEST_REQUIRES} }, }; } $meta->{requires} = $self->{PREREQ_PM} if defined $self->{PREREQ_PM}; $meta->{requires}{perl} = _normalize_version($self->{MIN_PERL_VERSION}) if $self->{MIN_PERL_VERSION}; } # Adapted from Module::Build::Base sub _normalize_version { my ($version) = @_; $version = 0 unless defined $version; if ( ref $version eq 'version' ) { # version objects $version = $version->stringify; } elsif ( $version =~ /^[^v][^.]*\.[^.]+\./ ) { # no leading v, multiple dots # normalize string tuples without "v": "1.2.3" -> "v1.2.3" $version = "v$version"; } else { # leave alone } return $version; } =head3 _dump_hash $yaml = _dump_hash(\%options, %hash); Implements a fake YAML dumper for a hash given as a list of pairs. No quoting/escaping is done. Keys are supposed to be strings. Values are undef, strings, hash refs or array refs of strings. Supported options are: delta => STR - indentation delta use_header => BOOL - whether to include a YAML header indent => STR - a string of spaces default: '' max_key_length => INT - maximum key length used to align keys and values of the same hash default: 20 key_sort => CODE - a sort sub It may be undef, which means no sorting by keys default: sub { lc $a cmp lc $b } customs => HASH - special options for certain keys (whose values are hashes themselves) may contain: max_key_length, key_sort, customs =end private =cut sub _dump_hash { croak "first argument should be a hash ref" unless ref $_[0] eq 'HASH'; my $options = shift; my %hash = @_; # Use a list to preserve order. my @pairs; my $k_sort = exists $options->{key_sort} ? $options->{key_sort} : sub { lc $a cmp lc $b }; if ($k_sort) { croak "'key_sort' should be a coderef" unless ref $k_sort eq 'CODE'; @pairs = _sort_pairs($k_sort, \%hash); } else { # list of pairs, no sorting @pairs = @_; } my $yaml = $options->{use_header} ? "--- #YAML:1.0\n" : ''; my $indent = $options->{indent} || ''; my $k_length = min( ($options->{max_key_length} || 20), max(map { length($_) + 1 } grep { !ref $hash{$_} } keys %hash) ); my $customs = $options->{customs} || {}; # printf format for key my $k_format = "%-${k_length}s"; while( @pairs ) { my($key, $val) = splice @pairs, 0, 2; $val = '~' unless defined $val; if(ref $val eq 'HASH') { if ( keys %$val ) { my %k_options = ( # options for recursive call delta => $options->{delta}, use_header => 0, indent => $indent . $options->{delta}, ); if (exists $customs->{$key}) { my %k_custom = %{$customs->{$key}}; foreach my $k (qw(key_sort max_key_length customs)) { $k_options{$k} = $k_custom{$k} if exists $k_custom{$k}; } } $yaml .= $indent . "$key:\n" . _dump_hash(\%k_options, %$val); } else { $yaml .= $indent . "$key: {}\n"; } } elsif (ref $val eq 'ARRAY') { if( @$val ) { $yaml .= $indent . "$key:\n"; for (@$val) { croak "only nested arrays of non-refs are supported" if ref $_; $yaml .= $indent . $options->{delta} . "- $_\n"; } } else { $yaml .= $indent . "$key: []\n"; } } elsif( ref $val and !blessed($val) ) { croak "only nested hashes, arrays and objects are supported"; } else { # if it's an object, just stringify it $yaml .= $indent . sprintf "$k_format %s\n", "$key:", $val; } }; return $yaml; } sub blessed { return eval { $_[0]->isa("UNIVERSAL"); }; } sub max { return (sort { $b <=> $a } @_)[0]; } sub min { return (sort { $a <=> $b } @_)[0]; } =head3 metafile_file my $meta_yml = $mm->metafile_file(@metadata_pairs); Turns the @metadata_pairs into YAML. This method does not implement a complete YAML dumper, being limited to dump a hash with values which are strings, undef's or nested hashes and arrays of strings. No quoting/escaping is done. =cut sub metafile_file { my $self = shift; my %dump_options = ( use_header => 1, delta => ' ' x 4, key_sort => undef, ); return _dump_hash(\%dump_options, @_); } =head3 distmeta_target my $make_frag = $mm->distmeta_target; Generates the distmeta target to add META.yml and META.json to the MANIFEST in the distdir. =cut sub distmeta_target { my $self = shift; my @add_meta = ( $self->oneliner(<<'CODE', ['-MExtUtils::Manifest=maniadd']), exit unless -e q{META.yml}; eval { maniadd({q{META.yml} => q{Module YAML meta-data (added by MakeMaker)}}) } or die "Could not add META.yml to MANIFEST: ${'@'}" CODE $self->oneliner(<<'CODE', ['-MExtUtils::Manifest=maniadd']) exit unless -f q{META.json}; eval { maniadd({q{META.json} => q{Module JSON meta-data (added by MakeMaker)}}) } or die "Could not add META.json to MANIFEST: ${'@'}" CODE ); my @add_meta_to_distdir = map { $self->cd('$(DISTVNAME)', $_) } @add_meta; return sprintf <<'MAKE', @add_meta_to_distdir; distmeta : create_distdir metafile $(NOECHO) %s $(NOECHO) %s MAKE } =head3 mymeta my $mymeta = $mm->mymeta; Generate MYMETA information as a hash either from an existing CPAN Meta file (META.json or META.yml) or from internal data. =cut sub mymeta { my $self = shift; my $file = shift || ''; # for testing my $mymeta = $self->_mymeta_from_meta($file); my $v2 = 1; unless ( $mymeta ) { $mymeta = $self->metafile_data( $self->{META_ADD} || {}, $self->{META_MERGE} || {}, ); $v2 = 0; } # Overwrite the non-configure dependency hashes $self->_add_requirements_to_meta($mymeta); $mymeta->{dynamic_config} = 0; return $mymeta; } sub _mymeta_from_meta { my $self = shift; my $metafile = shift || ''; # for testing return unless _has_cpan_meta(); my $meta; for my $file ( $metafile, "META.json", "META.yml" ) { next unless -e $file; eval { $meta = CPAN::Meta->load_file($file)->as_struct( { version => 2 } ); }; last if $meta; } return unless $meta; # META.yml before 6.25_01 cannot be trusted. META.yml lived in the source directory. # There was a good chance the author accidentally uploaded a stale META.yml if they # rolled their own tarball rather than using "make dist". if ($meta->{generated_by} && $meta->{generated_by} =~ /ExtUtils::MakeMaker version ([\d\._]+)/) { my $eummv = do { no warnings; $1+0; }; if ($eummv < 6.2501) { return; } } return $meta; } =head3 write_mymeta $self->write_mymeta( $mymeta ); Write MYMETA information to MYMETA.json and MYMETA.yml. =cut sub write_mymeta { my $self = shift; my $mymeta = shift; return unless _has_cpan_meta(); my $meta_obj = $self->_fix_metadata_before_conversion( $mymeta ); $meta_obj->save( 'MYMETA.json', { version => "2.0" } ); $meta_obj->save( 'MYMETA.yml', { version => "1.4" } ); return 1; } =head3 realclean (o) Defines the realclean target. =cut sub realclean { my($self, %attribs) = @_; my @dirs = qw($(DISTVNAME)); my @files = qw($(FIRST_MAKEFILE) $(MAKEFILE_OLD)); # Special exception for the perl core where INST_* is not in blib. # This cleans up the files built from the ext/ directory (all XS). if( $self->{PERL_CORE} ) { push @dirs, qw($(INST_AUTODIR) $(INST_ARCHAUTODIR)); push @files, values %{$self->{PM}}; } if( $self->has_link_code ){ push @files, qw($(OBJECT)); } if( $attribs{FILES} ) { if( ref $attribs{FILES} ) { push @dirs, @{ $attribs{FILES} }; } else { push @dirs, split /\s+/, $attribs{FILES}; } } # Occasionally files are repeated several times from different sources { my(%f) = map { ($_ => 1) } @files; @files = sort keys %f; } { my(%d) = map { ($_ => 1) } @dirs; @dirs = sort keys %d; } my $rm_cmd = join "\n\t", map { "$_" } $self->split_command('- $(RM_F)', @files); my $rmf_cmd = join "\n\t", map { "$_" } $self->split_command('- $(RM_RF)', @dirs); my $m = sprintf <<'MAKE', $rm_cmd, $rmf_cmd; # Delete temporary files (via clean) and also delete dist files realclean purge :: realclean_subdirs %s %s MAKE $m .= "\t$attribs{POSTOP}\n" if $attribs{POSTOP}; return $m; } =head3 realclean_subdirs_target my $make_frag = $MM->realclean_subdirs_target; Returns the realclean_subdirs target. This is used by the realclean target to call realclean on any subdirectories which contain Makefiles. =cut sub realclean_subdirs_target { my $self = shift; my @m = <<'EOF'; # so clean is forced to complete before realclean_subdirs runs realclean_subdirs : clean EOF return join '', @m, "\t\$(NOECHO) \$(NOOP)\n" unless @{$self->{DIR}}; foreach my $dir (@{$self->{DIR}}) { foreach my $makefile ('$(MAKEFILE_OLD)', '$(FIRST_MAKEFILE)' ) { my $subrclean .= $self->oneliner(_sprintf562 <<'CODE', $dir, $makefile); chdir '%1$s'; system '$(MAKE) $(USEMAKEFILE) %2$s realclean' if -f '%2$s'; CODE push @m, "\t- $subrclean\n"; } } return join '', @m; } =head3 signature_target my $target = $mm->signature_target; Generate the signature target. Writes the file SIGNATURE with "cpansign -s". =cut sub signature_target { my $self = shift; return <<'MAKE_FRAG'; signature : cpansign -s MAKE_FRAG } =head3 distsignature_target my $make_frag = $mm->distsignature_target; Generates the distsignature target to add SIGNATURE to the MANIFEST in the distdir. =cut sub distsignature_target { my $self = shift; my $add_sign = $self->oneliner(<<'CODE', ['-MExtUtils::Manifest=maniadd']); eval { maniadd({q{SIGNATURE} => q{Public-key signature (added by MakeMaker)}}) } or die "Could not add SIGNATURE to MANIFEST: ${'@'}" CODE my $sign_dist = $self->cd('$(DISTVNAME)' => 'cpansign -s'); # cpansign -s complains if SIGNATURE is in the MANIFEST yet does not # exist my $touch_sig = $self->cd('$(DISTVNAME)' => '$(TOUCH) SIGNATURE'); my $add_sign_to_dist = $self->cd('$(DISTVNAME)' => $add_sign ); return sprintf <<'MAKE', $add_sign_to_dist, $touch_sig, $sign_dist distsignature : distmeta $(NOECHO) %s $(NOECHO) %s %s MAKE } =head3 special_targets my $make_frag = $mm->special_targets Returns a make fragment containing any targets which have special meaning to make. For example, .SUFFIXES and .PHONY. =cut sub special_targets { my $make_frag = <<'MAKE_FRAG'; .SUFFIXES : .xs .c .C .cpp .i .s .cxx .cc $(OBJ_EXT) .PHONY: all config static dynamic test linkext manifest blibdirs clean realclean disttest distdir pure_all subdirs clean_subdirs makemakerdflt manifypods realclean_subdirs subdirs_dynamic subdirs_pure_nolink subdirs_static subdirs-test_dynamic subdirs-test_static test_dynamic test_static MAKE_FRAG $make_frag .= <<'MAKE_FRAG' if $ENV{CLEARCASE_ROOT}; .NO_CONFIG_REC: Makefile MAKE_FRAG return $make_frag; } =head2 Init methods Methods which help initialize the MakeMaker object and macros. =head3 init_ABSTRACT $mm->init_ABSTRACT =cut sub init_ABSTRACT { my $self = shift; if( $self->{ABSTRACT_FROM} and $self->{ABSTRACT} ) { warn "Both ABSTRACT_FROM and ABSTRACT are set. ". "Ignoring ABSTRACT_FROM.\n"; return; } if ($self->{ABSTRACT_FROM}){ $self->{ABSTRACT} = $self->parse_abstract($self->{ABSTRACT_FROM}) or carp "WARNING: Setting ABSTRACT via file ". "'$self->{ABSTRACT_FROM}' failed\n"; } if ($self->{ABSTRACT} && $self->{ABSTRACT} =~ m![[:cntrl:]]+!) { warn "WARNING: ABSTRACT contains control character(s),". " they will be removed\n"; $self->{ABSTRACT} =~ s![[:cntrl:]]+!!g; return; } } =head3 init_INST $mm->init_INST; Called by init_main. Sets up all INST_* variables except those related to XS code. Those are handled in init_xs. =cut sub init_INST { my($self) = shift; $self->{INST_ARCHLIB} ||= $self->catdir($Curdir,"blib","arch"); $self->{INST_BIN} ||= $self->catdir($Curdir,'blib','bin'); # INST_LIB typically pre-set if building an extension after # perl has been built and installed. Setting INST_LIB allows # you to build directly into, say $Config{privlibexp}. unless ($self->{INST_LIB}){ if ($self->{PERL_CORE}) { $self->{INST_LIB} = $self->{INST_ARCHLIB} = $self->{PERL_LIB}; } else { $self->{INST_LIB} = $self->catdir($Curdir,"blib","lib"); } } my @parentdir = split(/::/, $self->{PARENT_NAME}); $self->{INST_LIBDIR} = $self->catdir('$(INST_LIB)', @parentdir); $self->{INST_ARCHLIBDIR} = $self->catdir('$(INST_ARCHLIB)', @parentdir); $self->{INST_AUTODIR} = $self->catdir('$(INST_LIB)', 'auto', '$(FULLEXT)'); $self->{INST_ARCHAUTODIR} = $self->catdir('$(INST_ARCHLIB)', 'auto', '$(FULLEXT)'); $self->{INST_SCRIPT} ||= $self->catdir($Curdir,'blib','script'); $self->{INST_MAN1DIR} ||= $self->catdir($Curdir,'blib','man1'); $self->{INST_MAN3DIR} ||= $self->catdir($Curdir,'blib','man3'); return 1; } =head3 init_INSTALL $mm->init_INSTALL; Called by init_main. Sets up all INSTALL_* variables (except INSTALLDIRS) and *PREFIX. =cut sub init_INSTALL { my($self) = shift; if( $self->{ARGS}{INSTALL_BASE} and $self->{ARGS}{PREFIX} ) { die "Only one of PREFIX or INSTALL_BASE can be given. Not both.\n"; } if( $self->{ARGS}{INSTALL_BASE} ) { $self->init_INSTALL_from_INSTALL_BASE; } else { $self->init_INSTALL_from_PREFIX; } } =head3 init_INSTALL_from_PREFIX $mm->init_INSTALL_from_PREFIX; =cut sub init_INSTALL_from_PREFIX { my $self = shift; $self->init_lib2arch; # There are often no Config.pm defaults for these new man variables so # we fall back to the old behavior which is to use installman*dir foreach my $num (1, 3) { my $k = 'installsiteman'.$num.'dir'; $self->{uc $k} ||= uc "\$(installman${num}dir)" unless $Config{$k}; } foreach my $num (1, 3) { my $k = 'installvendorman'.$num.'dir'; unless( $Config{$k} ) { $self->{uc $k} ||= $Config{usevendorprefix} ? uc "\$(installman${num}dir)" : ''; } } $self->{INSTALLSITEBIN} ||= '$(INSTALLBIN)' unless $Config{installsitebin}; $self->{INSTALLSITESCRIPT} ||= '$(INSTALLSCRIPT)' unless $Config{installsitescript}; unless( $Config{installvendorbin} ) { $self->{INSTALLVENDORBIN} ||= $Config{usevendorprefix} ? $Config{installbin} : ''; } unless( $Config{installvendorscript} ) { $self->{INSTALLVENDORSCRIPT} ||= $Config{usevendorprefix} ? $Config{installscript} : ''; } my $iprefix = $Config{installprefixexp} || $Config{installprefix} || $Config{prefixexp} || $Config{prefix} || ''; my $vprefix = $Config{usevendorprefix} ? $Config{vendorprefixexp} : ''; my $sprefix = $Config{siteprefixexp} || ''; # 5.005_03 doesn't have a siteprefix. $sprefix = $iprefix unless $sprefix; $self->{PREFIX} ||= ''; if( $self->{PREFIX} ) { @{$self}{qw(PERLPREFIX SITEPREFIX VENDORPREFIX)} = ('$(PREFIX)') x 3; } else { $self->{PERLPREFIX} ||= $iprefix; $self->{SITEPREFIX} ||= $sprefix; $self->{VENDORPREFIX} ||= $vprefix; # Lots of MM extension authors like to use $(PREFIX) so we # put something sensible in there no matter what. $self->{PREFIX} = '$('.uc $self->{INSTALLDIRS}.'PREFIX)'; } my $arch = $Config{archname}; my $version = $Config{version}; # default style my $libstyle = $Config{installstyle} || 'lib/perl5'; my $manstyle = ''; if( $self->{LIBSTYLE} ) { $libstyle = $self->{LIBSTYLE}; $manstyle = $self->{LIBSTYLE} eq 'lib/perl5' ? 'lib/perl5' : ''; } # Some systems, like VOS, set installman*dir to '' if they can't # read man pages. for my $num (1, 3) { $self->{'INSTALLMAN'.$num.'DIR'} ||= 'none' unless $Config{'installman'.$num.'dir'}; } my %bin_layouts = ( bin => { s => $iprefix, t => 'perl', d => 'bin' }, vendorbin => { s => $vprefix, t => 'vendor', d => 'bin' }, sitebin => { s => $sprefix, t => 'site', d => 'bin' }, script => { s => $iprefix, t => 'perl', d => 'bin' }, vendorscript=> { s => $vprefix, t => 'vendor', d => 'bin' }, sitescript => { s => $sprefix, t => 'site', d => 'bin' }, ); my %man_layouts = ( man1dir => { s => $iprefix, t => 'perl', d => 'man/man1', style => $manstyle, }, siteman1dir => { s => $sprefix, t => 'site', d => 'man/man1', style => $manstyle, }, vendorman1dir => { s => $vprefix, t => 'vendor', d => 'man/man1', style => $manstyle, }, man3dir => { s => $iprefix, t => 'perl', d => 'man/man3', style => $manstyle, }, siteman3dir => { s => $sprefix, t => 'site', d => 'man/man3', style => $manstyle, }, vendorman3dir => { s => $vprefix, t => 'vendor', d => 'man/man3', style => $manstyle, }, ); my %lib_layouts = ( privlib => { s => $iprefix, t => 'perl', d => '', style => $libstyle, }, vendorlib => { s => $vprefix, t => 'vendor', d => '', style => $libstyle, }, sitelib => { s => $sprefix, t => 'site', d => 'site_perl', style => $libstyle, }, archlib => { s => $iprefix, t => 'perl', d => "$version/$arch", style => $libstyle }, vendorarch => { s => $vprefix, t => 'vendor', d => "$version/$arch", style => $libstyle }, sitearch => { s => $sprefix, t => 'site', d => "site_perl/$version/$arch", style => $libstyle }, ); # Special case for LIB. if( $self->{LIB} ) { foreach my $var (keys %lib_layouts) { my $Installvar = uc "install$var"; if( $var =~ /arch/ ) { $self->{$Installvar} ||= $self->catdir($self->{LIB}, $Config{archname}); } else { $self->{$Installvar} ||= $self->{LIB}; } } } my %type2prefix = ( perl => 'PERLPREFIX', site => 'SITEPREFIX', vendor => 'VENDORPREFIX' ); my %layouts = (%bin_layouts, %man_layouts, %lib_layouts); while( my($var, $layout) = each(%layouts) ) { my($s, $t, $d, $style) = @{$layout}{qw(s t d style)}; my $r = '$('.$type2prefix{$t}.')'; warn "Prefixing $var\n" if $Verbose >= 2; my $installvar = "install$var"; my $Installvar = uc $installvar; next if $self->{$Installvar}; $d = "$style/$d" if $style; $self->prefixify($installvar, $s, $r, $d); warn " $Installvar == $self->{$Installvar}\n" if $Verbose >= 2; } # Generate these if they weren't figured out. $self->{VENDORARCHEXP} ||= $self->{INSTALLVENDORARCH}; $self->{VENDORLIBEXP} ||= $self->{INSTALLVENDORLIB}; return 1; } =head3 init_from_INSTALL_BASE $mm->init_from_INSTALL_BASE =cut my %map = ( lib => [qw(lib perl5)], arch => [('lib', 'perl5', $Config{archname})], bin => [qw(bin)], man1dir => [qw(man man1)], man3dir => [qw(man man3)] ); $map{script} = $map{bin}; sub init_INSTALL_from_INSTALL_BASE { my $self = shift; @{$self}{qw(PREFIX VENDORPREFIX SITEPREFIX PERLPREFIX)} = '$(INSTALL_BASE)'; my %install; foreach my $thing (keys %map) { foreach my $dir (('', 'SITE', 'VENDOR')) { my $uc_thing = uc $thing; my $key = "INSTALL".$dir.$uc_thing; $install{$key} ||= ($thing =~ /^man.dir$/ and not $Config{lc $key}) ? 'none' : $self->catdir('$(INSTALL_BASE)', @{$map{$thing}}); } } # Adjust for variable quirks. $install{INSTALLARCHLIB} ||= delete $install{INSTALLARCH}; $install{INSTALLPRIVLIB} ||= delete $install{INSTALLLIB}; foreach my $key (keys %install) { $self->{$key} ||= $install{$key}; } return 1; } =head3 init_VERSION I $mm->init_VERSION Initialize macros representing versions of MakeMaker and other tools MAKEMAKER: path to the MakeMaker module. MM_VERSION: ExtUtils::MakeMaker Version MM_REVISION: ExtUtils::MakeMaker version control revision (for backwards compat) VERSION: version of your module VERSION_MACRO: which macro represents the version (usually 'VERSION') VERSION_SYM: like version but safe for use as an RCS revision number DEFINE_VERSION: -D line to set the module version when compiling XS_VERSION: version in your .xs file. Defaults to $(VERSION) XS_VERSION_MACRO: which macro represents the XS version. XS_DEFINE_VERSION: -D line to set the xs version when compiling. Called by init_main. =cut sub init_VERSION { my($self) = shift; $self->{MAKEMAKER} = $ExtUtils::MakeMaker::Filename; $self->{MM_VERSION} = $ExtUtils::MakeMaker::VERSION; $self->{MM_REVISION}= $ExtUtils::MakeMaker::Revision; $self->{VERSION_FROM} ||= ''; if ($self->{VERSION_FROM}){ $self->{VERSION} = $self->parse_version($self->{VERSION_FROM}); if( $self->{VERSION} eq 'undef' ) { carp("WARNING: Setting VERSION via file ". "'$self->{VERSION_FROM}' failed\n"); } } if (defined $self->{VERSION}) { if ( $self->{VERSION} !~ /^\s*v?[\d_\.]+\s*$/ ) { require version; my $normal = eval { version->new( $self->{VERSION} ) }; $self->{VERSION} = $normal if defined $normal; } $self->{VERSION} =~ s/^\s+//; $self->{VERSION} =~ s/\s+$//; } else { $self->{VERSION} = ''; } $self->{VERSION_MACRO} = 'VERSION'; ($self->{VERSION_SYM} = $self->{VERSION}) =~ s/\W/_/g; $self->{DEFINE_VERSION} = '-D$(VERSION_MACRO)=\"$(VERSION)\"'; # Graham Barr and Paul Marquess had some ideas how to ensure # version compatibility between the *.pm file and the # corresponding *.xs file. The bottom line was, that we need an # XS_VERSION macro that defaults to VERSION: $self->{XS_VERSION} ||= $self->{VERSION}; $self->{XS_VERSION_MACRO} = 'XS_VERSION'; $self->{XS_DEFINE_VERSION} = '-D$(XS_VERSION_MACRO)=\"$(XS_VERSION)\"'; } =head3 init_tools $MM->init_tools(); Initializes the simple macro definitions used by tools_other() and places them in the $MM object. These use conservative cross platform versions and should be overridden with platform specific versions for performance. Defines at least these macros. Macro Description NOOP Do nothing NOECHO Tell make not to display the command itself SHELL Program used to run shell commands ECHO Print text adding a newline on the end RM_F Remove a file RM_RF Remove a directory TOUCH Update a file's timestamp TEST_F Test for a file's existence TEST_S Test the size of a file CP Copy a file CP_NONEMPTY Copy a file if it is not empty MV Move a file CHMOD Change permissions on a file FALSE Exit with non-zero TRUE Exit with zero UMASK_NULL Nullify umask DEV_NULL Suppress all command output =cut sub init_tools { my $self = shift; $self->{ECHO} ||= $self->oneliner('binmode STDOUT, qq{:raw}; print qq{@ARGV}', ['-l']); $self->{ECHO_N} ||= $self->oneliner('print qq{@ARGV}'); $self->{TOUCH} ||= $self->oneliner('touch', ["-MExtUtils::Command"]); $self->{CHMOD} ||= $self->oneliner('chmod', ["-MExtUtils::Command"]); $self->{RM_F} ||= $self->oneliner('rm_f', ["-MExtUtils::Command"]); $self->{RM_RF} ||= $self->oneliner('rm_rf', ["-MExtUtils::Command"]); $self->{TEST_F} ||= $self->oneliner('test_f', ["-MExtUtils::Command"]); $self->{TEST_S} ||= $self->oneliner('test_s', ["-MExtUtils::Command::MM"]); $self->{CP_NONEMPTY} ||= $self->oneliner('cp_nonempty', ["-MExtUtils::Command::MM"]); $self->{FALSE} ||= $self->oneliner('exit 1'); $self->{TRUE} ||= $self->oneliner('exit 0'); $self->{MKPATH} ||= $self->oneliner('mkpath', ["-MExtUtils::Command"]); $self->{CP} ||= $self->oneliner('cp', ["-MExtUtils::Command"]); $self->{MV} ||= $self->oneliner('mv', ["-MExtUtils::Command"]); $self->{MOD_INSTALL} ||= $self->oneliner(<<'CODE', ['-MExtUtils::Install']); install([ from_to => {@ARGV}, verbose => '$(VERBINST)', uninstall_shadows => '$(UNINST)', dir_mode => '$(PERM_DIR)' ]); CODE $self->{DOC_INSTALL} ||= $self->oneliner('perllocal_install', ["-MExtUtils::Command::MM"]); $self->{UNINSTALL} ||= $self->oneliner('uninstall', ["-MExtUtils::Command::MM"]); $self->{WARN_IF_OLD_PACKLIST} ||= $self->oneliner('warn_if_old_packlist', ["-MExtUtils::Command::MM"]); $self->{FIXIN} ||= $self->oneliner('MY->fixin(shift)', ["-MExtUtils::MY"]); $self->{EQUALIZE_TIMESTAMP} ||= $self->oneliner('eqtime', ["-MExtUtils::Command"]); $self->{UNINST} ||= 0; $self->{VERBINST} ||= 0; $self->{SHELL} ||= $Config{sh}; # UMASK_NULL is not used by MakeMaker but some CPAN modules # make use of it. $self->{UMASK_NULL} ||= "umask 0"; # Not the greatest default, but its something. $self->{DEV_NULL} ||= "> /dev/null 2>&1"; $self->{NOOP} ||= '$(TRUE)'; $self->{NOECHO} = '@' unless defined $self->{NOECHO}; $self->{FIRST_MAKEFILE} ||= $self->{MAKEFILE} || 'Makefile'; $self->{MAKEFILE} ||= $self->{FIRST_MAKEFILE}; $self->{MAKEFILE_OLD} ||= $self->{MAKEFILE}.'.old'; $self->{MAKE_APERL_FILE} ||= $self->{MAKEFILE}.'.aperl'; # Not everybody uses -f to indicate "use this Makefile instead" $self->{USEMAKEFILE} ||= '-f'; # Some makes require a wrapper around macros passed in on the command # line. $self->{MACROSTART} ||= ''; $self->{MACROEND} ||= ''; return; } =head3 init_others $MM->init_others(); Initializes the macro definitions having to do with compiling and linking used by tools_other() and places them in the $MM object. If there is no description, its the same as the parameter to WriteMakefile() documented in L. =cut sub init_others { my $self = shift; $self->{LD_RUN_PATH} = ""; $self->{LIBS} = $self->_fix_libs($self->{LIBS}); # Compute EXTRALIBS, BSLOADLIBS and LDLOADLIBS from $self->{LIBS} foreach my $libs ( @{$self->{LIBS}} ){ $libs =~ s/^\s*(.*\S)\s*$/$1/; # remove leading and trailing whitespace my(@libs) = $self->extliblist($libs); if ($libs[0] or $libs[1] or $libs[2]){ # LD_RUN_PATH now computed by ExtUtils::Liblist ($self->{EXTRALIBS}, $self->{BSLOADLIBS}, $self->{LDLOADLIBS}, $self->{LD_RUN_PATH}) = @libs; last; } } if ( $self->{OBJECT} ) { $self->{OBJECT} = join(" ", @{$self->{OBJECT}}) if ref $self->{OBJECT}; $self->{OBJECT} =~ s!\.o(bj)?\b!\$(OBJ_EXT)!g; } elsif ( ($self->{MAGICXS} || $self->{XSMULTI}) && @{$self->{O_FILES}||[]} ) { $self->{OBJECT} = join(" ", @{$self->{O_FILES}}); $self->{OBJECT} =~ s!\.o(bj)?\b!\$(OBJ_EXT)!g; } else { # init_dirscan should have found out, if we have C files $self->{OBJECT} = ""; $self->{OBJECT} = '$(BASEEXT)$(OBJ_EXT)' if @{$self->{C}||[]}; } $self->{OBJECT} =~ s/\n+/ \\\n\t/g; $self->{BOOTDEP} = (-f "$self->{BASEEXT}_BS") ? "$self->{BASEEXT}_BS" : ""; $self->{PERLMAINCC} ||= '$(CC)'; $self->{LDFROM} = '$(OBJECT)' unless $self->{LDFROM}; # Sanity check: don't define LINKTYPE = dynamic if we're skipping # the 'dynamic' section of MM. We don't have this problem with # 'static', since we either must use it (%Config says we can't # use dynamic loading) or the caller asked for it explicitly. if (!$self->{LINKTYPE}) { $self->{LINKTYPE} = $self->{SKIPHASH}{'dynamic'} ? 'static' : ($Config{usedl} ? 'dynamic' : 'static'); } return; } # Lets look at $self->{LIBS} carefully: It may be an anon array, a string or # undefined. In any case we turn it into an anon array sub _fix_libs { my($self, $libs) = @_; return !defined $libs ? [''] : !ref $libs ? [$libs] : !defined $libs->[0] ? [''] : $libs ; } =head3 tools_other my $make_frag = $MM->tools_other; Returns a make fragment containing definitions for the macros init_others() initializes. =cut sub tools_other { my($self) = shift; my @m; # We set PM_FILTER as late as possible so it can see all the earlier # on macro-order sensitive makes such as nmake. for my $tool (qw{ SHELL CHMOD CP MV NOOP NOECHO RM_F RM_RF TEST_F TOUCH UMASK_NULL DEV_NULL MKPATH EQUALIZE_TIMESTAMP FALSE TRUE ECHO ECHO_N UNINST VERBINST MOD_INSTALL DOC_INSTALL UNINSTALL WARN_IF_OLD_PACKLIST MACROSTART MACROEND USEMAKEFILE PM_FILTER FIXIN CP_NONEMPTY } ) { next unless defined $self->{$tool}; push @m, "$tool = $self->{$tool}\n"; } return join "", @m; } =head3 init_DIRFILESEP I $MM->init_DIRFILESEP; my $dirfilesep = $MM->{DIRFILESEP}; Initializes the DIRFILESEP macro which is the separator between the directory and filename in a filepath. ie. / on Unix, \ on Win32 and nothing on VMS. For example: # instead of $(INST_ARCHAUTODIR)/extralibs.ld $(INST_ARCHAUTODIR)$(DIRFILESEP)extralibs.ld Something of a hack but it prevents a lot of code duplication between MM_* variants. Do not use this as a separator between directories. Some operating systems use different separators between subdirectories as between directories and filenames (for example: VOLUME:[dir1.dir2]file on VMS). =head3 init_linker I $mm->init_linker; Initialize macros which have to do with linking. PERL_ARCHIVE: path to libperl.a equivalent to be linked to dynamic extensions. PERL_ARCHIVE_AFTER: path to a library which should be put on the linker command line I the external libraries to be linked to dynamic extensions. This may be needed if the linker is one-pass, and Perl includes some overrides for C RTL functions, such as malloc(). EXPORT_LIST: name of a file that is passed to linker to define symbols to be exported. Some OSes do not need these in which case leave it blank. =head3 init_platform $mm->init_platform Initialize any macros which are for platform specific use only. A typical one is the version number of your OS specific module. (ie. MM_Unix_VERSION or MM_VMS_VERSION). =cut sub init_platform { return ''; } =head3 init_MAKE $mm->init_MAKE Initialize MAKE from either a MAKE environment variable or $Config{make}. =cut sub init_MAKE { my $self = shift; $self->{MAKE} ||= $ENV{MAKE} || $Config{make}; } =head2 Tools A grab bag of methods to generate specific macros and commands. =head3 manifypods Defines targets and routines to translate the pods into manpages and put them into the INST_* directories. =cut sub manifypods { my $self = shift; my $POD2MAN_macro = $self->POD2MAN_macro(); my $manifypods_target = $self->manifypods_target(); return <POD2MAN_macro Returns a definition for the POD2MAN macro. This is a program which emulates the pod2man utility. You can add more switches to the command by simply appending them on the macro. Typical usage: $(POD2MAN) --section=3 --perm_rw=$(PERM_RW) podfile1 man_page1 ... =cut sub POD2MAN_macro { my $self = shift; # Need the trailing '--' so perl stops gobbling arguments and - happens # to be an alternative end of line separator on VMS so we quote it return <<'END_OF_DEF'; POD2MAN_EXE = $(PERLRUN) "-MExtUtils::Command::MM" -e pod2man "--" POD2MAN = $(POD2MAN_EXE) END_OF_DEF } =head3 test_via_harness my $command = $mm->test_via_harness($perl, $tests); Returns a $command line which runs the given set of $tests with Test::Harness and the given $perl. Used on the t/*.t files. =cut sub test_via_harness { my($self, $perl, $tests) = @_; return qq{\t$perl "-MExtUtils::Command::MM" "-MTest::Harness" }. qq{"-e" "undef *Test::Harness::Switches; test_harness(\$(TEST_VERBOSE), '\$(INST_LIB)', '\$(INST_ARCHLIB)')" $tests\n}; } =head3 test_via_script my $command = $mm->test_via_script($perl, $script); Returns a $command line which just runs a single test without Test::Harness. No checks are done on the results, they're just printed. Used for test.pl, since they don't always follow Test::Harness formatting. =cut sub test_via_script { my($self, $perl, $script) = @_; return qq{\t$perl "-I\$(INST_LIB)" "-I\$(INST_ARCHLIB)" $script\n}; } =head3 tool_autosplit Defines a simple perl call that runs autosplit. May be deprecated by pm_to_blib soon. =cut sub tool_autosplit { my($self, %attribs) = @_; my $maxlen = $attribs{MAXLEN} ? '$$AutoSplit::Maxlen=$attribs{MAXLEN};' : ''; my $asplit = $self->oneliner(sprintf <<'PERL_CODE', $maxlen); use AutoSplit; %s autosplit($$ARGV[0], $$ARGV[1], 0, 1, 1) PERL_CODE return sprintf <<'MAKE_FRAG', $asplit; # Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto AUTOSPLITFILE = %s MAKE_FRAG } =head3 arch_check my $arch_ok = $mm->arch_check( $INC{"Config.pm"}, File::Spec->catfile($Config{archlibexp}, "Config.pm") ); A sanity check that what Perl thinks the architecture is and what Config thinks the architecture is are the same. If they're not it will return false and show a diagnostic message. When building Perl it will always return true, as nothing is installed yet. The interface is a bit odd because this is the result of a quick refactoring. Don't rely on it. =cut sub arch_check { my $self = shift; my($pconfig, $cconfig) = @_; return 1 if $self->{PERL_SRC}; my($pvol, $pthinks) = $self->splitpath($pconfig); my($cvol, $cthinks) = $self->splitpath($cconfig); $pthinks = $self->canonpath($pthinks); $cthinks = $self->canonpath($cthinks); my $ret = 1; if ($pthinks ne $cthinks) { print "Have $pthinks\n"; print "Want $cthinks\n"; $ret = 0; my $arch = (grep length, $self->splitdir($pthinks))[-1]; print <{UNINSTALLED_PERL}; Your perl and your Config.pm seem to have different ideas about the architecture they are running on. Perl thinks: [$arch] Config says: [$Config{archname}] This may or may not cause problems. Please check your installation of perl if you have problems building this extension. END } return $ret; } =head2 File::Spec wrappers ExtUtils::MM_Any is a subclass of L. The methods noted here override File::Spec. =head3 catfile File::Spec <= 0.83 has a bug where the file part of catfile is not canonicalized. This override fixes that bug. =cut sub catfile { my $self = shift; return $self->canonpath($self->SUPER::catfile(@_)); } =head2 Misc Methods I can't really figure out where they should go yet. =head3 find_tests my $test = $mm->find_tests; Returns a string suitable for feeding to the shell to return all tests in t/*.t. =cut sub find_tests { my($self) = shift; return -d 't' ? 't/*.t' : ''; } =head3 find_tests_recursive my $tests = $mm->find_tests_recursive; Returns a string suitable for feeding to the shell to return all tests in t/ but recursively. Equivalent to my $tests = $mm->find_tests_recursive_in('t'); =cut sub find_tests_recursive { my $self = shift; return $self->find_tests_recursive_in('t'); } =head3 find_tests_recursive_in my $tests = $mm->find_tests_recursive_in($dir); Returns a string suitable for feeding to the shell to return all tests in $dir recursively. =cut sub find_tests_recursive_in { my($self, $dir) = @_; return '' unless -d $dir; require File::Find; my $base_depth = grep { $_ ne '' } File::Spec->splitdir( (File::Spec->splitpath($dir))[1] ); my %depths; my $wanted = sub { return unless m!\.t$!; my ($volume,$directories,$file) = File::Spec->splitpath( $File::Find::name ); my $depth = grep { $_ ne '' } File::Spec->splitdir( $directories ); $depth -= $base_depth; $depths{ $depth } = 1; }; File::Find::find( $wanted, $dir ); return join ' ', map { $dir . '/*' x $_ . '.t' } sort { $a <=> $b } keys %depths; } =head3 extra_clean_files my @files_to_clean = $MM->extra_clean_files; Returns a list of OS specific files to be removed in the clean target in addition to the usual set. =cut # An empty method here tickled a perl 5.8.1 bug and would return its object. sub extra_clean_files { return; } =head3 installvars my @installvars = $mm->installvars; A list of all the INSTALL* variables without the INSTALL prefix. Useful for iteration or building related variable sets. =cut sub installvars { return qw(PRIVLIB SITELIB VENDORLIB ARCHLIB SITEARCH VENDORARCH BIN SITEBIN VENDORBIN SCRIPT SITESCRIPT VENDORSCRIPT MAN1DIR SITEMAN1DIR VENDORMAN1DIR MAN3DIR SITEMAN3DIR VENDORMAN3DIR ); } =head3 libscan my $wanted = $self->libscan($path); Takes a path to a file or dir and returns an empty string if we don't want to include this file in the library. Otherwise it returns the the $path unchanged. Mainly used to exclude version control administrative directories and base-level F from installation. =cut sub libscan { my($self,$path) = @_; if ($path =~ m<^README\.pod$>i) { warn "WARNING: Older versions of ExtUtils::MakeMaker may errantly install $path as part of this distribution. It is recommended to avoid using this path in CPAN modules.\n"; return ''; } my($dirs,$file) = ($self->splitpath($path))[1,2]; return '' if grep /^(?:RCS|CVS|SCCS|\.svn|_darcs)$/, $self->splitdir($dirs), $file; return $path; } =head3 platform_constants my $make_frag = $mm->platform_constants Returns a make fragment defining all the macros initialized in init_platform() rather than put them in constants(). =cut sub platform_constants { return ''; } =head3 post_constants (o) Returns an empty string per default. Dedicated to overrides from within Makefile.PL after all constants have been defined. =cut sub post_constants { ""; } =head3 post_initialize (o) Returns an empty string per default. Used in Makefile.PLs to add some chunk of text to the Makefile after the object is initialized. =cut sub post_initialize { ""; } =head3 postamble (o) Returns an empty string. Can be used in Makefile.PLs to write some text to the Makefile at the end. =cut sub postamble { ""; } =begin private =head3 _PREREQ_PRINT $self->_PREREQ_PRINT; Implements PREREQ_PRINT. Refactored out of MakeMaker->new(). =end private =cut sub _PREREQ_PRINT { my $self = shift; require Data::Dumper; my @what = ('PREREQ_PM'); push @what, 'MIN_PERL_VERSION' if $self->{MIN_PERL_VERSION}; push @what, 'BUILD_REQUIRES' if $self->{BUILD_REQUIRES}; print Data::Dumper->Dump([@{$self}{@what}], \@what); exit 0; } =begin private =head3 _PRINT_PREREQ $mm->_PRINT_PREREQ; Implements PRINT_PREREQ, a slightly different version of PREREQ_PRINT added by Redhat to, I think, support generating RPMs from Perl modules. Should not include BUILD_REQUIRES as RPMs do not include them. Refactored out of MakeMaker->new(). =end private =cut sub _PRINT_PREREQ { my $self = shift; my $prereqs= $self->{PREREQ_PM}; my @prereq = map { [$_, $prereqs->{$_}] } keys %$prereqs; if ( $self->{MIN_PERL_VERSION} ) { push @prereq, ['perl' => $self->{MIN_PERL_VERSION}]; } print join(" ", map { "perl($_->[0])>=$_->[1] " } sort { $a->[0] cmp $b->[0] } @prereq), "\n"; exit 0; } =begin private =head3 _perl_header_files my $perl_header_files= $self->_perl_header_files; returns a sorted list of header files as found in PERL_SRC or $archlibexp/CORE. Used by perldepend() in MM_Unix and MM_VMS via _perl_header_files_fragment() =end private =cut sub _perl_header_files { my $self = shift; my $header_dir = $self->{PERL_SRC} || $ENV{PERL_SRC} || $self->catdir($Config{archlibexp}, 'CORE'); opendir my $dh, $header_dir or die "Failed to opendir '$header_dir' to find header files: $!"; # we need to use a temporary here as the sort in scalar context would have undefined results. my @perl_headers= sort grep { /\.h\z/ } readdir($dh); closedir $dh; return @perl_headers; } =begin private =head3 _perl_header_files_fragment ($o, $separator) my $perl_header_files_fragment= $self->_perl_header_files_fragment("/"); return a Makefile fragment which holds the list of perl header files which XS code depends on $(PERL_INC), and sets up the dependency for the $(OBJECT) file. The $separator argument defaults to "". MM_VMS will set it to "" and MM_UNIX to "/" in perldepend(). This reason child subclasses need to control this is that in VMS the $(PERL_INC) directory will already have delimiters in it, but in UNIX $(PERL_INC) will need a slash between it an the filename. Hypothetically win32 could use "\\" (but it doesn't need to). =end private =cut sub _perl_header_files_fragment { my ($self, $separator)= @_; $separator ||= ""; return join("\\\n", "PERL_HDRS = ", map { sprintf( " \$(PERL_INCDEP)%s%s ", $separator, $_ ) } $self->_perl_header_files() ) . "\n\n" . "\$(OBJECT) : \$(PERL_HDRS)\n"; } =head1 AUTHOR Michael G Schwern and the denizens of makemaker@perl.org with code from ExtUtils::MM_Unix and ExtUtils::MM_Win32. =cut 1; PK!ê'ã��perl5/ExtUtils/testlib.pmnuÏÃ6Ç$package ExtUtils::testlib; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use Cwd; use File::Spec; # So the tests can chdir around and not break @INC. # We use getcwd() because otherwise rel2abs will blow up under taint # mode pre-5.8. We detaint is so @INC won't be tainted. This is # no worse, and probably better, than just shoving an untainted, # relative "blib/lib" onto @INC. my $cwd; BEGIN { ($cwd) = getcwd() =~ /(.*)/; } use lib map { File::Spec->rel2abs($_, $cwd) } qw(blib/arch blib/lib); 1; __END__ =head1 NAME ExtUtils::testlib - add blib/* directories to @INC =head1 SYNOPSIS use ExtUtils::testlib; =head1 DESCRIPTION After an extension has been built and before it is installed it may be desirable to test it bypassing C. By adding use ExtUtils::testlib; to a test program the intermediate directories used by C are added to @INC. PK!”Yqüââperl5/ExtUtils/MM_UWIN.pmnuÏÃ6Ç$package ExtUtils::MM_UWIN; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Unix; our @ISA = qw(ExtUtils::MM_Unix); =head1 NAME ExtUtils::MM_UWIN - U/WIN specific subclass of ExtUtils::MM_Unix =head1 SYNOPSIS Don't use this module directly. Use ExtUtils::MM and let it choose. =head1 DESCRIPTION This is a subclass of L which contains functionality for the AT&T U/WIN UNIX on Windows environment. Unless otherwise stated it works just like ExtUtils::MM_Unix. =head2 Overridden methods =over 4 =item os_flavor In addition to being Unix, we're U/WIN. =cut sub os_flavor { return('Unix', 'U/WIN'); } =item B =cut sub replace_manpage_separator { my($self, $man) = @_; $man =~ s,/+,.,g; return $man; } =back =head1 AUTHOR Michael G Schwern with code from ExtUtils::MM_Unix =head1 SEE ALSO L, L =cut 1; PK!XÕÒÊ Ê perl5/ExtUtils/Mkbootstrap.pmnuÏÃ6Ç$package ExtUtils::Mkbootstrap; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require Exporter; our @ISA = ('Exporter'); our @EXPORT = ('&Mkbootstrap'); use Config; our $Verbose = 0; sub Mkbootstrap { my($baseext, @bsloadlibs)=@_; @bsloadlibs = grep($_, @bsloadlibs); # strip empty libs print " bsloadlibs=@bsloadlibs\n" if $Verbose; # We need DynaLoader here because we and/or the *_BS file may # call dl_findfile(). We don't say `use' here because when # first building perl extensions the DynaLoader will not have # been built when MakeMaker gets first used. require DynaLoader; rename "$baseext.bs", "$baseext.bso" if -s "$baseext.bs"; if (-f "${baseext}_BS"){ $_ = "${baseext}_BS"; package DynaLoader; # execute code as if in DynaLoader no strict 'vars'; local($osname, $dlsrc) = (); # avoid warnings ($osname, $dlsrc) = @Config::Config{qw(osname dlsrc)}; $bscode = ""; unshift @INC, "."; require $_; shift @INC; } if ($Config{'dlsrc'} =~ /^dl_dld/){ package DynaLoader; no strict 'vars'; push(@dl_resolve_using, dl_findfile('-lc')); } my(@all) = (@bsloadlibs, @DynaLoader::dl_resolve_using); my($method) = ''; if (@all || (defined $DynaLoader::bscode && length $DynaLoader::bscode)){ open my $bs, ">", "$baseext.bs" or die "Unable to open $baseext.bs: $!"; print "Writing $baseext.bs\n"; print " containing: @all" if $Verbose; print $bs "# $baseext DynaLoader bootstrap file for $^O architecture.\n"; print $bs "# Do not edit this file, changes will be lost.\n"; print $bs "# This file was automatically generated by the\n"; print $bs "# Mkbootstrap routine in ExtUtils::Mkbootstrap (v$VERSION).\n"; if (@all) { print $bs "\@DynaLoader::dl_resolve_using = "; # If @all contains names in the form -lxxx or -Lxxx then it's asking for # runtime library location so we automatically add a call to dl_findfile() if (" @all" =~ m/ -[lLR]/){ print $bs " dl_findfile(qw(\n @all\n ));\n"; } else { print $bs " qw(@all);\n"; } } # write extra code if *_BS says so print $bs $DynaLoader::bscode if $DynaLoader::bscode; print $bs "\n1;\n"; close $bs; } } 1; __END__ =head1 NAME ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader =head1 SYNOPSIS Mkbootstrap =head1 DESCRIPTION Mkbootstrap typically gets called from an extension Makefile. There is no C<*.bs> file supplied with the extension. Instead, there may be a C<*_BS> file which has code for the special cases, like posix for berkeley db on the NeXT. This file will get parsed, and produce a maybe empty C<@DynaLoader::dl_resolve_using> array for the current architecture. That will be extended by $BSLOADLIBS, which was computed by ExtUtils::Liblist::ext(). If this array still is empty, we do nothing, else we write a .bs file with an C<@DynaLoader::dl_resolve_using> array. The C<*_BS> file can put some code into the generated C<*.bs> file by placing it in C<$bscode>. This is a handy 'escape' mechanism that may prove useful in complex situations. If @DynaLoader::dl_resolve_using contains C<-L*> or C<-l*> entries then Mkbootstrap will automatically add a dl_findfile() call to the generated C<*.bs> file. =cut PK!§"ØØperl5/ExtUtils/MM_AIX.pmnuÏÃ6Ç$package ExtUtils::MM_AIX; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use ExtUtils::MakeMaker::Config; require ExtUtils::MM_Unix; our @ISA = qw(ExtUtils::MM_Unix); =head1 NAME ExtUtils::MM_AIX - AIX specific subclass of ExtUtils::MM_Unix =head1 SYNOPSIS Don't use this module directly. Use ExtUtils::MM and let it choose. =head1 DESCRIPTION This is a subclass of L which contains functionality for AIX. Unless otherwise stated it works just like ExtUtils::MM_Unix. =head2 Overridden methods =head3 dlsyms Define DL_FUNCS and DL_VARS and write the *.exp files. =cut sub dlsyms { my($self,%attribs) = @_; return '' unless $self->needs_linking; join "\n", $self->xs_dlsyms_iterator(\%attribs); } =head3 xs_dlsyms_ext On AIX, is C<.exp>. =cut sub xs_dlsyms_ext { '.exp'; } sub xs_dlsyms_arg { my($self, $file) = @_; my $arg = qq{-bE:${file}}; $arg = '-Wl,'.$arg if $Config{lddlflags} =~ /-Wl,-bE:/; return $arg; } sub init_others { my $self = shift; $self->SUPER::init_others; # perl "hints" add -bE:$(BASEEXT).exp to LDDLFLAGS. strip that out # so right value can be added by xs_make_dynamic_lib to work for XSMULTI $self->{LDDLFLAGS} ||= $Config{lddlflags}; $self->{LDDLFLAGS} =~ s#(\s*)\S*\Q$(BASEEXT)\E\S*(\s*)#$1$2#; return; } =head1 AUTHOR Michael G Schwern with code from ExtUtils::MM_Unix =head1 SEE ALSO L =cut 1; PK!o¢«ÿ88perl5/ExtUtils/Installed.pmnuÏÃ6Ç$package ExtUtils::Installed; use 5.00503; use strict; #use warnings; # XXX requires 5.6 use Carp qw(); use ExtUtils::Packlist; use ExtUtils::MakeMaker; use Config; use File::Find; use File::Basename; use File::Spec; my $Is_VMS = $^O eq 'VMS'; my $DOSISH = ($^O =~ /^(MSWin\d\d|os2|dos|mint)$/); require VMS::Filespec if $Is_VMS; use vars qw($VERSION); $VERSION = '2.06'; $VERSION = eval $VERSION; sub _is_prefix { my ($self, $path, $prefix) = @_; return unless defined $prefix && defined $path; if( $Is_VMS ) { $prefix = VMS::Filespec::unixify($prefix); $path = VMS::Filespec::unixify($path); } # Unix path normalization. $prefix = File::Spec->canonpath($prefix); return 1 if substr($path, 0, length($prefix)) eq $prefix; if ($DOSISH) { $path =~ s|\\|/|g; $prefix =~ s|\\|/|g; return 1 if $path =~ m{^\Q$prefix\E}i; } return(0); } sub _is_doc { my ($self, $path) = @_; my $man1dir = $self->{':private:'}{Config}{man1direxp}; my $man3dir = $self->{':private:'}{Config}{man3direxp}; return(($man1dir && $self->_is_prefix($path, $man1dir)) || ($man3dir && $self->_is_prefix($path, $man3dir)) ? 1 : 0) } sub _is_type { my ($self, $path, $type) = @_; return 1 if $type eq "all"; return($self->_is_doc($path)) if $type eq "doc"; my $conf= $self->{':private:'}{Config}; if ($type eq "prog") { return($self->_is_prefix($path, $conf->{prefix} || $conf->{prefixexp}) && !($self->_is_doc($path)) ? 1 : 0); } return(0); } sub _is_under { my ($self, $path, @under) = @_; $under[0] = "" if (! @under); foreach my $dir (@under) { return(1) if ($self->_is_prefix($path, $dir)); } return(0); } sub _fix_dirs { my ($self, @dirs)= @_; # File::Find does not know how to deal with VMS filepaths. if( $Is_VMS ) { $_ = VMS::Filespec::unixify($_) for @dirs; } if ($DOSISH) { s|\\|/|g for @dirs; } return wantarray ? @dirs : $dirs[0]; } sub _make_entry { my ($self, $module, $packlist_file, $modfile)= @_; my $data= { module => $module, packlist => scalar(ExtUtils::Packlist->new($packlist_file)), packlist_file => $packlist_file, }; if (!$modfile) { $data->{version} = $self->{':private:'}{Config}{version}; } else { $data->{modfile} = $modfile; # Find the top-level module file in @INC $data->{version} = ''; foreach my $dir (@{$self->{':private:'}{INC}}) { my $p = File::Spec->catfile($dir, $modfile); if (-r $p) { $module = _module_name($p, $module) if $Is_VMS; $data->{version} = MM->parse_version($p); $data->{version_from} = $p; $data->{packlist_valid} = exists $data->{packlist}{$p}; last; } } } $self->{$module}= $data; } our $INSTALLED; sub new { my ($class) = shift(@_); $class = ref($class) || $class; my %args = @_; return $INSTALLED if $INSTALLED and ($args{default_get} || $args{default}); my $self = bless {}, $class; $INSTALLED= $self if $args{default_set} || $args{default}; if ($args{config_override}) { eval { $self->{':private:'}{Config} = { %{$args{config_override}} }; } or Carp::croak( "The 'config_override' parameter must be a hash reference." ); } else { $self->{':private:'}{Config} = \%Config; } for my $tuple ([inc_override => INC => [ @INC ] ], [ extra_libs => EXTRA => [] ]) { my ($arg,$key,$val)=@$tuple; if ( $args{$arg} ) { eval { $self->{':private:'}{$key} = [ @{$args{$arg}} ]; } or Carp::croak( "The '$arg' parameter must be an array reference." ); } elsif ($val) { $self->{':private:'}{$key} = $val; } } { my %dupe; @{$self->{':private:'}{LIBDIRS}} = grep { $_ ne '.' || ! $args{skip_cwd} } grep { -e $_ && !$dupe{$_}++ } @{$self->{':private:'}{EXTRA}}, @{$self->{':private:'}{INC}}; } my @dirs= $self->_fix_dirs(@{$self->{':private:'}{LIBDIRS}}); # Read the core packlist my $archlib = $self->_fix_dirs($self->{':private:'}{Config}{archlibexp}); $self->_make_entry("Perl",File::Spec->catfile($archlib, '.packlist')); my $root; # Read the module packlists my $sub = sub { # Only process module .packlists return if $_ ne ".packlist" || $File::Find::dir eq $archlib; # Hack of the leading bits of the paths & convert to a module name my $module = $File::Find::name; my $found = $module =~ s!^.*?/auto/(.*)/.packlist!$1!s or do { # warn "Woah! \$_=$_\n\$module=$module\n\$File::Find::dir=$File::Find::dir\n", # join ("\n",@dirs); return; }; my $modfile = "$module.pm"; $module =~ s!/!::!g; return if $self->{$module}; #shadowing? $self->_make_entry($module,$File::Find::name,$modfile); }; while (@dirs) { $root= shift @dirs; next if !-d $root; find($sub,$root); } return $self; } # VMS's non-case preserving file-system means the package name can't # be reconstructed from the filename. sub _module_name { my($file, $orig_module) = @_; my $module = ''; if (open PACKFH, $file) { while () { if (/package\s+(\S+)\s*;/) { my $pack = $1; # Make a sanity check, that lower case $module # is identical to lowercase $pack before # accepting it if (lc($pack) eq lc($orig_module)) { $module = $pack; last; } } } close PACKFH; } print STDERR "Couldn't figure out the package name for $file\n" unless $module; return $module; } sub modules { my ($self) = @_; $self= $self->new(default=>1) if !ref $self; # Bug/feature of sort in scalar context requires this. return wantarray ? sort grep { not /^:private:$/ } keys %$self : grep { not /^:private:$/ } keys %$self; } sub files { my ($self, $module, $type, @under) = @_; $self= $self->new(default=>1) if !ref $self; # Validate arguments Carp::croak("$module is not installed") if (! exists($self->{$module})); $type = "all" if (! defined($type)); Carp::croak('type must be "all", "prog" or "doc"') if ($type ne "all" && $type ne "prog" && $type ne "doc"); my (@files); foreach my $file (keys(%{$self->{$module}{packlist}})) { push(@files, $file) if ($self->_is_type($file, $type) && $self->_is_under($file, @under)); } return(@files); } sub directories { my ($self, $module, $type, @under) = @_; $self= $self->new(default=>1) if !ref $self; my (%dirs); foreach my $file ($self->files($module, $type, @under)) { $dirs{dirname($file)}++; } return sort keys %dirs; } sub directory_tree { my ($self, $module, $type, @under) = @_; $self= $self->new(default=>1) if !ref $self; my (%dirs); foreach my $dir ($self->directories($module, $type, @under)) { $dirs{$dir}++; my ($last) = (""); while ($last ne $dir) { $last = $dir; $dir = dirname($dir); last if !$self->_is_under($dir, @under); $dirs{$dir}++; } } return(sort(keys(%dirs))); } sub validate { my ($self, $module, $remove) = @_; $self= $self->new(default=>1) if !ref $self; Carp::croak("$module is not installed") if (! exists($self->{$module})); return($self->{$module}{packlist}->validate($remove)); } sub packlist { my ($self, $module) = @_; $self= $self->new(default=>1) if !ref $self; Carp::croak("$module is not installed") if (! exists($self->{$module})); return($self->{$module}{packlist}); } sub version { my ($self, $module) = @_; $self= $self->new(default=>1) if !ref $self; Carp::croak("$module is not installed") if (! exists($self->{$module})); return($self->{$module}{version}); } sub debug_dump { my ($self, $module) = @_; $self= $self->new(default=>1) if !ref $self; local $self->{":private:"}{Config}; require Data::Dumper; print Data::Dumper->new([$self])->Sortkeys(1)->Indent(1)->Dump(); } 1; __END__ =head1 NAME ExtUtils::Installed - Inventory management of installed modules =head1 SYNOPSIS use ExtUtils::Installed; my ($inst) = ExtUtils::Installed->new( skip_cwd => 1 ); my (@modules) = $inst->modules(); my (@missing) = $inst->validate("DBI"); my $all_files = $inst->files("DBI"); my $files_below_usr_local = $inst->files("DBI", "all", "/usr/local"); my $all_dirs = $inst->directories("DBI"); my $dirs_below_usr_local = $inst->directory_tree("DBI", "prog"); my $packlist = $inst->packlist("DBI"); =head1 DESCRIPTION ExtUtils::Installed provides a standard way to find out what core and module files have been installed. It uses the information stored in .packlist files created during installation to provide this information. In addition it provides facilities to classify the installed files and to extract directory information from the .packlist files. =head1 USAGE The new() function searches for all the installed .packlists on the system, and stores their contents. The .packlists can be queried with the functions described below. Where it searches by default is determined by the settings found in C<%Config::Config>, and what the value is of the PERL5LIB environment variable. =head1 METHODS Unless specified otherwise all method can be called as class methods, or as object methods. If called as class methods then the "default" object will be used, and if necessary created using the current processes %Config and @INC. See the 'default' option to new() for details. =over 4 =item new() This takes optional named parameters. Without parameters, this searches for all the installed .packlists on the system using information from C<%Config::Config> and the default module search paths C<@INC>. The packlists are read using the L module. If the named parameter C is true, the current directory C<.> will be stripped from C<@INC> before searching for .packlists. This keeps ExtUtils::Installed from finding modules installed in other perls that happen to be located below the current directory. If the named parameter C is specified, it should be a reference to a hash which contains all information usually found in C<%Config::Config>. For example, you can obtain the configuration information for a separate perl installation and pass that in. my $yoda_cfg = get_fake_config('yoda'); my $yoda_inst = ExtUtils::Installed->new(config_override=>$yoda_cfg); Similarly, the parameter C may be a reference to an array which is used in place of the default module search paths from C<@INC>. use Config; my @dirs = split(/\Q$Config{path_sep}\E/, $ENV{PERL5LIB}); my $p5libs = ExtUtils::Installed->new(inc_override=>\@dirs); B: You probably do not want to use these options alone, almost always you will want to set both together. The parameter C can be used to specify B paths to search for installed modules. For instance my $installed = ExtUtils::Installed->new(extra_libs=>["/my/lib/path"]); This should only be necessary if F is not in PERL5LIB. Finally there is the 'default', and the related 'default_get' and 'default_set' options. These options control the "default" object which is provided by the class interface to the methods. Setting C to true tells the constructor to return the default object if it is defined. Setting C to true tells the constructor to make the default object the constructed object. Setting the C option is like setting both to true. This is used primarily internally and probably isn't interesting to any real user. =item modules() This returns a list of the names of all the installed modules. The perl 'core' is given the special name 'Perl'. =item files() This takes one mandatory parameter, the name of a module. It returns a list of all the filenames from the package. To obtain a list of core perl files, use the module name 'Perl'. Additional parameters are allowed. The first is one of the strings "prog", "doc" or "all", to select either just program files, just manual files or all files. The remaining parameters are a list of directories. The filenames returned will be restricted to those under the specified directories. =item directories() This takes one mandatory parameter, the name of a module. It returns a list of all the directories from the package. Additional parameters are allowed. The first is one of the strings "prog", "doc" or "all", to select either just program directories, just manual directories or all directories. The remaining parameters are a list of directories. The directories returned will be restricted to those under the specified directories. This method returns only the leaf directories that contain files from the specified module. =item directory_tree() This is identical in operation to directories(), except that it includes all the intermediate directories back up to the specified directories. =item validate() This takes one mandatory parameter, the name of a module. It checks that all the files listed in the modules .packlist actually exist, and returns a list of any missing files. If an optional second argument which evaluates to true is given any missing files will be removed from the .packlist =item packlist() This returns the ExtUtils::Packlist object for the specified module. =item version() This returns the version number for the specified module. =back =head1 EXAMPLE See the example in L. =head1 AUTHOR Alan Burlison =cut PK!ëî _ª_ªperl5/ExtUtils/MakeMaker.pmnuÏÃ6Ç$# $Id$ package ExtUtils::MakeMaker; use strict; use warnings; BEGIN {require 5.006;} require Exporter; use ExtUtils::MakeMaker::Config; use ExtUtils::MakeMaker::version; # ensure we always have our fake version.pm use Carp; use File::Path; my $CAN_DECODE = eval { require ExtUtils::MakeMaker::Locale; }; # 2 birds, 1 stone eval { ExtUtils::MakeMaker::Locale::reinit('UTF-8') } if $CAN_DECODE and Encode::find_encoding('locale')->name eq 'ascii'; our $Verbose = 0; # exported our @Parent; # needs to be localized our @Get_from_Config; # referenced by MM_Unix our @MM_Sections; our @Overridable; my @Prepend_parent; my %Recognized_Att_Keys; our %macro_fsentity; # whether a macro is a filesystem name our %macro_dep; # whether a macro is a dependency our $VERSION = '7.50'; $VERSION =~ tr/_//d; # Emulate something resembling CVS $Revision$ (our $Revision = $VERSION) =~ s{_}{}; $Revision = int $Revision * 10000; our $Filename = __FILE__; # referenced outside MakeMaker our @ISA = qw(Exporter); our @EXPORT = qw(&WriteMakefile $Verbose &prompt &os_unsupported); our @EXPORT_OK = qw($VERSION &neatvalue &mkbootstrap &mksymlists &WriteEmptyMakefile &open_for_writing &write_file_via_tmp &_sprintf562); # These will go away once the last of the Win32 & VMS specific code is # purged. my $Is_VMS = $^O eq 'VMS'; my $Is_Win32 = $^O eq 'MSWin32'; our $UNDER_CORE = $ENV{PERL_CORE}; # needs to be our full_setup(); require ExtUtils::MM; # Things like CPAN assume loading ExtUtils::MakeMaker # will give them MM. require ExtUtils::MY; # XXX pre-5.8 versions of ExtUtils::Embed expect # loading ExtUtils::MakeMaker will give them MY. # This will go when Embed is its own CPAN module. # 5.6.2 can't do sprintf "%1$s" - this can only do %s sub _sprintf562 { my ($format, @args) = @_; for (my $i = 1; $i <= @args; $i++) { $format =~ s#%$i\$s#$args[$i-1]#g; } $format; } sub WriteMakefile { croak "WriteMakefile: Need even number of args" if @_ % 2; require ExtUtils::MY; my %att = @_; _convert_compat_attrs(\%att); _verify_att(\%att); my $mm = MM->new(\%att); $mm->flush; return $mm; } # Basic signatures of the attributes WriteMakefile takes. Each is the # reference type. Empty value indicate it takes a non-reference # scalar. my %Att_Sigs; my %Special_Sigs = ( AUTHOR => 'ARRAY', C => 'ARRAY', CONFIG => 'ARRAY', CONFIGURE => 'CODE', DIR => 'ARRAY', DL_FUNCS => 'HASH', DL_VARS => 'ARRAY', EXCLUDE_EXT => 'ARRAY', EXE_FILES => 'ARRAY', FUNCLIST => 'ARRAY', H => 'ARRAY', IMPORTS => 'HASH', INCLUDE_EXT => 'ARRAY', LIBS => ['ARRAY',''], MAN1PODS => 'HASH', MAN3PODS => 'HASH', META_ADD => 'HASH', META_MERGE => 'HASH', OBJECT => ['ARRAY', ''], PL_FILES => 'HASH', PM => 'HASH', PMLIBDIRS => 'ARRAY', PMLIBPARENTDIRS => 'ARRAY', PREREQ_PM => 'HASH', BUILD_REQUIRES => 'HASH', CONFIGURE_REQUIRES => 'HASH', TEST_REQUIRES => 'HASH', SKIP => 'ARRAY', TYPEMAPS => 'ARRAY', XS => 'HASH', XSBUILD => 'HASH', VERSION => ['version',''], _KEEP_AFTER_FLUSH => '', clean => 'HASH', depend => 'HASH', dist => 'HASH', dynamic_lib=> 'HASH', linkext => 'HASH', macro => 'HASH', postamble => 'HASH', realclean => 'HASH', test => 'HASH', tool_autosplit => 'HASH', ); @Att_Sigs{keys %Recognized_Att_Keys} = ('') x keys %Recognized_Att_Keys; @Att_Sigs{keys %Special_Sigs} = values %Special_Sigs; sub _convert_compat_attrs { #result of running several times should be same my($att) = @_; if (exists $att->{AUTHOR}) { if ($att->{AUTHOR}) { if (!ref($att->{AUTHOR})) { my $t = $att->{AUTHOR}; $att->{AUTHOR} = [$t]; } } else { $att->{AUTHOR} = []; } } } sub _verify_att { my($att) = @_; foreach my $key (sort keys %$att) { my $val = $att->{$key}; my $sig = $Att_Sigs{$key}; unless( defined $sig ) { warn "WARNING: $key is not a known parameter.\n"; next; } my @sigs = ref $sig ? @$sig : $sig; my $given = ref $val; unless( grep { _is_of_type($val, $_) } @sigs ) { my $takes = join " or ", map { _format_att($_) } @sigs; my $has = _format_att($given); warn "WARNING: $key takes a $takes not a $has.\n". " Please inform the author.\n"; } } } # Check if a given thing is a reference or instance of $type sub _is_of_type { my($thing, $type) = @_; return 1 if ref $thing eq $type; local $SIG{__DIE__}; return 1 if eval{ $thing->isa($type) }; return 0; } sub _format_att { my $given = shift; return $given eq '' ? "string/number" : uc $given eq $given ? "$given reference" : "$given object" ; } sub prompt ($;$) { ## no critic my($mess, $def) = @_; confess("prompt function called without an argument") unless defined $mess; my $isa_tty = -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ; my $dispdef = defined $def ? "[$def] " : " "; $def = defined $def ? $def : ""; local $|=1; local $\; print "$mess $dispdef"; my $ans; if ($ENV{PERL_MM_USE_DEFAULT} || (!$isa_tty && eof STDIN)) { print "$def\n"; } else { $ans = ; if( defined $ans ) { $ans =~ s{\015?\012$}{}; } else { # user hit ctrl-D print "\n"; } } return (!defined $ans || $ans eq '') ? $def : $ans; } sub os_unsupported { die "OS unsupported\n"; } sub eval_in_subdirs { my($self) = @_; use Cwd qw(cwd abs_path); my $pwd = cwd() || die "Can't figure out your cwd!"; local @INC = map eval {abs_path($_) if -e} || $_, @INC; push @INC, '.'; # '.' has to always be at the end of @INC foreach my $dir (@{$self->{DIR}}){ my($abs) = $self->catdir($pwd,$dir); eval { $self->eval_in_x($abs); }; last if $@; } chdir $pwd; die $@ if $@; } sub eval_in_x { my($self,$dir) = @_; chdir $dir or carp("Couldn't change to directory $dir: $!"); { package main; do './Makefile.PL'; }; if ($@) { # if ($@ =~ /prerequisites/) { # die "MakeMaker WARNING: $@"; # } else { # warn "WARNING from evaluation of $dir/Makefile.PL: $@"; # } die "ERROR from evaluation of $dir/Makefile.PL: $@"; } } # package name for the classes into which the first object will be blessed my $PACKNAME = 'PACK000'; sub full_setup { $Verbose ||= 0; my @dep_macros = qw/ PERL_INCDEP PERL_ARCHLIBDEP PERL_ARCHIVEDEP /; my @fs_macros = qw/ FULLPERL XSUBPPDIR INST_ARCHLIB INST_SCRIPT INST_BIN INST_LIB INST_MAN1DIR INST_MAN3DIR INSTALLDIRS DESTDIR PREFIX INSTALL_BASE PERLPREFIX SITEPREFIX VENDORPREFIX INSTALLPRIVLIB INSTALLSITELIB INSTALLVENDORLIB INSTALLARCHLIB INSTALLSITEARCH INSTALLVENDORARCH INSTALLBIN INSTALLSITEBIN INSTALLVENDORBIN INSTALLMAN1DIR INSTALLMAN3DIR INSTALLSITEMAN1DIR INSTALLSITEMAN3DIR INSTALLVENDORMAN1DIR INSTALLVENDORMAN3DIR INSTALLSCRIPT INSTALLSITESCRIPT INSTALLVENDORSCRIPT PERL_LIB PERL_ARCHLIB SITELIBEXP SITEARCHEXP MAKE LIBPERL_A LIB PERL_SRC PERL_INC PPM_INSTALL_EXEC PPM_UNINSTALL_EXEC PPM_INSTALL_SCRIPT PPM_UNINSTALL_SCRIPT /; my @attrib_help = qw/ AUTHOR ABSTRACT ABSTRACT_FROM BINARY_LOCATION C CAPI CCFLAGS CONFIG CONFIGURE DEFINE DIR DISTNAME DISTVNAME DL_FUNCS DL_VARS EXCLUDE_EXT EXE_FILES FIRST_MAKEFILE FULLPERLRUN FULLPERLRUNINST FUNCLIST H IMPORTS INC INCLUDE_EXT LDFROM LIBS LICENSE LINKTYPE MAKEAPERL MAKEFILE MAKEFILE_OLD MAN1PODS MAN3PODS MAP_TARGET META_ADD META_MERGE MIN_PERL_VERSION BUILD_REQUIRES CONFIGURE_REQUIRES MYEXTLIB NAME NEEDS_LINKING NOECHO NO_META NO_MYMETA NO_PACKLIST NO_PERLLOCAL NORECURS NO_VC OBJECT OPTIMIZE PERL_MALLOC_OK PERL PERLMAINCC PERLRUN PERLRUNINST PERL_CORE PERM_DIR PERM_RW PERM_RWX MAGICXS PL_FILES PM PM_FILTER PMLIBDIRS PMLIBPARENTDIRS POLLUTE PREREQ_FATAL PREREQ_PM PREREQ_PRINT PRINT_PREREQ PUREPERL_ONLY SIGN SKIP TEST_REQUIRES TYPEMAPS UNINST VERSION VERSION_FROM XS XSBUILD XSMULTI XSOPT XSPROTOARG XS_VERSION clean depend dist dynamic_lib linkext macro realclean tool_autosplit MAN1EXT MAN3EXT MACPERL_SRC MACPERL_LIB MACLIBS_68K MACLIBS_PPC MACLIBS_SC MACLIBS_MRC MACLIBS_ALL_68K MACLIBS_ALL_PPC MACLIBS_SHARED /; push @attrib_help, @fs_macros; @macro_fsentity{@fs_macros, @dep_macros} = (1) x (@fs_macros+@dep_macros); @macro_dep{@dep_macros} = (1) x @dep_macros; # IMPORTS is used under OS/2 and Win32 # @Overridable is close to @MM_Sections but not identical. The # order is important. Many subroutines declare macros. These # depend on each other. Let's try to collect the macros up front, # then pasthru, then the rules. # MM_Sections are the sections we have to call explicitly # in Overridable we have subroutines that are used indirectly @MM_Sections = qw( post_initialize const_config constants platform_constants tool_autosplit tool_xsubpp tools_other makemakerdflt dist macro depend cflags const_loadlibs const_cccmd post_constants pasthru special_targets c_o xs_c xs_o top_targets blibdirs linkext dlsyms dynamic_bs dynamic dynamic_lib static static_lib manifypods processPL installbin subdirs clean_subdirs clean realclean_subdirs realclean metafile signature dist_basics dist_core distdir dist_test dist_ci distmeta distsignature install force perldepend makefile staticmake test ppd ); # loses section ordering @Overridable = @MM_Sections; push @Overridable, qw[ libscan makeaperl needs_linking subdir_x test_via_harness test_via_script init_VERSION init_dist init_INST init_INSTALL init_DEST init_dirscan init_PM init_MANPODS init_xs init_PERL init_DIRFILESEP init_linker ]; push @MM_Sections, qw[ pm_to_blib selfdocument ]; # Postamble needs to be the last that was always the case push @MM_Sections, "postamble"; push @Overridable, "postamble"; # All sections are valid keys. @Recognized_Att_Keys{@MM_Sections} = (1) x @MM_Sections; # we will use all these variables in the Makefile @Get_from_Config = qw( ar cc cccdlflags ccdlflags dlext dlsrc exe_ext full_ar ld lddlflags ldflags libc lib_ext obj_ext osname osvers ranlib sitelibexp sitearchexp so ); # 5.5.3 doesn't have any concept of vendor libs push @Get_from_Config, qw( vendorarchexp vendorlibexp ) if "$]" >= 5.006; foreach my $item (@attrib_help){ $Recognized_Att_Keys{$item} = 1; } foreach my $item (@Get_from_Config) { $Recognized_Att_Keys{uc $item} = $Config{$item}; print "Attribute '\U$item\E' => '$Config{$item}'\n" if ($Verbose >= 2); } # # When we eval a Makefile.PL in a subdirectory, that one will ask # us (the parent) for the values and will prepend "..", so that # all files to be installed end up below OUR ./blib # @Prepend_parent = qw( INST_BIN INST_LIB INST_ARCHLIB INST_SCRIPT MAP_TARGET INST_MAN1DIR INST_MAN3DIR PERL_SRC PERL FULLPERL ); } sub _has_cpan_meta_requirements { return eval { require CPAN::Meta::Requirements; CPAN::Meta::Requirements->VERSION(2.130); require B; # CMR requires this, for core we have to too. }; } sub new { my($class,$self) = @_; my($key); _convert_compat_attrs($self) if defined $self && $self; # Store the original args passed to WriteMakefile() foreach my $k (keys %$self) { $self->{ARGS}{$k} = $self->{$k}; } $self = {} unless defined $self; # Temporarily bless it into MM so it can be used as an # object. It will be blessed into a temp package later. bless $self, "MM"; # Cleanup all the module requirement bits my %key2cmr; for my $key (qw(PREREQ_PM BUILD_REQUIRES CONFIGURE_REQUIRES TEST_REQUIRES)) { $self->{$key} ||= {}; if (_has_cpan_meta_requirements) { my $cmr = CPAN::Meta::Requirements->from_string_hash( $self->{$key}, { bad_version_hook => sub { #no warnings 'numeric'; # module doesn't use warnings my $fallback; if ( $_[0] =~ m!^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$! ) { $fallback = sprintf "%f", $_[0]; } else { ($fallback) = $_[0] ? ($_[0] =~ /^([0-9.]+)/) : 0; $fallback += 0; carp "Unparsable version '$_[0]' for prerequisite $_[1] treated as $fallback"; } version->new($fallback); }, }, ); $self->{$key} = $cmr->as_string_hash; $key2cmr{$key} = $cmr; } else { for my $module (sort keys %{ $self->{$key} }) { my $version = $self->{$key}->{$module}; my $fallback = 0; if (!defined($version) or !length($version)) { carp "Undefined requirement for $module treated as '0' (CPAN::Meta::Requirements not available)"; } elsif ($version =~ /^\d+(?:\.\d+(?:_\d+)*)?$/) { next; } else { if ( $version =~ m!^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$! ) { $fallback = sprintf "%f", $version; } else { ($fallback) = $version ? ($version =~ /^([0-9.]+)/) : 0; $fallback += 0; carp "Unparsable version '$version' for prerequisite $module treated as $fallback (CPAN::Meta::Requirements not available)"; } } $self->{$key}->{$module} = $fallback; } } } if ("@ARGV" =~ /\bPREREQ_PRINT\b/) { $self->_PREREQ_PRINT; } # PRINT_PREREQ is RedHatism. if ("@ARGV" =~ /\bPRINT_PREREQ\b/) { $self->_PRINT_PREREQ; } print "MakeMaker (v$VERSION)\n" if $Verbose; if (-f "MANIFEST" && ! -f "Makefile" && ! $UNDER_CORE){ check_manifest(); } check_hints($self); if ( $self->{MIN_PERL_VERSION}) { my $perl_version = $self->{MIN_PERL_VERSION}; if (ref $perl_version) { # assume a version object } else { $perl_version = eval { local $SIG{__WARN__} = sub { # simulate "use warnings FATAL => 'all'" for vintage perls die @_; }; version->new( $perl_version )->numify; }; $perl_version =~ tr/_//d if defined $perl_version; } if (!defined $perl_version) { # should this be a warning? die sprintf <<'END', $self->{MIN_PERL_VERSION}; MakeMaker FATAL: MIN_PERL_VERSION (%s) is not in a recognized format. Recommended is a quoted numerical value like '5.005' or '5.008001'. END } elsif ($perl_version > "$]") { my $message = sprintf <<'END', $perl_version, $]; Perl version %s or higher required. We run %s. END if ($self->{PREREQ_FATAL}) { die "MakeMaker FATAL: $message"; } else { warn "Warning: $message"; } } $self->{MIN_PERL_VERSION} = $perl_version; } my %configure_att; # record &{$self->{CONFIGURE}} attributes my(%initial_att) = %$self; # record initial attributes my(%unsatisfied) = (); my %prereq2version; my $cmr; if (_has_cpan_meta_requirements) { $cmr = CPAN::Meta::Requirements->new; for my $key (qw(PREREQ_PM BUILD_REQUIRES CONFIGURE_REQUIRES TEST_REQUIRES)) { $cmr->add_requirements($key2cmr{$key}) if $key2cmr{$key}; } foreach my $prereq ($cmr->required_modules) { $prereq2version{$prereq} = $cmr->requirements_for_module($prereq); } } else { for my $key (qw(PREREQ_PM BUILD_REQUIRES CONFIGURE_REQUIRES TEST_REQUIRES)) { next unless my $module2version = $self->{$key}; $prereq2version{$_} = $module2version->{$_} for keys %$module2version; } } foreach my $prereq (sort keys %prereq2version) { my $required_version = $prereq2version{$prereq}; my $pr_version = 0; my $installed_file; if ( $prereq eq 'perl' ) { if ( defined $required_version && $required_version =~ /^v?[\d_\.]+$/ || $required_version !~ /^v?[\d_\.]+$/ ) { require version; my $normal = eval { version->new( $required_version ) }; $required_version = $normal if defined $normal; } $installed_file = $prereq; $pr_version = $]; } else { $installed_file = MM->_installed_file_for_module($prereq); $pr_version = MM->parse_version($installed_file) if $installed_file; $pr_version = 0 if $pr_version eq 'undef'; if ( !eval { version->new( $pr_version ); 1 } ) { #no warnings 'numeric'; # module doesn't use warnings my $fallback; if ( $pr_version =~ m!^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$! ) { $fallback = sprintf '%f', $pr_version; } else { ($fallback) = $pr_version ? ($pr_version =~ /^([0-9.]+)/) : 0; $fallback += 0; carp "Unparsable version '$pr_version' for installed prerequisite $prereq treated as $fallback"; } $pr_version = $fallback; } } # convert X.Y_Z alpha version #s to X.YZ for easier comparisons $pr_version =~ s/(\d+)\.(\d+)_(\d+)/$1.$2$3/; if (!$installed_file) { warn sprintf "Warning: prerequisite %s %s not found.\n", $prereq, $required_version unless $self->{PREREQ_FATAL} or $UNDER_CORE; $unsatisfied{$prereq} = 'not installed'; } elsif ( $cmr ? !$cmr->accepts_module($prereq, $pr_version) : $required_version > $pr_version ) { warn sprintf "Warning: prerequisite %s %s not found. We have %s.\n", $prereq, $required_version, ($pr_version || 'unknown version') unless $self->{PREREQ_FATAL} or $UNDER_CORE; $unsatisfied{$prereq} = $required_version || 'unknown version' ; } } if (%unsatisfied && $self->{PREREQ_FATAL}){ my $failedprereqs = join "\n", map {" $_ $unsatisfied{$_}"} sort { $a cmp $b } keys %unsatisfied; die <<"END"; MakeMaker FATAL: prerequisites not found. $failedprereqs Please install these modules first and rerun 'perl Makefile.PL'. END } if (defined $self->{CONFIGURE}) { if (ref $self->{CONFIGURE} eq 'CODE') { %configure_att = %{&{$self->{CONFIGURE}}}; _convert_compat_attrs(\%configure_att); $self = { %$self, %configure_att }; } else { croak "Attribute 'CONFIGURE' to WriteMakefile() not a code reference\n"; } } my $newclass = ++$PACKNAME; local @Parent = @Parent; # Protect against non-local exits { print "Blessing Object into class [$newclass]\n" if $Verbose>=2; mv_all_methods("MY",$newclass); bless $self, $newclass; push @Parent, $self; require ExtUtils::MY; no strict 'refs'; ## no critic; @{"$newclass\:\:ISA"} = 'MM'; } if (defined $Parent[-2]){ $self->{PARENT} = $Parent[-2]; for my $key (@Prepend_parent) { next unless defined $self->{PARENT}{$key}; # Don't stomp on WriteMakefile() args. next if defined $self->{ARGS}{$key} and $self->{ARGS}{$key} eq $self->{$key}; $self->{$key} = $self->{PARENT}{$key}; if ($Is_VMS && $key =~ /PERL$/) { # PERL or FULLPERL will be a command verb or even a # command with an argument instead of a full file # specification under VMS. So, don't turn the command # into a filespec, but do add a level to the path of # the argument if not already absolute. my @cmd = split /\s+/, $self->{$key}; $cmd[1] = $self->catfile('[-]',$cmd[1]) unless (@cmd < 2) || $self->file_name_is_absolute($cmd[1]); $self->{$key} = join(' ', @cmd); } else { my $value = $self->{$key}; # not going to test in FS so only stripping start $value =~ s/"// if $key =~ /PERL$/ and $self->is_make_type('dmake'); $value =~ s/^"// if $key =~ /PERL$/; $value = $self->catdir("..", $value) unless $self->file_name_is_absolute($value); $value = qq{"$value} if $key =~ /PERL$/; $self->{$key} = $value; } } if ($self->{PARENT}) { $self->{PARENT}->{CHILDREN}->{$newclass} = $self; foreach my $opt (qw(POLLUTE PERL_CORE LINKTYPE AR FULL_AR CC CCFLAGS OPTIMIZE LD LDDLFLAGS LDFLAGS PERL_ARCHLIB DESTDIR)) { if (exists $self->{PARENT}->{$opt} and not exists $self->{$opt}) { # inherit, but only if already unspecified $self->{$opt} = $self->{PARENT}->{$opt}; } } } my @fm = grep /^FIRST_MAKEFILE=/, @ARGV; parse_args($self,@fm) if @fm; } else { parse_args($self, _shellwords($ENV{PERL_MM_OPT} || ''),@ARGV); } # RT#91540 PREREQ_FATAL not recognized on command line if (%unsatisfied && $self->{PREREQ_FATAL}){ my $failedprereqs = join "\n", map {" $_ $unsatisfied{$_}"} sort { $a cmp $b } keys %unsatisfied; die <<"END"; MakeMaker FATAL: prerequisites not found. $failedprereqs Please install these modules first and rerun 'perl Makefile.PL'. END } $self->{NAME} ||= $self->guess_name; warn "Warning: NAME must be a package name\n" unless $self->{NAME} =~ m!^[A-Z_a-z][0-9A-Z_a-z]*(?:::[0-9A-Z_a-z]+)*$!; ($self->{NAME_SYM} = $self->{NAME}) =~ s/\W+/_/g; $self->init_MAKE; $self->init_main; $self->init_VERSION; $self->init_dist; $self->init_INST; $self->init_INSTALL; $self->init_DEST; $self->init_dirscan; $self->init_PM; $self->init_MANPODS; $self->init_xs; $self->init_PERL; $self->init_DIRFILESEP; $self->init_linker; $self->init_ABSTRACT; $self->arch_check( $INC{'Config.pm'}, $self->catfile($Config{'archlibexp'}, "Config.pm") ); $self->init_tools(); $self->init_others(); $self->init_platform(); $self->init_PERM(); my @args = @ARGV; @args = map { Encode::decode(locale => $_) } @args if $CAN_DECODE; my($argv) = neatvalue(\@args); $argv =~ s/^\[/(/; $argv =~ s/\]$/)/; push @{$self->{RESULT}}, <{NAME} extension to perl. # # It was generated automatically by MakeMaker version # $VERSION (Revision: $Revision) from the contents of # Makefile.PL. Don't edit this file, edit Makefile.PL instead. # # ANY CHANGES MADE HERE WILL BE LOST! # # MakeMaker ARGV: $argv # END push @{$self->{RESULT}}, $self->_MakeMaker_Parameters_section(\%initial_att); if (defined $self->{CONFIGURE}) { push @{$self->{RESULT}}, < 0) { foreach my $key (sort keys %configure_att){ next if $key eq 'ARGS'; my($v) = neatvalue($configure_att{$key}); $v =~ s/(CODE|HASH|ARRAY|SCALAR)\([\dxa-f]+\)/$1\(...\)/; $v =~ tr/\n/ /s; push @{$self->{RESULT}}, "# $key => $v"; } } else { push @{$self->{RESULT}}, "# no values returned"; } undef %configure_att; # free memory } # turn the SKIP array into a SKIPHASH hash for my $skip (@{$self->{SKIP} || []}) { $self->{SKIPHASH}{$skip} = 1; } delete $self->{SKIP}; # free memory if ($self->{PARENT}) { for (qw/install dist dist_basics dist_core distdir dist_test dist_ci/) { $self->{SKIPHASH}{$_} = 1; } } # We run all the subdirectories now. They don't have much to query # from the parent, but the parent has to query them: if they need linking! unless ($self->{NORECURS}) { $self->eval_in_subdirs if @{$self->{DIR}}; } foreach my $section ( @MM_Sections ){ # Support for new foo_target() methods. my $method = $section; $method .= '_target' unless $self->can($method); print "Processing Makefile '$section' section\n" if ($Verbose >= 2); my($skipit) = $self->skipcheck($section); if ($skipit){ push @{$self->{RESULT}}, "\n# --- MakeMaker $section section $skipit."; } else { my(%a) = %{$self->{$section} || {}}; push @{$self->{RESULT}}, "\n# --- MakeMaker $section section:"; push @{$self->{RESULT}}, "# " . join ", ", %a if $Verbose && %a; push @{$self->{RESULT}}, $self->maketext_filter( $self->$method( %a ) ); } } push @{$self->{RESULT}}, "\n# End."; $self; } sub WriteEmptyMakefile { croak "WriteEmptyMakefile: Need an even number of args" if @_ % 2; my %att = @_; $att{DIR} = [] unless $att{DIR}; # don't recurse by default my $self = MM->new(\%att); my $new = $self->{MAKEFILE}; my $old = $self->{MAKEFILE_OLD}; if (-f $old) { _unlink($old) or warn "unlink $old: $!"; } if ( -f $new ) { _rename($new, $old) or warn "rename $new => $old: $!" } open my $mfh, '>', $new or die "open $new for write: $!"; print $mfh <<'EOP'; all : manifypods : subdirs : dynamic : static : clean : install : makemakerdflt : test : test_dynamic : test_static : EOP close $mfh or die "close $new for write: $!"; } =begin private =head3 _installed_file_for_module my $file = MM->_installed_file_for_module($module); Return the first installed .pm $file associated with the $module. The one which will show up when you C. $module is something like "strict" or "Test::More". =end private =cut sub _installed_file_for_module { my $class = shift; my $prereq = shift; my $file = "$prereq.pm"; $file =~ s{::}{/}g; my $path; for my $dir (@INC) { my $tmp = File::Spec->catfile($dir, $file); if ( -r $tmp ) { $path = $tmp; last; } } return $path; } # Extracted from MakeMaker->new so we can test it sub _MakeMaker_Parameters_section { my $self = shift; my $att = shift; my @result = <<'END'; # MakeMaker Parameters: END foreach my $key (sort keys %$att){ next if $key eq 'ARGS'; my $v; if ($key eq 'PREREQ_PM') { # CPAN.pm takes prereqs from this field in 'Makefile' # and does not know about BUILD_REQUIRES $v = neatvalue({ %{ $att->{PREREQ_PM} || {} }, %{ $att->{BUILD_REQUIRES} || {} }, %{ $att->{TEST_REQUIRES} || {} }, }); } else { $v = neatvalue($att->{$key}); } $v =~ s/(CODE|HASH|ARRAY|SCALAR)\([\dxa-f]+\)/$1\(...\)/; $v =~ tr/\n/ /s; push @result, "# $key => $v"; } return @result; } # _shellwords and _parseline borrowed from Text::ParseWords sub _shellwords { my (@lines) = @_; my @allwords; foreach my $line (@lines) { $line =~ s/^\s+//; my @words = _parse_line('\s+', 0, $line); pop @words if (@words and !defined $words[-1]); return() unless (@words || !length($line)); push(@allwords, @words); } return(@allwords); } sub _parse_line { my($delimiter, $keep, $line) = @_; my($word, @pieces); no warnings 'uninitialized'; # we will be testing undef strings while (length($line)) { # This pattern is optimised to be stack conservative on older perls. # Do not refactor without being careful and testing it on very long strings. # See Perl bug #42980 for an example of a stack busting input. $line =~ s/^ (?: # double quoted string (") # $quote ((?>[^\\"]*(?:\\.[^\\"]*)*))" # $quoted | # --OR-- # singe quoted string (') # $quote ((?>[^\\']*(?:\\.[^\\']*)*))' # $quoted | # --OR-- # unquoted string ( # $unquoted (?:\\.|[^\\"'])*? ) # followed by ( # $delim \Z(?!\n) # EOL | # --OR-- (?-x:$delimiter) # delimiter | # --OR-- (?!^)(?=["']) # a quote ) )//xs or return; # extended layout my ($quote, $quoted, $unquoted, $delim) = (($1 ? ($1,$2) : ($3,$4)), $5, $6); return() unless( defined($quote) || length($unquoted) || length($delim)); if ($keep) { $quoted = "$quote$quoted$quote"; } else { $unquoted =~ s/\\(.)/$1/sg; if (defined $quote) { $quoted =~ s/\\(.)/$1/sg if ($quote eq '"'); #$quoted =~ s/\\([\\'])/$1/g if ( $PERL_SINGLE_QUOTE && $quote eq "'"); } } $word .= substr($line, 0, 0); # leave results tainted $word .= defined $quote ? $quoted : $unquoted; if (length($delim)) { push(@pieces, $word); push(@pieces, $delim) if ($keep eq 'delimiters'); undef $word; } if (!length($line)) { push(@pieces, $word); } } return(@pieces); } sub check_manifest { print "Checking if your kit is complete...\n"; require ExtUtils::Manifest; # avoid warning $ExtUtils::Manifest::Quiet = $ExtUtils::Manifest::Quiet = 1; my(@missed) = ExtUtils::Manifest::manicheck(); if (@missed) { print "Warning: the following files are missing in your kit:\n"; print "\t", join "\n\t", @missed; print "\n"; print "Please inform the author.\n"; } else { print "Looks good\n"; } } sub parse_args{ my($self, @args) = @_; @args = map { Encode::decode(locale => $_) } @args if $CAN_DECODE; foreach (@args) { unless (m/(.*?)=(.*)/) { ++$Verbose if m/^verb/; next; } my($name, $value) = ($1, $2); if ($value =~ m/^~(\w+)?/) { # tilde with optional username $value =~ s [^~(\w*)] [$1 ? ((getpwnam($1))[7] || "~$1") : (getpwuid($>))[7] ]ex; } # Remember the original args passed it. It will be useful later. $self->{ARGS}{uc $name} = $self->{uc $name} = $value; } # catch old-style 'potential_libs' and inform user how to 'upgrade' if (defined $self->{potential_libs}){ my($msg)="'potential_libs' => '$self->{potential_libs}' should be"; if ($self->{potential_libs}){ print "$msg changed to:\n\t'LIBS' => ['$self->{potential_libs}']\n"; } else { print "$msg deleted.\n"; } $self->{LIBS} = [$self->{potential_libs}]; delete $self->{potential_libs}; } # catch old-style 'ARMAYBE' and inform user how to 'upgrade' if (defined $self->{ARMAYBE}){ my($armaybe) = $self->{ARMAYBE}; print "ARMAYBE => '$armaybe' should be changed to:\n", "\t'dynamic_lib' => {ARMAYBE => '$armaybe'}\n"; my(%dl) = %{$self->{dynamic_lib} || {}}; $self->{dynamic_lib} = { %dl, ARMAYBE => $armaybe}; delete $self->{ARMAYBE}; } if (defined $self->{LDTARGET}){ print "LDTARGET should be changed to LDFROM\n"; $self->{LDFROM} = $self->{LDTARGET}; delete $self->{LDTARGET}; } # Turn a DIR argument on the command line into an array if (defined $self->{DIR} && ref \$self->{DIR} eq 'SCALAR') { # So they can choose from the command line, which extensions they want # the grep enables them to have some colons too much in case they # have to build a list with the shell $self->{DIR} = [grep $_, split ":", $self->{DIR}]; } # Turn a INCLUDE_EXT argument on the command line into an array if (defined $self->{INCLUDE_EXT} && ref \$self->{INCLUDE_EXT} eq 'SCALAR') { $self->{INCLUDE_EXT} = [grep $_, split '\s+', $self->{INCLUDE_EXT}]; } # Turn a EXCLUDE_EXT argument on the command line into an array if (defined $self->{EXCLUDE_EXT} && ref \$self->{EXCLUDE_EXT} eq 'SCALAR') { $self->{EXCLUDE_EXT} = [grep $_, split '\s+', $self->{EXCLUDE_EXT}]; } foreach my $mmkey (sort keys %$self){ next if $mmkey eq 'ARGS'; print " $mmkey => ", neatvalue($self->{$mmkey}), "\n" if $Verbose; print "'$mmkey' is not a known MakeMaker parameter name.\n" unless exists $Recognized_Att_Keys{$mmkey}; } $| = 1 if $Verbose; } sub check_hints { my($self) = @_; # We allow extension-specific hints files. require File::Spec; my $curdir = File::Spec->curdir; my $hint_dir = File::Spec->catdir($curdir, "hints"); return unless -d $hint_dir; # First we look for the best hintsfile we have my($hint)="${^O}_$Config{osvers}"; $hint =~ s/\./_/g; $hint =~ s/_$//; return unless $hint; # Also try without trailing minor version numbers. while (1) { last if -f File::Spec->catfile($hint_dir, "$hint.pl"); # found } continue { last unless $hint =~ s/_[^_]*$//; # nothing to cut off } my $hint_file = File::Spec->catfile($hint_dir, "$hint.pl"); return unless -f $hint_file; # really there _run_hintfile($self, $hint_file); } sub _run_hintfile { my ($self, $hint_file) = @_; local($@, $!); print "Processing hints file $hint_file\n" if $Verbose; if(open(my $fh, '<', $hint_file)) { my $hints_content = do { local $/; <$fh> }; no strict; eval $hints_content; warn "Failed to run hint file $hint_file: $@" if $@; } else { warn "Could not open $hint_file for read: $!"; } } sub mv_all_methods { my($from,$to) = @_; local $SIG{__WARN__} = sub { # can't use 'no warnings redefined', 5.6 only warn @_ unless $_[0] =~ /^Subroutine .* redefined/ }; foreach my $method (@Overridable) { next unless defined &{"${from}::$method"}; no strict 'refs'; ## no critic *{"${to}::$method"} = \&{"${from}::$method"}; # If we delete a method, then it will be undefined and cannot # be called. But as long as we have Makefile.PLs that rely on # %MY:: being intact, we have to fill the hole with an # inheriting method: { package MY; my $super = "SUPER::".$method; *{$method} = sub { shift->$super(@_); }; } } } sub skipcheck { my($self) = shift; my($section) = @_; return 'skipped' if $section eq 'metafile' && $UNDER_CORE; if ($section eq 'dynamic') { print "Warning (non-fatal): Target 'dynamic' depends on targets ", "in skipped section 'dynamic_bs'\n" if $self->{SKIPHASH}{dynamic_bs} && $Verbose; print "Warning (non-fatal): Target 'dynamic' depends on targets ", "in skipped section 'dynamic_lib'\n" if $self->{SKIPHASH}{dynamic_lib} && $Verbose; } if ($section eq 'dynamic_lib') { print "Warning (non-fatal): Target '\$(INST_DYNAMIC)' depends on ", "targets in skipped section 'dynamic_bs'\n" if $self->{SKIPHASH}{dynamic_bs} && $Verbose; } if ($section eq 'static') { print "Warning (non-fatal): Target 'static' depends on targets ", "in skipped section 'static_lib'\n" if $self->{SKIPHASH}{static_lib} && $Verbose; } return 'skipped' if $self->{SKIPHASH}{$section}; return ''; } # returns filehandle, dies on fail. :raw so no :crlf sub open_for_writing { my ($file) = @_; open my $fh ,">", $file or die "Unable to open $file: $!"; my @layers = ':raw'; push @layers, join ' ', ':encoding(locale)' if $CAN_DECODE; binmode $fh, join ' ', @layers; $fh; } sub flush { my $self = shift; my $finalname = $self->{MAKEFILE}; printf "Generating a %s %s\n", $self->make_type, $finalname if $Verbose || !$self->{PARENT}; print "Writing $finalname for $self->{NAME}\n" if $Verbose || !$self->{PARENT}; unlink($finalname, "MakeMaker.tmp", $Is_VMS ? 'Descrip.MMS' : ()); write_file_via_tmp($finalname, $self->{RESULT}); # Write MYMETA.yml to communicate metadata up to the CPAN clients print "Writing MYMETA.yml and MYMETA.json\n" if !$self->{NO_MYMETA} and $self->write_mymeta( $self->mymeta ); # save memory if ($self->{PARENT} && !$self->{_KEEP_AFTER_FLUSH}) { my %keep = map { ($_ => 1) } qw(NEEDS_LINKING HAS_LINK_CODE); delete $self->{$_} for grep !$keep{$_}, keys %$self; } system("$Config::Config{eunicefix} $finalname") if $Config::Config{eunicefix} ne ":"; return; } sub write_file_via_tmp { my ($finalname, $contents) = @_; my $fh = open_for_writing("MakeMaker.tmp"); die "write_file_via_tmp: 2nd arg must be ref" unless ref $contents; for my $chunk (@$contents) { my $to_write = $chunk; utf8::encode $to_write if !$CAN_DECODE && "$]" > 5.008; print $fh "$to_write\n" or die "Can't write to MakeMaker.tmp: $!"; } close $fh or die "Can't write to MakeMaker.tmp: $!"; _rename("MakeMaker.tmp", $finalname) or warn "rename MakeMaker.tmp => $finalname: $!"; chmod 0644, $finalname if !$Is_VMS; return; } # This is a rename for OS's where the target must be unlinked first. sub _rename { my($src, $dest) = @_; _unlink($dest); return rename $src, $dest; } # This is an unlink for OS's where the target must be writable first. sub _unlink { my @files = @_; chmod 0666, @files; return unlink @files; } # The following mkbootstrap() is only for installations that are calling # the pre-4.1 mkbootstrap() from their old Makefiles. This MakeMaker # writes Makefiles, that use ExtUtils::Mkbootstrap directly. sub mkbootstrap { die <".neatvalue($v->{$key}); } return "{ ".join(', ',@m)." }"; } sub _find_magic_vstring { my $value = shift; return $value if $UNDER_CORE; my $tvalue = ''; require B; my $sv = B::svref_2object(\$value); my $magic = ref($sv) eq 'B::PVMG' ? $sv->MAGIC : undef; while ( $magic ) { if ( $magic->TYPE eq 'V' ) { $tvalue = $magic->PTR; $tvalue =~ s/^v?(.+)$/v$1/; last; } else { $magic = $magic->MOREMAGIC; } } return $tvalue; } sub selfdocument { my($self) = @_; my(@m); if ($Verbose){ push @m, "\n# Full list of MakeMaker attribute values:"; foreach my $key (sort keys %$self){ next if $key eq 'RESULT' || $key =~ /^[A-Z][a-z]/; my($v) = neatvalue($self->{$key}); $v =~ s/(CODE|HASH|ARRAY|SCALAR)\([\dxa-f]+\)/$1\(...\)/; $v =~ tr/\n/ /s; push @m, "# $key => $v"; } } # added here as selfdocument is not overridable push @m, <<'EOF'; # here so even if top_targets is overridden, these will still be defined # gmake will silently still work if any are .PHONY-ed but nmake won't EOF push @m, join "\n", map "$_ ::\n\t\$(NOECHO) \$(NOOP)\n", # config is so manifypods won't puke if no subdirs grep !$self->{SKIPHASH}{$_}, qw(static dynamic config); join "\n", @m; } 1; __END__ =head1 NAME ExtUtils::MakeMaker - Create a module Makefile =head1 SYNOPSIS use ExtUtils::MakeMaker; WriteMakefile( NAME => "Foo::Bar", VERSION_FROM => "lib/Foo/Bar.pm", ); =head1 DESCRIPTION This utility is designed to write a Makefile for an extension module from a Makefile.PL. It is based on the Makefile.SH model provided by Andy Dougherty and the perl5-porters. It splits the task of generating the Makefile into several subroutines that can be individually overridden. Each subroutine returns the text it wishes to have written to the Makefile. As there are various Make programs with incompatible syntax, which use operating system shells, again with incompatible syntax, it is important for users of this module to know which flavour of Make a Makefile has been written for so they'll use the correct one and won't have to face the possibly bewildering errors resulting from using the wrong one. On POSIX systems, that program will likely be GNU Make; on Microsoft Windows, it will be either Microsoft NMake, DMake or GNU Make. See the section on the L parameter for details. ExtUtils::MakeMaker (EUMM) is object oriented. Each directory below the current directory that contains a Makefile.PL is treated as a separate object. This makes it possible to write an unlimited number of Makefiles with a single invocation of WriteMakefile(). All inputs to WriteMakefile are Unicode characters, not just octets. EUMM seeks to handle all of these correctly. It is currently still not possible to portably use Unicode characters in module names, because this requires Perl to handle Unicode filenames, which is not yet the case on Windows. See L for details of the design and usage. =head2 How To Write A Makefile.PL See L. The long answer is the rest of the manpage :-) =head2 Default Makefile Behaviour The generated Makefile enables the user of the extension to invoke perl Makefile.PL # optionally "perl Makefile.PL verbose" make make test # optionally set TEST_VERBOSE=1 make install # See below The Makefile to be produced may be altered by adding arguments of the form C. E.g. perl Makefile.PL INSTALL_BASE=~ Other interesting targets in the generated Makefile are make config # to check if the Makefile is up-to-date make clean # delete local temp files (Makefile gets renamed) make realclean # delete derived files (including ./blib) make ci # check in all the files in the MANIFEST file make dist # see below the Distribution Support section =head2 make test MakeMaker checks for the existence of a file named F in the current directory, and if it exists it executes the script with the proper set of perl C<-I> options. MakeMaker also checks for any files matching glob("t/*.t"). It will execute all matching files in alphabetical order via the L module with the C<-I> switches set correctly. You can also organize your tests within subdirectories in the F directory. To do so, use the F directive in your I. For example, if you had tests in: t/foo t/foo/bar You could tell make to run tests in both of those directories with the following directives: test => {TESTS => 't/*/*.t t/*/*/*.t'} test => {TESTS => 't/foo/*.t t/foo/bar/*.t'} The first will run all test files in all first-level subdirectories and all subdirectories they contain. The second will run tests in only the F and F. If you'd like to see the raw output of your tests, set the C variable to true. make test TEST_VERBOSE=1 If you want to run particular test files, set the C variable. It is possible to use globbing with this mechanism. make test TEST_FILES='t/foobar.t t/dagobah*.t' Windows users who are using C should note that due to a bug in C, when specifying C you must use back-slashes instead of forward-slashes. nmake test TEST_FILES='t\foobar.t t\dagobah*.t' =head2 make testdb A useful variation of the above is the target C. It runs the test under the Perl debugger (see L). If the file F exists in the current directory, it is used for the test. If you want to debug some other testfile, set the C variable thusly: make testdb TEST_FILE=t/mytest.t By default the debugger is called using C<-d> option to perl. If you want to specify some other option, set the C variable: make testdb TESTDB_SW=-Dx =head2 make install make alone puts all relevant files into directories that are named by the macros INST_LIB, INST_ARCHLIB, INST_SCRIPT, INST_MAN1DIR and INST_MAN3DIR. All these default to something below ./blib if you are I building below the perl source directory. If you I building below the perl source, INST_LIB and INST_ARCHLIB default to ../../lib, and INST_SCRIPT is not defined. The I target of the generated Makefile copies the files found below each of the INST_* directories to their INSTALL* counterparts. Which counterparts are chosen depends on the setting of INSTALLDIRS according to the following table: INSTALLDIRS set to perl site vendor PERLPREFIX SITEPREFIX VENDORPREFIX INST_ARCHLIB INSTALLARCHLIB INSTALLSITEARCH INSTALLVENDORARCH INST_LIB INSTALLPRIVLIB INSTALLSITELIB INSTALLVENDORLIB INST_BIN INSTALLBIN INSTALLSITEBIN INSTALLVENDORBIN INST_SCRIPT INSTALLSCRIPT INSTALLSITESCRIPT INSTALLVENDORSCRIPT INST_MAN1DIR INSTALLMAN1DIR INSTALLSITEMAN1DIR INSTALLVENDORMAN1DIR INST_MAN3DIR INSTALLMAN3DIR INSTALLSITEMAN3DIR INSTALLVENDORMAN3DIR The INSTALL... macros in turn default to their %Config ($Config{installprivlib}, $Config{installarchlib}, etc.) counterparts. You can check the values of these variables on your system with perl '-V:install.*' And to check the sequence in which the library directories are searched by perl, run perl -le 'print join $/, @INC' Sometimes older versions of the module you're installing live in other directories in @INC. Because Perl loads the first version of a module it finds, not the newest, you might accidentally get one of these older versions even after installing a brand new version. To delete I (not simply older ones) set the C variable. make install UNINST=1 =head2 INSTALL_BASE INSTALL_BASE can be passed into Makefile.PL to change where your module will be installed. INSTALL_BASE is more like what everyone else calls "prefix" than PREFIX is. To have everything installed in your home directory, do the following. # Unix users, INSTALL_BASE=~ works fine perl Makefile.PL INSTALL_BASE=/path/to/your/home/dir Like PREFIX, it sets several INSTALL* attributes at once. Unlike PREFIX it is easy to predict where the module will end up. The installation pattern looks like this: INSTALLARCHLIB INSTALL_BASE/lib/perl5/$Config{archname} INSTALLPRIVLIB INSTALL_BASE/lib/perl5 INSTALLBIN INSTALL_BASE/bin INSTALLSCRIPT INSTALL_BASE/bin INSTALLMAN1DIR INSTALL_BASE/man/man1 INSTALLMAN3DIR INSTALL_BASE/man/man3 INSTALL_BASE in MakeMaker and C<--install_base> in Module::Build (as of 0.28) install to the same location. If you want MakeMaker and Module::Build to install to the same location simply set INSTALL_BASE and C<--install_base> to the same location. INSTALL_BASE was added in 6.31. =head2 PREFIX and LIB attribute PREFIX and LIB can be used to set several INSTALL* attributes in one go. Here's an example for installing into your home directory. # Unix users, PREFIX=~ works fine perl Makefile.PL PREFIX=/path/to/your/home/dir This will install all files in the module under your home directory, with man pages and libraries going into an appropriate place (usually ~/man and ~/lib). How the exact location is determined is complicated and depends on how your Perl was configured. INSTALL_BASE works more like what other build systems call "prefix" than PREFIX and we recommend you use that instead. Another way to specify many INSTALL directories with a single parameter is LIB. perl Makefile.PL LIB=~/lib This will install the module's architecture-independent files into ~/lib, the architecture-dependent files into ~/lib/$archname. Note, that in both cases the tilde expansion is done by MakeMaker, not by perl by default, nor by make. Conflicts between parameters LIB, PREFIX and the various INSTALL* arguments are resolved so that: =over 4 =item * setting LIB overrides any setting of INSTALLPRIVLIB, INSTALLARCHLIB, INSTALLSITELIB, INSTALLSITEARCH (and they are not affected by PREFIX); =item * without LIB, setting PREFIX replaces the initial C<$Config{prefix}> part of those INSTALL* arguments, even if the latter are explicitly set (but are set to still start with C<$Config{prefix}>). =back If the user has superuser privileges, and is not working on AFS or relatives, then the defaults for INSTALLPRIVLIB, INSTALLARCHLIB, INSTALLSCRIPT, etc. will be appropriate, and this incantation will be the best: perl Makefile.PL; make; make test make install make install by default writes some documentation of what has been done into the file C<$(INSTALLARCHLIB)/perllocal.pod>. This feature can be bypassed by calling make pure_install. =head2 AFS users will have to specify the installation directories as these most probably have changed since perl itself has been installed. They will have to do this by calling perl Makefile.PL INSTALLSITELIB=/afs/here/today \ INSTALLSCRIPT=/afs/there/now INSTALLMAN3DIR=/afs/for/manpages make Be careful to repeat this procedure every time you recompile an extension, unless you are sure the AFS installation directories are still valid. =head2 Static Linking of a new Perl Binary An extension that is built with the above steps is ready to use on systems supporting dynamic loading. On systems that do not support dynamic loading, any newly created extension has to be linked together with the available resources. MakeMaker supports the linking process by creating appropriate targets in the Makefile whenever an extension is built. You can invoke the corresponding section of the makefile with make perl That produces a new perl binary in the current directory with all extensions linked in that can be found in INST_ARCHLIB, SITELIBEXP, and PERL_ARCHLIB. To do that, MakeMaker writes a new Makefile, on UNIX, this is called F (may be system dependent). If you want to force the creation of a new perl, it is recommended that you delete this F, so the directories are searched through for linkable libraries again. The binary can be installed into the directory where perl normally resides on your machine with make inst_perl To produce a perl binary with a different name than C, either say perl Makefile.PL MAP_TARGET=myperl make myperl make inst_perl or say perl Makefile.PL make myperl MAP_TARGET=myperl make inst_perl MAP_TARGET=myperl In any case you will be prompted with the correct invocation of the C target that installs the new binary into INSTALLBIN. make inst_perl by default writes some documentation of what has been done into the file C<$(INSTALLARCHLIB)/perllocal.pod>. This can be bypassed by calling make pure_inst_perl. Warning: the inst_perl: target will most probably overwrite your existing perl binary. Use with care! Sometimes you might want to build a statically linked perl although your system supports dynamic loading. In this case you may explicitly set the linktype with the invocation of the Makefile.PL or make: perl Makefile.PL LINKTYPE=static # recommended or make LINKTYPE=static # works on most systems =head2 Determination of Perl Library and Installation Locations MakeMaker needs to know, or to guess, where certain things are located. Especially INST_LIB and INST_ARCHLIB (where to put the files during the make(1) run), PERL_LIB and PERL_ARCHLIB (where to read existing modules from), and PERL_INC (header files and C). Extensions may be built either using the contents of the perl source directory tree or from the installed perl library. The recommended way is to build extensions after you have run 'make install' on perl itself. You can do that in any directory on your hard disk that is not below the perl source tree. The support for extensions below the ext directory of the perl distribution is only good for the standard extensions that come with perl. If an extension is being built below the C directory of the perl source then MakeMaker will set PERL_SRC automatically (e.g., C<../..>). If PERL_SRC is defined and the extension is recognized as a standard extension, then other variables default to the following: PERL_INC = PERL_SRC PERL_LIB = PERL_SRC/lib PERL_ARCHLIB = PERL_SRC/lib INST_LIB = PERL_LIB INST_ARCHLIB = PERL_ARCHLIB If an extension is being built away from the perl source then MakeMaker will leave PERL_SRC undefined and default to using the installed copy of the perl library. The other variables default to the following: PERL_INC = $archlibexp/CORE PERL_LIB = $privlibexp PERL_ARCHLIB = $archlibexp INST_LIB = ./blib/lib INST_ARCHLIB = ./blib/arch If perl has not yet been installed then PERL_SRC can be defined on the command line as shown in the previous section. =head2 Which architecture dependent directory? If you don't want to keep the defaults for the INSTALL* macros, MakeMaker helps you to minimize the typing needed: the usual relationship between INSTALLPRIVLIB and INSTALLARCHLIB is determined by Configure at perl compilation time. MakeMaker supports the user who sets INSTALLPRIVLIB. If INSTALLPRIVLIB is set, but INSTALLARCHLIB not, then MakeMaker defaults the latter to be the same subdirectory of INSTALLPRIVLIB as Configure decided for the counterparts in %Config, otherwise it defaults to INSTALLPRIVLIB. The same relationship holds for INSTALLSITELIB and INSTALLSITEARCH. MakeMaker gives you much more freedom than needed to configure internal variables and get different results. It is worth mentioning that make(1) also lets you configure most of the variables that are used in the Makefile. But in the majority of situations this will not be necessary, and should only be done if the author of a package recommends it (or you know what you're doing). =head2 Using Attributes and Parameters The following attributes may be specified as arguments to WriteMakefile() or as NAME=VALUE pairs on the command line. Attributes that became available with later versions of MakeMaker are indicated. In order to maintain portability of attributes with older versions of MakeMaker you may want to use L with your C. =over 2 =item ABSTRACT One line description of the module. Will be included in PPD file. =item ABSTRACT_FROM Name of the file that contains the package description. MakeMaker looks for a line in the POD matching /^($package\s-\s)(.*)/. This is typically the first line in the "=head1 NAME" section. $2 becomes the abstract. =item AUTHOR Array of strings containing name (and email address) of package author(s). Is used in CPAN Meta files (META.yml or META.json) and PPD (Perl Package Description) files for PPM (Perl Package Manager). =item BINARY_LOCATION Used when creating PPD files for binary packages. It can be set to a full or relative path or URL to the binary archive for a particular architecture. For example: perl Makefile.PL BINARY_LOCATION=x86/Agent.tar.gz builds a PPD package that references a binary of the C package, located in the C directory relative to the PPD itself. =item BUILD_REQUIRES Available in version 6.55_03 and above. A hash of modules that are needed to build your module but not run it. This will go into the C field of your F and the C of the C field of your F. Defaults to C<<< { "ExtUtils::MakeMaker" => 0 } >>> if this attribute is not specified. The format is the same as PREREQ_PM. =item C Ref to array of *.c file names. Initialised from a directory scan and the values portion of the XS attribute hash. This is not currently used by MakeMaker but may be handy in Makefile.PLs. =item CCFLAGS String that will be included in the compiler call command line between the arguments INC and OPTIMIZE. =item CONFIG Arrayref. E.g. [qw(archname manext)] defines ARCHNAME & MANEXT from config.sh. MakeMaker will add to CONFIG the following values anyway: ar cc cccdlflags ccdlflags dlext dlsrc ld lddlflags ldflags libc lib_ext obj_ext ranlib sitelibexp sitearchexp so =item CONFIGURE CODE reference. The subroutine should return a hash reference. The hash may contain further attributes, e.g. {LIBS =E ...}, that have to be determined by some evaluation method. =item CONFIGURE_REQUIRES Available in version 6.52 and above. A hash of modules that are required to run Makefile.PL itself, but not to run your distribution. This will go into the C field of your F and the C of the C field of your F. Defaults to C<<< { "ExtUtils::MakeMaker" => 0 } >>> if this attribute is not specified. The format is the same as PREREQ_PM. =item DEFINE Something like C<"-DHAVE_UNISTD_H"> =item DESTDIR This is the root directory into which the code will be installed. It I. For example, if your code would normally go into F you could set DESTDIR=~/tmp/ and installation would go into F<~/tmp/usr/local/lib/perl>. This is primarily of use for people who repackage Perl modules. NOTE: Due to the nature of make, it is important that you put the trailing slash on your DESTDIR. F<~/tmp/> not F<~/tmp>. =item DIR Ref to array of subdirectories containing Makefile.PLs e.g. ['sdbm'] in ext/SDBM_File =item DISTNAME A safe filename for the package. Defaults to NAME below but with :: replaced with -. For example, Foo::Bar becomes Foo-Bar. =item DISTVNAME Your name for distributing the package with the version number included. This is used by 'make dist' to name the resulting archive file. Defaults to DISTNAME-VERSION. For example, version 1.04 of Foo::Bar becomes Foo-Bar-1.04. On some OS's where . has special meaning VERSION_SYM may be used in place of VERSION. =item DLEXT Specifies the extension of the module's loadable object. For example: DLEXT => 'unusual_ext', # Default value is $Config{so} NOTE: When using this option to alter the extension of a module's loadable object, it is also necessary that the module's pm file specifies the same change: local $DynaLoader::dl_dlext = 'unusual_ext'; =item DL_FUNCS Hashref of symbol names for routines to be made available as universal symbols. Each key/value pair consists of the package name and an array of routine names in that package. Used only under AIX, OS/2, VMS and Win32 at present. The routine names supplied will be expanded in the same way as XSUB names are expanded by the XS() macro. Defaults to {"$(NAME)" => ["boot_$(NAME)" ] } e.g. {"RPC" => [qw( boot_rpcb rpcb_gettime getnetconfigent )], "NetconfigPtr" => [ 'DESTROY'] } Please see the L documentation for more information about the DL_FUNCS, DL_VARS and FUNCLIST attributes. =item DL_VARS Array of symbol names for variables to be made available as universal symbols. Used only under AIX, OS/2, VMS and Win32 at present. Defaults to []. (e.g. [ qw(Foo_version Foo_numstreams Foo_tree ) ]) =item EXCLUDE_EXT Array of extension names to exclude when doing a static build. This is ignored if INCLUDE_EXT is present. Consult INCLUDE_EXT for more details. (e.g. [ qw( Socket POSIX ) ] ) This attribute may be most useful when specified as a string on the command line: perl Makefile.PL EXCLUDE_EXT='Socket Safe' =item EXE_FILES Ref to array of executable files. The files will be copied to the INST_SCRIPT directory. Make realclean will delete them from there again. If your executables start with something like #!perl or #!/usr/bin/perl MakeMaker will change this to the path of the perl 'Makefile.PL' was invoked with so the programs will be sure to run properly even if perl is not in /usr/bin/perl. =item FIRST_MAKEFILE The name of the Makefile to be produced. This is used for the second Makefile that will be produced for the MAP_TARGET. Defaults to 'Makefile' or 'Descrip.MMS' on VMS. (Note: we couldn't use MAKEFILE because dmake uses this for something else). =item FULLPERL Perl binary able to run this extension, load XS modules, etc... =item FULLPERLRUN Like PERLRUN, except it uses FULLPERL. =item FULLPERLRUNINST Like PERLRUNINST, except it uses FULLPERL. =item FUNCLIST This provides an alternate means to specify function names to be exported from the extension. Its value is a reference to an array of function names to be exported by the extension. These names are passed through unaltered to the linker options file. =item H Ref to array of *.h file names. Similar to C. =item IMPORTS This attribute is used to specify names to be imported into the extension. Takes a hash ref. It is only used on OS/2 and Win32. =item INC Include file dirs eg: C<"-I/usr/5include -I/path/to/inc"> =item INCLUDE_EXT Array of extension names to be included when doing a static build. MakeMaker will normally build with all of the installed extensions when doing a static build, and that is usually the desired behavior. If INCLUDE_EXT is present then MakeMaker will build only with those extensions which are explicitly mentioned. (e.g. [ qw( Socket POSIX ) ]) It is not necessary to mention DynaLoader or the current extension when filling in INCLUDE_EXT. If the INCLUDE_EXT is mentioned but is empty then only DynaLoader and the current extension will be included in the build. This attribute may be most useful when specified as a string on the command line: perl Makefile.PL INCLUDE_EXT='POSIX Socket Devel::Peek' =item INSTALLARCHLIB Used by 'make install', which copies files from INST_ARCHLIB to this directory if INSTALLDIRS is set to perl. =item INSTALLBIN Directory to install binary files (e.g. tkperl) into if INSTALLDIRS=perl. =item INSTALLDIRS Determines which of the sets of installation directories to choose: perl, site or vendor. Defaults to site. =item INSTALLMAN1DIR =item INSTALLMAN3DIR These directories get the man pages at 'make install' time if INSTALLDIRS=perl. Defaults to $Config{installman*dir}. If set to 'none', no man pages will be installed. =item INSTALLPRIVLIB Used by 'make install', which copies files from INST_LIB to this directory if INSTALLDIRS is set to perl. Defaults to $Config{installprivlib}. =item INSTALLSCRIPT Available in version 6.30_02 and above. Used by 'make install' which copies files from INST_SCRIPT to this directory if INSTALLDIRS=perl. =item INSTALLSITEARCH Used by 'make install', which copies files from INST_ARCHLIB to this directory if INSTALLDIRS is set to site (default). =item INSTALLSITEBIN Used by 'make install', which copies files from INST_BIN to this directory if INSTALLDIRS is set to site (default). =item INSTALLSITELIB Used by 'make install', which copies files from INST_LIB to this directory if INSTALLDIRS is set to site (default). =item INSTALLSITEMAN1DIR =item INSTALLSITEMAN3DIR These directories get the man pages at 'make install' time if INSTALLDIRS=site (default). Defaults to $(SITEPREFIX)/man/man$(MAN*EXT). If set to 'none', no man pages will be installed. =item INSTALLSITESCRIPT Used by 'make install' which copies files from INST_SCRIPT to this directory if INSTALLDIRS is set to site (default). =item INSTALLVENDORARCH Used by 'make install', which copies files from INST_ARCHLIB to this directory if INSTALLDIRS is set to vendor. Note that if you do not set this, the value of INSTALLVENDORLIB will be used, which is probably not what you want. =item INSTALLVENDORBIN Used by 'make install', which copies files from INST_BIN to this directory if INSTALLDIRS is set to vendor. =item INSTALLVENDORLIB Used by 'make install', which copies files from INST_LIB to this directory if INSTALLDIRS is set to vendor. =item INSTALLVENDORMAN1DIR =item INSTALLVENDORMAN3DIR These directories get the man pages at 'make install' time if INSTALLDIRS=vendor. Defaults to $(VENDORPREFIX)/man/man$(MAN*EXT). If set to 'none', no man pages will be installed. =item INSTALLVENDORSCRIPT Available in version 6.30_02 and above. Used by 'make install' which copies files from INST_SCRIPT to this directory if INSTALLDIRS is set to vendor. =item INST_ARCHLIB Same as INST_LIB for architecture dependent files. =item INST_BIN Directory to put real binary files during 'make'. These will be copied to INSTALLBIN during 'make install' =item INST_LIB Directory where we put library files of this extension while building it. =item INST_MAN1DIR Directory to hold the man pages at 'make' time =item INST_MAN3DIR Directory to hold the man pages at 'make' time =item INST_SCRIPT Directory where executable files should be installed during 'make'. Defaults to "./blib/script", just to have a dummy location during testing. make install will copy the files in INST_SCRIPT to INSTALLSCRIPT. =item LD Program to be used to link libraries for dynamic loading. Defaults to $Config{ld}. =item LDDLFLAGS Any special flags that might need to be passed to ld to create a shared library suitable for dynamic loading. It is up to the makefile to use it. (See L) Defaults to $Config{lddlflags}. =item LDFROM Defaults to "$(OBJECT)" and is used in the ld command to specify what files to link/load from (also see dynamic_lib below for how to specify ld flags) =item LIB LIB should only be set at C time but is allowed as a MakeMaker argument. It has the effect of setting both INSTALLPRIVLIB and INSTALLSITELIB to that value regardless any explicit setting of those arguments (or of PREFIX). INSTALLARCHLIB and INSTALLSITEARCH are set to the corresponding architecture subdirectory. =item LIBPERL_A The filename of the perllibrary that will be used together with this extension. Defaults to libperl.a. =item LIBS An anonymous array of alternative library specifications to be searched for (in order) until at least one library is found. E.g. 'LIBS' => ["-lgdbm", "-ldbm -lfoo", "-L/path -ldbm.nfs"] Mind, that any element of the array contains a complete set of arguments for the ld command. So do not specify 'LIBS' => ["-ltcl", "-ltk", "-lX11"] See ODBM_File/Makefile.PL for an example, where an array is needed. If you specify a scalar as in 'LIBS' => "-ltcl -ltk -lX11" MakeMaker will turn it into an array with one element. =item LICENSE Available in version 6.31 and above. The licensing terms of your distribution. Generally it's "perl_5" for the same license as Perl itself. See L for the list of options. Defaults to "unknown". =item LINKTYPE 'static' or 'dynamic' (default unless usedl=undef in config.sh). Should only be used to force static linking (also see linkext below). =item MAGICXS Available in version 6.8305 and above. When this is set to C<1>, C will be automagically derived from C. =item MAKE Available in version 6.30_01 and above. Variant of make you intend to run the generated Makefile with. This parameter lets Makefile.PL know what make quirks to account for when generating the Makefile. MakeMaker also honors the MAKE environment variable. This parameter takes precedence. Currently the only significant values are 'dmake' and 'nmake' for Windows users, instructing MakeMaker to generate a Makefile in the flavour of DMake ("Dennis Vadura's Make") or Microsoft NMake respectively. Defaults to $Config{make}, which may go looking for a Make program in your environment. How are you supposed to know what flavour of Make a Makefile has been generated for if you didn't specify a value explicitly? Search the generated Makefile for the definition of the MAKE variable, which is used to recursively invoke the Make utility. That will tell you what Make you're supposed to invoke the Makefile with. =item MAKEAPERL Boolean which tells MakeMaker that it should include the rules to make a perl. This is handled automatically as a switch by MakeMaker. The user normally does not need it. =item MAKEFILE_OLD When 'make clean' or similar is run, the $(FIRST_MAKEFILE) will be backed up at this location. Defaults to $(FIRST_MAKEFILE).old or $(FIRST_MAKEFILE)_old on VMS. =item MAN1PODS Hashref of pod-containing files. MakeMaker will default this to all EXE_FILES files that include POD directives. The files listed here will be converted to man pages and installed as was requested at Configure time. This hash should map POD files (or scripts containing POD) to the man file names under the C directory, as in the following example: MAN1PODS => { 'doc/command.pod' => 'blib/man1/command.1', 'scripts/script.pl' => 'blib/man1/script.1', } =item MAN3PODS Hashref that assigns to *.pm and *.pod files the files into which the manpages are to be written. MakeMaker parses all *.pod and *.pm files for POD directives. Files that contain POD will be the default keys of the MAN3PODS hashref. These will then be converted to man pages during C and will be installed during C. Example similar to MAN1PODS. =item MAP_TARGET If it is intended that a new perl binary be produced, this variable may hold a name for that binary. Defaults to perl =item META_ADD =item META_MERGE Available in version 6.46 and above. A hashref of items to add to the CPAN Meta file (F or F). They differ in how they behave if they have the same key as the default metadata. META_ADD will override the default value with its own. META_MERGE will merge its value with the default. Unless you want to override the defaults, prefer META_MERGE so as to get the advantage of any future defaults. Where prereqs are concerned, if META_MERGE is used, prerequisites are merged with their counterpart C argument (PREREQ_PM is merged into {prereqs}{runtime}{requires}, BUILD_REQUIRES into C<{prereqs}{build}{requires}>, CONFIGURE_REQUIRES into C<{prereqs}{configure}{requires}>, and TEST_REQUIRES into C<{prereqs}{test}{requires})>. When prereqs are specified with META_ADD, the only prerequisites added to the file come from the metadata, not C arguments. Note that these configuration options are only used for generating F and F -- they are NOT used for F and F. Therefore data in these fields should NOT be used for dynamic (user-side) configuration. By default CPAN Meta specification C<1.4> is used. In order to use CPAN Meta specification C<2.0>, indicate with C the version you want to use. META_MERGE => { "meta-spec" => { version => 2 }, resources => { repository => { type => 'git', url => 'git://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker.git', web => 'https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker', }, }, }, =item MIN_PERL_VERSION Available in version 6.48 and above. The minimum required version of Perl for this distribution. Either the 5.006001 or the 5.6.1 format is acceptable. =item MYEXTLIB If the extension links to a library that it builds, set this to the name of the library (see SDBM_File) =item NAME The package representing the distribution. For example, C or C. It will be used to derive information about the distribution such as the L, installation locations within the Perl library and where XS files will be looked for by default (see L). C I be a valid Perl package name and it I have an associated C<.pm> file. For example, C is a valid C and there must exist F. Any XS code should be in F unless stated otherwise. Your distribution B have a C. =item NEEDS_LINKING MakeMaker will figure out if an extension contains linkable code anywhere down the directory tree, and will set this variable accordingly, but you can speed it up a very little bit if you define this boolean variable yourself. =item NOECHO Command so make does not print the literal commands it's running. By setting it to an empty string you can generate a Makefile that prints all commands. Mainly used in debugging MakeMaker itself. Defaults to C<@>. =item NORECURS Boolean. Attribute to inhibit descending into subdirectories. =item NO_META When true, suppresses the generation and addition to the MANIFEST of the META.yml and META.json module meta-data files during 'make distdir'. Defaults to false. =item NO_MYMETA Available in version 6.57_02 and above. When true, suppresses the generation of MYMETA.yml and MYMETA.json module meta-data files during 'perl Makefile.PL'. Defaults to false. =item NO_PACKLIST Available in version 6.7501 and above. When true, suppresses the writing of C files for installs. Defaults to false. =item NO_PERLLOCAL Available in version 6.7501 and above. When true, suppresses the appending of installations to C. Defaults to false. =item NO_VC In general, any generated Makefile checks for the current version of MakeMaker and the version the Makefile was built under. If NO_VC is set, the version check is neglected. Do not write this into your Makefile.PL, use it interactively instead. =item OBJECT List of object files, defaults to '$(BASEEXT)$(OBJ_EXT)', but can be a long string or an array containing all object files, e.g. "tkpBind.o tkpButton.o tkpCanvas.o" or ["tkpBind.o", "tkpButton.o", "tkpCanvas.o"] (Where BASEEXT is the last component of NAME, and OBJ_EXT is $Config{obj_ext}.) =item OPTIMIZE Defaults to C<-O>. Set it to C<-g> to turn debugging on. The flag is passed to subdirectory makes. =item PERL Perl binary for tasks that can be done by miniperl. If it contains spaces or other shell metacharacters, it needs to be quoted in a way that protects them, since this value is intended to be inserted in a shell command line in the Makefile. E.g.: # Perl executable lives in "C:/Program Files/Perl/bin" # Normally you don't need to set this yourself! $ perl Makefile.PL PERL='"C:/Program Files/Perl/bin/perl.exe" -w' =item PERL_CORE Set only when MakeMaker is building the extensions of the Perl core distribution. =item PERLMAINCC The call to the program that is able to compile perlmain.c. Defaults to $(CC). =item PERL_ARCHLIB Same as for PERL_LIB, but for architecture dependent files. Used only when MakeMaker is building the extensions of the Perl core distribution (because normally $(PERL_ARCHLIB) is automatically in @INC, and adding it would get in the way of PERL5LIB). =item PERL_LIB Directory containing the Perl library to use. Used only when MakeMaker is building the extensions of the Perl core distribution (because normally $(PERL_LIB) is automatically in @INC, and adding it would get in the way of PERL5LIB). =item PERL_MALLOC_OK defaults to 0. Should be set to TRUE if the extension can work with the memory allocation routines substituted by the Perl malloc() subsystem. This should be applicable to most extensions with exceptions of those =over 4 =item * with bugs in memory allocations which are caught by Perl's malloc(); =item * which interact with the memory allocator in other ways than via malloc(), realloc(), free(), calloc(), sbrk() and brk(); =item * which rely on special alignment which is not provided by Perl's malloc(). =back B Neglecting to set this flag in I of the loaded extension nullifies many advantages of Perl's malloc(), such as better usage of system resources, error detection, memory usage reporting, catchable failure of memory allocations, etc. =item PERLPREFIX Directory under which core modules are to be installed. Defaults to $Config{installprefixexp}, falling back to $Config{installprefix}, $Config{prefixexp} or $Config{prefix} should $Config{installprefixexp} not exist. Overridden by PREFIX. =item PERLRUN Use this instead of $(PERL) when you wish to run perl. It will set up extra necessary flags for you. =item PERLRUNINST Use this instead of $(PERL) when you wish to run perl to work with modules. It will add things like -I$(INST_ARCH) and other necessary flags so perl can see the modules you're about to install. =item PERL_SRC Directory containing the Perl source code (use of this should be avoided, it may be undefined) =item PERM_DIR Available in version 6.51_01 and above. Desired permission for directories. Defaults to C<755>. =item PERM_RW Desired permission for read/writable files. Defaults to C<644>. =item PERM_RWX Desired permission for executable files. Defaults to C<755>. =item PL_FILES MakeMaker can run programs to generate files for you at build time. By default any file named *.PL (except Makefile.PL and Build.PL) in the top level directory will be assumed to be a Perl program and run passing its own basename in as an argument. This basename is actually a build target, and there is an intention, but not a requirement, that the *.PL file make the file passed to to as an argument. For example... perl foo.PL foo This behavior can be overridden by supplying your own set of files to search. PL_FILES accepts a hash ref, the key being the file to run and the value is passed in as the first argument when the PL file is run. PL_FILES => {'bin/foobar.PL' => 'bin/foobar'} PL_FILES => {'foo.PL' => 'foo.c'} Would run bin/foobar.PL like this: perl bin/foobar.PL bin/foobar If multiple files from one program are desired an array ref can be used. PL_FILES => {'bin/foobar.PL' => [qw(bin/foobar1 bin/foobar2)]} In this case the program will be run multiple times using each target file. perl bin/foobar.PL bin/foobar1 perl bin/foobar.PL bin/foobar2 If an output file depends on extra input files beside the script itself, a hash ref can be used in version 7.36 and above: PL_FILES => { 'foo.PL' => { 'foo.out' => 'foo.in', 'bar.out' => [qw(bar1.in bar2.in)], } In this case the extra input files will be passed to the program after the target file: perl foo.PL foo.out foo.in perl foo.PL bar.out bar1.in bar2.in PL files are normally run B pm_to_blib and include INST_LIB and INST_ARCH in their C<@INC>, so the just built modules can be accessed... unless the PL file is making a module (or anything else in PM) in which case it is run B pm_to_blib and does not include INST_LIB and INST_ARCH in its C<@INC>. This apparently odd behavior is there for backwards compatibility (and it's somewhat DWIM). The argument passed to the .PL is set up as a target to build in the Makefile. In other sections such as C you can specify a dependency on the filename/argument that the .PL is supposed (or will have, now that that is is a dependency) to generate. Note the file to be generated will still be generated and the .PL will still run even without an explicit dependency created by you, since the C target still depends on running all eligible to run.PL files. =item PM Hashref of .pm files and *.pl files to be installed. e.g. {'name_of_file.pm' => '$(INST_LIB)/install_as.pm'} By default this will include *.pm and *.pl and the files found in the PMLIBDIRS directories. Defining PM in the Makefile.PL will override PMLIBDIRS. =item PMLIBDIRS Ref to array of subdirectories containing library files. Defaults to [ 'lib', $(BASEEXT) ]. The directories will be scanned and I files they contain will be installed in the corresponding location in the library. A libscan() method can be used to alter the behaviour. Defining PM in the Makefile.PL will override PMLIBDIRS. (Where BASEEXT is the last component of NAME.) =item PM_FILTER A filter program, in the traditional Unix sense (input from stdin, output to stdout) that is passed on each .pm file during the build (in the pm_to_blib() phase). It is empty by default, meaning no filtering is done. You could use: PM_FILTER => 'perl -ne "print unless /^\\#/"', to remove all the leading comments on the fly during the build. In order to be as portable as possible, please consider using a Perl one-liner rather than Unix (or other) utilities, as above. The # is escaped for the Makefile, since what is going to be generated will then be: PM_FILTER = perl -ne "print unless /^\#/" Without the \ before the #, we'd have the start of a Makefile comment, and the macro would be incorrectly defined. You will almost certainly be better off using the C system, instead. See above, or the L entry. =item POLLUTE Release 5.005 grandfathered old global symbol names by providing preprocessor macros for extension source compatibility. As of release 5.6, these preprocessor definitions are not available by default. The POLLUTE flag specifies that the old names should still be defined: perl Makefile.PL POLLUTE=1 Please inform the module author if this is necessary to successfully install a module under 5.6 or later. =item PPM_INSTALL_EXEC Name of the executable used to run C below. (e.g. perl) =item PPM_INSTALL_SCRIPT Name of the script that gets executed by the Perl Package Manager after the installation of a package. =item PPM_UNINSTALL_EXEC Available in version 6.8502 and above. Name of the executable used to run C below. (e.g. perl) =item PPM_UNINSTALL_SCRIPT Available in version 6.8502 and above. Name of the script that gets executed by the Perl Package Manager before the removal of a package. =item PREFIX This overrides all the default install locations. Man pages, libraries, scripts, etc... MakeMaker will try to make an educated guess about where to place things under the new PREFIX based on your Config defaults. Failing that, it will fall back to a structure which should be sensible for your platform. If you specify LIB or any INSTALL* variables they will not be affected by the PREFIX. =item PREREQ_FATAL Bool. If this parameter is true, failing to have the required modules (or the right versions thereof) will be fatal. C will C instead of simply informing the user of the missing dependencies. It is I rare to have to use C. Its use by module authors is I and should never be used lightly. For dependencies that are required in order to run C, see C. Module installation tools have ways of resolving unmet dependencies but to do that they need a F. Using C breaks this. That's bad. Assuming you have good test coverage, your tests should fail with missing dependencies informing the user more strongly that something is wrong. You can write a F test which will simply check that your code compiles and stop "make test" prematurely if it doesn't. See L for more details. =item PREREQ_PM A hash of modules that are needed to run your module. The keys are the module names ie. Test::More, and the minimum version is the value. If the required version number is 0 any version will do. The versions given may be a Perl v-string (see L) or a range (see L). This will go into the C field of your F and the C of the C field of your F. PREREQ_PM => { # Require Test::More at least 0.47 "Test::More" => "0.47", # Require any version of Acme::Buffy "Acme::Buffy" => 0, } =item PREREQ_PRINT Bool. If this parameter is true, the prerequisites will be printed to stdout and MakeMaker will exit. The output format is an evalable hash ref. $PREREQ_PM = { 'A::B' => Vers1, 'C::D' => Vers2, ... }; If a distribution defines a minimal required perl version, this is added to the output as an additional line of the form: $MIN_PERL_VERSION = '5.008001'; If BUILD_REQUIRES is not empty, it will be dumped as $BUILD_REQUIRES hashref. =item PRINT_PREREQ RedHatism for C. The output format is different, though: perl(A::B)>=Vers1 perl(C::D)>=Vers2 ... A minimal required perl version, if present, will look like this: perl(perl)>=5.008001 =item SITEPREFIX Like PERLPREFIX, but only for the site install locations. Defaults to $Config{siteprefixexp}. Perls prior to 5.6.0 didn't have an explicit siteprefix in the Config. In those cases $Config{installprefix} will be used. Overridable by PREFIX =item SIGN Available in version 6.18 and above. When true, perform the generation and addition to the MANIFEST of the SIGNATURE file in the distdir during 'make distdir', via 'cpansign -s'. Note that you need to install the Module::Signature module to perform this operation. Defaults to false. =item SKIP Arrayref. E.g. [qw(name1 name2)] skip (do not write) sections of the Makefile. Caution! Do not use the SKIP attribute for the negligible speedup. It may seriously damage the resulting Makefile. Only use it if you really need it. =item TEST_REQUIRES Available in version 6.64 and above. A hash of modules that are needed to test your module but not run or build it. This will go into the C field of your F and the C of the C field of your F. The format is the same as PREREQ_PM. =item TYPEMAPS Ref to array of typemap file names. Use this when the typemaps are in some directory other than the current directory or when they are not named B. The last typemap in the list takes precedence. A typemap in the current directory has highest precedence, even if it isn't listed in TYPEMAPS. The default system typemap has lowest precedence. =item VENDORPREFIX Like PERLPREFIX, but only for the vendor install locations. Defaults to $Config{vendorprefixexp}. Overridable by PREFIX =item VERBINST If true, make install will be verbose =item VERSION Your version number for distributing the package. This defaults to 0.1. =item VERSION_FROM Instead of specifying the VERSION in the Makefile.PL you can let MakeMaker parse a file to determine the version number. The parsing routine requires that the file named by VERSION_FROM contains one single line to compute the version number. The first line in the file that contains something like a $VERSION assignment or C will be used. The following lines will be parsed o.k.: # Good package Foo::Bar 1.23; # 1.23 $VERSION = '1.00'; # 1.00 *VERSION = \'1.01'; # 1.01 ($VERSION) = q$Revision$ =~ /(\d+)/g; # The digits in $Revision$ $FOO::VERSION = '1.10'; # 1.10 *FOO::VERSION = \'1.11'; # 1.11 but these will fail: # Bad my $VERSION = '1.01'; local $VERSION = '1.02'; local $FOO::VERSION = '1.30'; (Putting C or C on the preceding line will work o.k.) "Version strings" are incompatible and should not be used. # Bad $VERSION = 1.2.3; $VERSION = v1.2.3; L objects are fine. As of MakeMaker 6.35 version.pm will be automatically loaded, but you must declare the dependency on version.pm. For compatibility with older MakeMaker you should load on the same line as $VERSION is declared. # All on one line use version; our $VERSION = qv(1.2.3); The file named in VERSION_FROM is not added as a dependency to Makefile. This is not really correct, but it would be a major pain during development to have to rewrite the Makefile for any smallish change in that file. If you want to make sure that the Makefile contains the correct VERSION macro after any change of the file, you would have to do something like depend => { Makefile => '$(VERSION_FROM)' } See attribute C below. =item VERSION_SYM A sanitized VERSION with . replaced by _. For places where . has special meaning (some filesystems, RCS labels, etc...) =item XS Hashref of .xs files. MakeMaker will default this. e.g. {'name_of_file.xs' => 'name_of_file.c'} The .c files will automatically be included in the list of files deleted by a make clean. =item XSBUILD Available in version 7.12 and above. Hashref with options controlling the operation of C: { xs => { all => { # options applying to all .xs files for this distribution }, 'lib/Class/Name/File' => { # specifically for this file DEFINE => '-Dfunktastic', # defines for only this file INC => "-I$funkyliblocation", # include flags for only this file # OBJECT => 'lib/Class/Name/File$(OBJ_EXT)', # default LDFROM => "lib/Class/Name/File\$(OBJ_EXT) $otherfile\$(OBJ_EXT)", # what's linked }, }, } Note C is the file-extension. More possibilities may arise in the future. Note that object names are specified without their XS extension. C defaults to the same as C. C defaults to, for C, just the XS filename with the extension replaced with the compiler-specific object-file extension. The distinction between C and C: C is the make target, so make will try to build it. However, C is what will actually be linked together to make the shared object or static library (SO/SL), so if you override it, make sure it includes what you want to make the final SO/SL, almost certainly including the XS basename with C<$(OBJ_EXT)> appended. =item XSMULTI Available in version 7.12 and above. When this is set to C<1>, multiple XS files may be placed under F next to their corresponding C<*.pm> files (this is essential for compiling with the correct C values). This feature should be considered experimental, and details of it may change. This feature was inspired by, and small portions of code copied from, L. Hopefully this feature will render that module mainly obsolete. =item XSOPT String of options to pass to xsubpp. This might include C<-C++> or C<-extern>. Do not include typemaps here; the TYPEMAP parameter exists for that purpose. =item XSPROTOARG May be set to C<-prototypes>, C<-noprototypes> or the empty string. The empty string is equivalent to the xsubpp default, or C<-noprototypes>. See the xsubpp documentation for details. MakeMaker defaults to the empty string. =item XS_VERSION Your version number for the .xs file of this package. This defaults to the value of the VERSION attribute. =back =head2 Additional lowercase attributes can be used to pass parameters to the methods which implement that part of the Makefile. Parameters are specified as a hash ref but are passed to the method as a hash. =over 2 =item clean {FILES => "*.xyz foo"} =item depend {ANY_TARGET => ANY_DEPENDENCY, ...} (ANY_TARGET must not be given a double-colon rule by MakeMaker.) =item dist {TARFLAGS => 'cvfF', COMPRESS => 'gzip', SUFFIX => '.gz', SHAR => 'shar -m', DIST_CP => 'ln', ZIP => '/bin/zip', ZIPFLAGS => '-rl', DIST_DEFAULT => 'private tardist' } If you specify COMPRESS, then SUFFIX should also be altered, as it is needed to tell make the target file of the compression. Setting DIST_CP to ln can be useful, if you need to preserve the timestamps on your files. DIST_CP can take the values 'cp', which copies the file, 'ln', which links the file, and 'best' which copies symbolic links and links the rest. Default is 'best'. =item dynamic_lib {ARMAYBE => 'ar', OTHERLDFLAGS => '...', INST_DYNAMIC_DEP => '...'} =item linkext {LINKTYPE => 'static', 'dynamic' or ''} NB: Extensions that have nothing but *.pm files had to say {LINKTYPE => ''} with Pre-5.0 MakeMakers. Since version 5.00 of MakeMaker such a line can be deleted safely. MakeMaker recognizes when there's nothing to be linked. =item macro {ANY_MACRO => ANY_VALUE, ...} =item postamble Anything put here will be passed to L if you have one. =item realclean {FILES => '$(INST_ARCHAUTODIR)/*.xyz'} =item test Specify the targets for testing. {TESTS => 't/*.t'} C can be used to include all directories recursively under C that contain C<.t> files. It will be ignored if you provide your own C attribute, defaults to false. {RECURSIVE_TEST_FILES=>1} This is supported since 6.76 =item tool_autosplit {MAXLEN => 8} =back =head2 Overriding MakeMaker Methods If you cannot achieve the desired Makefile behaviour by specifying attributes you may define private subroutines in the Makefile.PL. Each subroutine returns the text it wishes to have written to the Makefile. To override a section of the Makefile you can either say: sub MY::c_o { "new literal text" } or you can edit the default by saying something like: package MY; # so that "SUPER" works right sub c_o { my $inherited = shift->SUPER::c_o(@_); $inherited =~ s/old text/new text/; $inherited; } If you are running experiments with embedding perl as a library into other applications, you might find MakeMaker is not sufficient. You'd better have a look at L which is a collection of utilities for embedding. If you still need a different solution, try to develop another subroutine that fits your needs and submit the diffs to C For a complete description of all MakeMaker methods see L. Here is a simple example of how to add a new target to the generated Makefile: sub MY::postamble { return <<'MAKE_FRAG'; $(MYEXTLIB): sdbm/Makefile cd sdbm && $(MAKE) all MAKE_FRAG } =head2 The End Of Cargo Cult Programming WriteMakefile() now does some basic sanity checks on its parameters to protect against typos and malformatted values. This means some things which happened to work in the past will now throw warnings and possibly produce internal errors. Some of the most common mistakes: =over 2 =item C<< MAN3PODS => ' ' >> This is commonly used to suppress the creation of man pages. MAN3PODS takes a hash ref not a string, but the above worked by accident in old versions of MakeMaker. The correct code is C<< MAN3PODS => { } >>. =back =head2 Hintsfile support MakeMaker.pm uses the architecture-specific information from Config.pm. In addition it evaluates architecture specific hints files in a C directory. The hints files are expected to be named like their counterparts in C, but with an C<.pl> file name extension (eg. C). They are simply Ced by MakeMaker within the WriteMakefile() subroutine, and can be used to execute commands as well as to include special variables. The rules which hintsfile is chosen are the same as in Configure. The hintsfile is eval()ed immediately after the arguments given to WriteMakefile are stuffed into a hash reference $self but before this reference becomes blessed. So if you want to do the equivalent to override or create an attribute you would say something like $self->{LIBS} = ['-ldbm -lucb -lc']; =head2 Distribution Support For authors of extensions MakeMaker provides several Makefile targets. Most of the support comes from the L module, where additional documentation can be found. =over 4 =item make distcheck reports which files are below the build directory but not in the MANIFEST file and vice versa. (See L for details) =item make skipcheck reports which files are skipped due to the entries in the C file (See L for details) =item make distclean does a realclean first and then the distcheck. Note that this is not needed to build a new distribution as long as you are sure that the MANIFEST file is ok. =item make veryclean does a realclean first and then removes backup files such as C<*~>, C<*.bak>, C<*.old> and C<*.orig> =item make manifest rewrites the MANIFEST file, adding all remaining files found (See L for details) =item make distdir Copies all the files that are in the MANIFEST file to a newly created directory with the name C<$(DISTNAME)-$(VERSION)>. If that directory exists, it will be removed first. Additionally, it will create META.yml and META.json module meta-data file in the distdir and add this to the distdir's MANIFEST. You can shut this behavior off with the NO_META flag. =item make disttest Makes a distdir first, and runs a C, a make, and a make test in that directory. =item make tardist First does a distdir. Then a command $(PREOP) which defaults to a null command, followed by $(TO_UNIX), which defaults to a null command under UNIX, and will convert files in distribution directory to UNIX format otherwise. Next it runs C on that directory into a tarfile and deletes the directory. Finishes with a command $(POSTOP) which defaults to a null command. =item make dist Defaults to $(DIST_DEFAULT) which in turn defaults to tardist. =item make uutardist Runs a tardist first and uuencodes the tarfile. =item make shdist First does a distdir. Then a command $(PREOP) which defaults to a null command. Next it runs C on that directory into a sharfile and deletes the intermediate directory again. Finishes with a command $(POSTOP) which defaults to a null command. Note: For shdist to work properly a C program that can handle directories is mandatory. =item make zipdist First does a distdir. Then a command $(PREOP) which defaults to a null command. Runs C<$(ZIP) $(ZIPFLAGS)> on that directory into a zipfile. Then deletes that directory. Finishes with a command $(POSTOP) which defaults to a null command. =item make ci Does a $(CI) and a $(RCS_LABEL) on all files in the MANIFEST file. =back Customization of the dist targets can be done by specifying a hash reference to the dist attribute of the WriteMakefile call. The following parameters are recognized: CI ('ci -u') COMPRESS ('gzip --best') POSTOP ('@ :') PREOP ('@ :') TO_UNIX (depends on the system) RCS_LABEL ('rcs -q -Nv$(VERSION_SYM):') SHAR ('shar') SUFFIX ('.gz') TAR ('tar') TARFLAGS ('cvf') ZIP ('zip') ZIPFLAGS ('-r') An example: WriteMakefile( ...other options... dist => { COMPRESS => "bzip2", SUFFIX => ".bz2" } ); =head2 Module Meta-Data (META and MYMETA) Long plaguing users of MakeMaker based modules has been the problem of getting basic information about the module out of the sources I running the F and doing a bunch of messy heuristics on the resulting F. Over the years, it has become standard to keep this information in one or more CPAN Meta files distributed with each distribution. The original format of CPAN Meta files was L and the corresponding file was called F. In 2010, version 2 of the L was released, which mandates JSON format for the metadata in order to overcome certain compatibility issues between YAML serializers and to avoid breaking older clients unable to handle a new version of the spec. The L library is now standard for accessing old and new-style Meta files. If L is installed, MakeMaker will automatically generate F and F files for you and add them to your F as part of the 'distdir' target (and thus the 'dist' target). This is intended to seamlessly and rapidly populate CPAN with module meta-data. If you wish to shut this feature off, set the C C flag to true. At the 2008 QA Hackathon in Oslo, Perl module toolchain maintainers agreed to use the CPAN Meta format to communicate post-configuration requirements between toolchain components. These files, F and F, are generated when F generates a F (if L is installed). Clients like L or L will read these files to see what prerequisites must be fulfilled before building or testing the distribution. If you wish to shut this feature off, set the C C flag to true. =head2 Disabling an extension If some events detected in F imply that there is no way to create the Module, but this is a normal state of things, then you can create a F which does nothing, but succeeds on all the "usual" build targets. To do so, use use ExtUtils::MakeMaker qw(WriteEmptyMakefile); WriteEmptyMakefile(); instead of WriteMakefile(). This may be useful if other modules expect this module to be I OK, as opposed to I OK (say, this system-dependent module builds in a subdirectory of some other distribution, or is listed as a dependency in a CPAN::Bundle, but the functionality is supported by different means on the current architecture). =head2 Other Handy Functions =over 4 =item prompt my $value = prompt($message); my $value = prompt($message, $default); The C function provides an easy way to request user input used to write a makefile. It displays the $message as a prompt for input. If a $default is provided it will be used as a default. The function returns the $value selected by the user. If C detects that it is not running interactively and there is nothing on STDIN or if the PERL_MM_USE_DEFAULT environment variable is set to true, the $default will be used without prompting. This prevents automated processes from blocking on user input. If no $default is provided an empty string will be used instead. =item os_unsupported os_unsupported(); os_unsupported if $^O eq 'MSWin32'; The C function provides a way to correctly exit your C before calling C. It is essentially a C with the message "OS unsupported". This is supported since 7.26 =back =head2 Supported versions of Perl Please note that while this module works on Perl 5.6, it is no longer being routinely tested on 5.6 - the earliest Perl version being routinely tested, and expressly supported, is 5.8.1. However, patches to repair any breakage on 5.6 are still being accepted. =head1 ENVIRONMENT =over 4 =item PERL_MM_OPT Command line options used by Cnew()>, and thus by C. The string is split as the shell would, and the result is processed before any actual command line arguments are processed. PERL_MM_OPT='CCFLAGS="-Wl,-rpath -Wl,/foo/bar/lib" LIBS="-lwibble -lwobble"' =item PERL_MM_USE_DEFAULT If set to a true value then MakeMaker's prompt function will always return the default without waiting for user input. =item PERL_CORE Same as the PERL_CORE parameter. The parameter overrides this. =back =head1 SEE ALSO L is a pure-Perl alternative to MakeMaker which does not rely on make or any other external utility. It may be easier to extend to suit your needs. L is a minimal pure-Perl alternative to MakeMaker that follows the Build.PL protocol of Module::Build but without its complexity and cruft, implementing only the installation of the module and leaving authoring to L or other authoring tools. L is a (now discouraged) wrapper around MakeMaker which adds features not normally available. L and L are both modules to help you setup your distribution. L and L explain CPAN Meta files in detail. L makes it easy to install static, sometimes also referred to as 'shared' files. L helps accessing the shared files after installation. L helps when writing tests to use the shared files both before and after installation. L is an authoring tool which allows great customization and extensibility of the author experience, relying on the existing install tools like ExtUtils::MakeMaker only for installation. L is a Dist::Zilla bundle that greatly simplifies common usage. L is a minimal authoring tool that does the same things as Dist::Milla without the overhead of Dist::Zilla. =head1 AUTHORS Andy Dougherty C, Andreas KEnig C, Tim Bunce C. VMS support by Charles Bailey C. OS/2 support by Ilya Zakharevich C. Currently maintained by Michael G Schwern C Send patches and ideas to C. Send bug reports via http://rt.cpan.org/. Please send your generated Makefile along with your report. For more up-to-date information, see L. Repository available at L. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L =cut PK! °›Ý……perl5/ExtUtils/MM_MacOS.pmnuÏÃ6Ç$package ExtUtils::MM_MacOS; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; sub new { die 'MacOS Classic (MacPerl) is no longer supported by MakeMaker'; } =head1 NAME ExtUtils::MM_MacOS - once produced Makefiles for MacOS Classic =head1 SYNOPSIS # MM_MacOS no longer contains any code. This is just a stub. =head1 DESCRIPTION Once upon a time, MakeMaker could produce an approximation of a correct Makefile on MacOS Classic (MacPerl). Due to a lack of maintainers, this fell out of sync with the rest of MakeMaker and hadn't worked in years. Since there's little chance of it being repaired, MacOS Classic is fading away, and the code was icky to begin with, the code has been deleted to make maintenance easier. Anyone interested in resurrecting this file should pull the old version from the MakeMaker CVS repository and contact makemaker@perl.org. =cut 1; PK!х׃ƒperl5/ExtUtils/Command.pmnuÏÃ6Ç$package ExtUtils::Command; use 5.00503; use strict; use warnings; require Exporter; use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION); @ISA = qw(Exporter); @EXPORT = qw(cp rm_f rm_rf mv cat eqtime mkpath touch test_f test_d chmod dos2unix); $VERSION = '7.50'; $VERSION =~ tr/_//d; my $Is_VMS = $^O eq 'VMS'; my $Is_VMS_mode = $Is_VMS; my $Is_VMS_noefs = $Is_VMS; my $Is_Win32 = $^O eq 'MSWin32'; if( $Is_VMS ) { my $vms_unix_rpt; my $vms_efs; my $vms_case; if (eval { local $SIG{__DIE__}; local @INC = @INC; pop @INC if $INC[-1] eq '.'; require VMS::Feature; }) { $vms_unix_rpt = VMS::Feature::current("filename_unix_report"); $vms_efs = VMS::Feature::current("efs_charset"); $vms_case = VMS::Feature::current("efs_case_preserve"); } else { my $unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || ''; my $efs_charset = $ENV{'DECC$EFS_CHARSET'} || ''; my $efs_case = $ENV{'DECC$EFS_CASE_PRESERVE'} || ''; $vms_unix_rpt = $unix_rpt =~ /^[ET1]/i; $vms_efs = $efs_charset =~ /^[ET1]/i; $vms_case = $efs_case =~ /^[ET1]/i; } $Is_VMS_mode = 0 if $vms_unix_rpt; $Is_VMS_noefs = 0 if ($vms_efs); } =head1 NAME ExtUtils::Command - utilities to replace common UNIX commands in Makefiles etc. =head1 SYNOPSIS perl -MExtUtils::Command -e cat files... > destination perl -MExtUtils::Command -e mv source... destination perl -MExtUtils::Command -e cp source... destination perl -MExtUtils::Command -e touch files... perl -MExtUtils::Command -e rm_f files... perl -MExtUtils::Command -e rm_rf directories... perl -MExtUtils::Command -e mkpath directories... perl -MExtUtils::Command -e eqtime source destination perl -MExtUtils::Command -e test_f file perl -MExtUtils::Command -e test_d directory perl -MExtUtils::Command -e chmod mode files... ... =head1 DESCRIPTION The module is used to replace common UNIX commands. In all cases the functions work from @ARGV rather than taking arguments. This makes them easier to deal with in Makefiles. Call them like this: perl -MExtUtils::Command -e some_command some files to work on and I like this: perl -MExtUtils::Command -e 'some_command qw(some files to work on)' For that use L. Filenames with * and ? will be glob expanded. =head2 FUNCTIONS =over 4 =cut # VMS uses % instead of ? to mean "one character" my $wild_regex = $Is_VMS ? '*%' : '*?'; sub expand_wildcards { @ARGV = map(/[$wild_regex]/o ? glob($_) : $_,@ARGV); } =item cat cat file ... Concatenates all files mentioned on command line to STDOUT. =cut sub cat () { expand_wildcards(); print while (<>); } =item eqtime eqtime source destination Sets modified time of destination to that of source. =cut sub eqtime { my ($src,$dst) = @ARGV; local @ARGV = ($dst); touch(); # in case $dst doesn't exist utime((stat($src))[8,9],$dst); } =item rm_rf rm_rf files or directories ... Removes files and directories - recursively (even if readonly) =cut sub rm_rf { expand_wildcards(); require File::Path; File::Path::rmtree([grep -e $_,@ARGV],0,0); } =item rm_f rm_f file ... Removes files (even if readonly) =cut sub rm_f { expand_wildcards(); foreach my $file (@ARGV) { next unless -f $file; next if _unlink($file); chmod(0777, $file); next if _unlink($file); require Carp; Carp::carp("Cannot delete $file: $!"); } } sub _unlink { my $files_unlinked = 0; foreach my $file (@_) { my $delete_count = 0; $delete_count++ while unlink $file; $files_unlinked++ if $delete_count; } return $files_unlinked; } =item touch touch file ... Makes files exist, with current timestamp =cut sub touch { my $t = time; expand_wildcards(); foreach my $file (@ARGV) { open(FILE,">>$file") || die "Cannot write $file:$!"; close(FILE); utime($t,$t,$file); } } =item mv mv source_file destination_file mv source_file source_file destination_dir Moves source to destination. Multiple sources are allowed if destination is an existing directory. Returns true if all moves succeeded, false otherwise. =cut sub mv { expand_wildcards(); my @src = @ARGV; my $dst = pop @src; if (@src > 1 && ! -d $dst) { require Carp; Carp::croak("Too many arguments"); } require File::Copy; my $nok = 0; foreach my $src (@src) { $nok ||= !File::Copy::move($src,$dst); } return !$nok; } =item cp cp source_file destination_file cp source_file source_file destination_dir Copies sources to the destination. Multiple sources are allowed if destination is an existing directory. Returns true if all copies succeeded, false otherwise. =cut sub cp { expand_wildcards(); my @src = @ARGV; my $dst = pop @src; if (@src > 1 && ! -d $dst) { require Carp; Carp::croak("Too many arguments"); } require File::Copy; my $nok = 0; foreach my $src (@src) { $nok ||= !File::Copy::copy($src,$dst); # Win32 does not update the mod time of a copied file, just the # created time which make does not look at. utime(time, time, $dst) if $Is_Win32; } return $nok; } =item chmod chmod mode files ... Sets UNIX like permissions 'mode' on all the files. e.g. 0666 =cut sub chmod { local @ARGV = @ARGV; my $mode = shift(@ARGV); expand_wildcards(); if( $Is_VMS_mode && $Is_VMS_noefs) { require File::Spec; foreach my $idx (0..$#ARGV) { my $path = $ARGV[$idx]; next unless -d $path; # chmod 0777, [.foo.bar] doesn't work on VMS, you have to do # chmod 0777, [.foo]bar.dir my @dirs = File::Spec->splitdir( $path ); $dirs[-1] .= '.dir'; $path = File::Spec->catfile(@dirs); $ARGV[$idx] = $path; } } chmod(oct $mode,@ARGV) || die "Cannot chmod ".join(' ',$mode,@ARGV).":$!"; } =item mkpath mkpath directory ... Creates directories, including any parent directories. =cut sub mkpath { expand_wildcards(); require File::Path; File::Path::mkpath([@ARGV],0,0777); } =item test_f test_f file Tests if a file exists. I with 0 if it does, 1 if it does not (ie. shell's idea of true and false). =cut sub test_f { exit(-f $ARGV[0] ? 0 : 1); } =item test_d test_d directory Tests if a directory exists. I with 0 if it does, 1 if it does not (ie. shell's idea of true and false). =cut sub test_d { exit(-d $ARGV[0] ? 0 : 1); } =item dos2unix dos2unix files or dirs ... Converts DOS and OS/2 linefeeds to Unix style recursively. =cut sub dos2unix { require File::Find; File::Find::find(sub { return if -d; return unless -w _; return unless -r _; return if -B _; local $\; my $orig = $_; my $temp = '.dos2unix_tmp'; open ORIG, $_ or do { warn "dos2unix can't open $_: $!"; return }; open TEMP, ">$temp" or do { warn "dos2unix can't create .dos2unix_tmp: $!"; return }; binmode ORIG; binmode TEMP; while (my $line = ) { $line =~ s/\015\012/\012/g; print TEMP $line; } close ORIG; close TEMP; rename $temp, $orig; }, @ARGV); } =back =head1 SEE ALSO Shell::Command which is these same functions but take arguments normally. =head1 AUTHOR Nick Ing-Simmons C Maintained by Michael G Schwern C within the ExtUtils-MakeMaker package and, as a separate CPAN package, by Randy Kobes C. =cut PK!ÈßÛ^LL$perl5/ExtUtils/Typemaps/OutputMap.pmnuÏÃ6Ç$package ExtUtils::Typemaps::OutputMap; use 5.006001; use strict; use warnings; our $VERSION = '3.35'; =head1 NAME ExtUtils::Typemaps::OutputMap - Entry in the OUTPUT section of a typemap =head1 SYNOPSIS use ExtUtils::Typemaps; ... my $output = $typemap->get_output_map('T_NV'); my $code = $output->code(); $output->code("..."); =head1 DESCRIPTION Refer to L for details. =head1 METHODS =cut =head2 new Requires C and C parameters. =cut sub new { my $prot = shift; my $class = ref($prot)||$prot; my %args = @_; if (!ref($prot)) { if (not defined $args{xstype} or not defined $args{code}) { die("Need xstype and code parameters"); } } my $self = bless( (ref($prot) ? {%$prot} : {}) => $class ); $self->{xstype} = $args{xstype} if defined $args{xstype}; $self->{code} = $args{code} if defined $args{code}; $self->{code} =~ s/^(?=\S)/\t/mg; return $self; } =head2 code Returns or sets the OUTPUT mapping code for this entry. =cut sub code { $_[0]->{code} = $_[1] if @_ > 1; return $_[0]->{code}; } =head2 xstype Returns the name of the XS type of the OUTPUT map. =cut sub xstype { return $_[0]->{xstype}; } =head2 cleaned_code Returns a cleaned-up copy of the code to which certain transformations have been applied to make it more ANSI compliant. =cut sub cleaned_code { my $self = shift; my $code = $self->code; # Move C pre-processor instructions to column 1 to be strictly ANSI # conformant. Some pre-processors are fussy about this. $code =~ s/^\s+#/#/mg; $code =~ s/\s*\z/\n/; return $code; } =head2 targetable This is an obscure but effective optimization that used to live in C directly. Not implementing it should never result in incorrect use of typemaps, just less efficient code. In a nutshell, this will check whether the output code involves calling C, C, C, C or C to set the special C<$arg> placeholder to a new value B. If that is the case, the code is eligible for using the C-related macros to optimize this. Thus the name of the method: C. If this optimization is applicable, C will emit a C definition at the start of the generated XSUB code, and type (see below) dependent code to set C and push it on the stack at the end of the generated XSUB code. If the optimization can not be applied, this returns undef. If it can be applied, this method returns a hash reference containing the following information: type: Any of the characters i, u, n, p with_size: Bool indicating whether this is the sv_setpvn variant what: The code that actually evaluates to the output scalar what_size: If "with_size", this has the string length (as code, not constant, including leading comma) =cut sub targetable { my $self = shift; return $self->{targetable} if exists $self->{targetable}; our $bal; # ()-balanced $bal = qr[ (?: (?>[^()]+) | \( (??{ $bal }) \) )* ]x; my $bal_no_comma = qr[ (?: (?>[^(),]+) | \( (??{ $bal }) \) )+ ]x; # matches variations on (SV*) my $sv_cast = qr[ (?: \( \s* SV \s* \* \s* \) \s* )? ]x; my $size = qr[ # Third arg (to setpvn) , \s* (??{ $bal }) ]xo; my $code = $self->code; # We can still bootstrap compile 're', because in code re.pm is # available to miniperl, and does not attempt to load the XS code. use re 'eval'; my ($type, $with_size, $arg, $sarg) = ($code =~ m[^ \s+ sv_set([iunp])v(n)? # Type, is_setpvn \s* \( \s* $sv_cast \$arg \s* , \s* ( $bal_no_comma ) # Set from ( $size )? # Possible sizeof set-from \s* \) \s* ; \s* $ ]xo ); my $rv = undef; if ($type) { $rv = { type => $type, with_size => $with_size, what => $arg, what_size => $sarg, }; } $self->{targetable} = $rv; return $rv; } =head1 SEE ALSO L =head1 AUTHOR Steffen Mueller C<> =head1 COPYRIGHT & LICENSE Copyright 2009, 2010, 2011, 2012 Steffen Mueller This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK!÷�½¯¢¢#perl5/ExtUtils/Typemaps/InputMap.pmnuÏÃ6Ç$package ExtUtils::Typemaps::InputMap; use 5.006001; use strict; use warnings; our $VERSION = '3.35'; =head1 NAME ExtUtils::Typemaps::InputMap - Entry in the INPUT section of a typemap =head1 SYNOPSIS use ExtUtils::Typemaps; ... my $input = $typemap->get_input_map('T_NV'); my $code = $input->code(); $input->code("..."); =head1 DESCRIPTION Refer to L for details. =head1 METHODS =cut =head2 new Requires C and C parameters. =cut sub new { my $prot = shift; my $class = ref($prot)||$prot; my %args = @_; if (!ref($prot)) { if (not defined $args{xstype} or not defined $args{code}) { die("Need xstype and code parameters"); } } my $self = bless( (ref($prot) ? {%$prot} : {}) => $class ); $self->{xstype} = $args{xstype} if defined $args{xstype}; $self->{code} = $args{code} if defined $args{code}; $self->{code} =~ s/^(?=\S)/\t/mg; return $self; } =head2 code Returns or sets the INPUT mapping code for this entry. =cut sub code { $_[0]->{code} = $_[1] if @_ > 1; return $_[0]->{code}; } =head2 xstype Returns the name of the XS type of the INPUT map. =cut sub xstype { return $_[0]->{xstype}; } =head2 cleaned_code Returns a cleaned-up copy of the code to which certain transformations have been applied to make it more ANSI compliant. =cut sub cleaned_code { my $self = shift; my $code = $self->code; $code =~ s/(?:;+\s*|;*\s+)\z//s; # Move C pre-processor instructions to column 1 to be strictly ANSI # conformant. Some pre-processors are fussy about this. $code =~ s/^\s+#/#/mg; $code =~ s/\s*\z/\n/; return $code; } =head1 SEE ALSO L =head1 AUTHOR Steffen Mueller C<> =head1 COPYRIGHT & LICENSE Copyright 2009, 2010, 2011, 2012 Steffen Mueller This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK!HËØX%%perl5/ExtUtils/Typemaps/Type.pmnuÏÃ6Ç$package ExtUtils::Typemaps::Type; use 5.006001; use strict; use warnings; require ExtUtils::Typemaps; our $VERSION = '3.35'; =head1 NAME ExtUtils::Typemaps::Type - Entry in the TYPEMAP section of a typemap =head1 SYNOPSIS use ExtUtils::Typemaps; ... my $type = $typemap->get_type_map('char*'); my $input = $typemap->get_input_map($type->xstype); =head1 DESCRIPTION Refer to L for details. Object associates C with C, which is the index into the in- and output mapping tables. =head1 METHODS =cut =head2 new Requires C and C parameters. Optionally takes C parameter. =cut sub new { my $prot = shift; my $class = ref($prot)||$prot; my %args = @_; if (!ref($prot)) { if (not defined $args{xstype} or not defined $args{ctype}) { die("Need xstype and ctype parameters"); } } my $self = bless( (ref($prot) ? {%$prot} : {proto => ''}) => $class ); $self->{xstype} = $args{xstype} if defined $args{xstype}; $self->{ctype} = $args{ctype} if defined $args{ctype}; $self->{tidy_ctype} = ExtUtils::Typemaps::tidy_type($self->{ctype}); $self->{proto} = $args{'prototype'} if defined $args{'prototype'}; return $self; } =head2 proto Returns or sets the prototype. =cut sub proto { $_[0]->{proto} = $_[1] if @_ > 1; return $_[0]->{proto}; } =head2 xstype Returns the name of the XS type that this C type is associated to. =cut sub xstype { return $_[0]->{xstype}; } =head2 ctype Returns the name of the C type as it was set on construction. =cut sub ctype { return defined($_[0]->{ctype}) ? $_[0]->{ctype} : $_[0]->{tidy_ctype}; } =head2 tidy_ctype Returns the canonicalized name of the C type. =cut sub tidy_ctype { return $_[0]->{tidy_ctype}; } =head1 SEE ALSO L =head1 AUTHOR Steffen Mueller C<> =head1 COPYRIGHT & LICENSE Copyright 2009, 2010, 2011, 2012 Steffen Mueller This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK!ÙûB%%perl5/ExtUtils/Typemaps/Cmd.pmnuÏÃ6Ç$package ExtUtils::Typemaps::Cmd; use 5.006001; use strict; use warnings; our $VERSION = '3.35'; use ExtUtils::Typemaps; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(embeddable_typemap); our %EXPORT_TAGS = (all => \@EXPORT); sub embeddable_typemap { my @tms = @_; # Get typemap objects my @tm_objs = map [$_, _intuit_typemap_source($_)], @tms; # merge or short-circuit my $final_tm; if (@tm_objs == 1) { # just one, merge would be pointless $final_tm = shift(@tm_objs)->[1]; } else { # multiple, need merge $final_tm = ExtUtils::Typemaps->new; foreach my $other_tm (@tm_objs) { my ($tm_ident, $tm_obj) = @$other_tm; eval { $final_tm->merge(typemap => $tm_obj); 1 } or do { my $err = $@ || 'Zombie error'; die "Failed to merge typ"; } } } # stringify for embedding return $final_tm->as_embedded_typemap(); } sub _load_module { my $name = shift; return eval "require $name; 1"; } SCOPE: { my %sources = ( module => sub { my $ident = shift; my $tm; if (/::/) { # looks like FQ module name, try that first foreach my $module ($ident, "ExtUtils::Typemaps::$ident") { if (_load_module($module)) { eval { $tm = $module->new } and return $tm; } } } else { foreach my $module ("ExtUtils::Typemaps::$ident", "$ident") { if (_load_module($module)) { eval { $tm = $module->new } and return $tm; } } } return(); }, file => sub { my $ident = shift; return unless -e $ident and -r _; return ExtUtils::Typemaps->new(file => $ident); }, ); # Try to find typemap either from module or file sub _intuit_typemap_source { my $identifier = shift; my @locate_attempts; if ($identifier =~ /::/ || $identifier !~ /[^\w_]/) { @locate_attempts = qw(module file); } else { @locate_attempts = qw(file module); } foreach my $source (@locate_attempts) { my $tm = $sources{$source}->($identifier); return $tm if defined $tm; } die "Unable to find typemap for '$identifier': " . "Tried to load both as file or module and failed.\n"; } } # end SCOPE =head1 NAME ExtUtils::Typemaps::Cmd - Quick commands for handling typemaps =head1 SYNOPSIS From XS: INCLUDE_COMMAND: $^X -MExtUtils::Typemaps::Cmd \ -e "print embeddable_typemap(q{Excommunicated})" Loads C, instantiates an object, and dumps it as an embeddable typemap for use directly in your XS file. =head1 DESCRIPTION This is a helper module for L for quick one-liners, specifically for inclusion of shared typemaps that live on CPAN into an XS file (see SYNOPSIS). For this reason, the following functions are exported by default: =head1 EXPORTED FUNCTIONS =head2 embeddable_typemap Given a list of identifiers, C tries to load typemaps from a file of the given name(s), or from a module that is an C subclass. Returns a string representation of the merged typemaps that can be included verbatim into XS. Example: print embeddable_typemap( "Excommunicated", "ExtUtils::Typemaps::Basic", "./typemap" ); This will try to load a module C and use it as an C subclass. If that fails, it'll try loading C as a module, if that fails, it'll try to read a file called F. It'll work similarly for the second argument, but the third will be loaded as a file first. After loading all typemap files or modules, it will merge them in the specified order and dump the result as an embeddable typemap. =head1 SEE ALSO L L =head1 AUTHOR Steffen Mueller C<> =head1 COPYRIGHT & LICENSE Copyright 2012 Steffen Mueller This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK!ˆ²Ht· · perl5/ExtUtils/MM_VMS.pmnuÏÃ6Ç$package ExtUtils::MM_VMS; use strict; use warnings; use ExtUtils::MakeMaker::Config; require Exporter; BEGIN { # so we can compile the thing on non-VMS platforms. if( $^O eq 'VMS' ) { require VMS::Filespec; VMS::Filespec->import; } } use File::Basename; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Any; require ExtUtils::MM_Unix; our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix ); use ExtUtils::MakeMaker qw($Verbose neatvalue _sprintf562); our $Revision = $ExtUtils::MakeMaker::Revision; =head1 NAME ExtUtils::MM_VMS - methods to override UN*X behaviour in ExtUtils::MakeMaker =head1 SYNOPSIS Do not use this directly. Instead, use ExtUtils::MM and it will figure out which MM_* class to use for you. =head1 DESCRIPTION See L for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. =head2 Methods always loaded =over 4 =item wraplist Converts a list into a string wrapped at approximately 80 columns. =cut sub wraplist { my($self) = shift; my($line,$hlen) = ('',0); foreach my $word (@_) { # Perl bug -- seems to occasionally insert extra elements when # traversing array (scalar(@array) doesn't show them, but # foreach(@array) does) (5.00307) next unless $word =~ /\w/; $line .= ' ' if length($line); if ($hlen > 80) { $line .= "\\\n\t"; $hlen = 0; } $line .= $word; $hlen += length($word) + 2; } $line; } # This isn't really an override. It's just here because ExtUtils::MM_VMS # appears in @MM::ISA before ExtUtils::Liblist::Kid, so if there isn't an ext() # in MM_VMS, then AUTOLOAD is called, and bad things happen. So, we just # mimic inheritance here and hand off to ExtUtils::Liblist::Kid. # XXX This hackery will die soon. --Schwern sub ext { require ExtUtils::Liblist::Kid; goto &ExtUtils::Liblist::Kid::ext; } =back =head2 Methods Those methods which override default MM_Unix methods are marked "(override)", while methods unique to MM_VMS are marked "(specific)". For overridden methods, documentation is limited to an explanation of why this method overrides the MM_Unix method; see the L documentation for more details. =over 4 =item guess_name (override) Try to determine name of extension being built. We begin with the name of the current directory. Since VMS filenames are case-insensitive, however, we look for a F<.pm> file whose name matches that of the current directory (presumably the 'main' F<.pm> file for this extension), and try to find a C statement from which to obtain the Mixed::Case package name. =cut sub guess_name { my($self) = @_; my($defname,$defpm,@pm,%xs); local *PM; $defname = basename(fileify($ENV{'DEFAULT'})); $defname =~ s![\d\-_]*\.dir.*$!!; # Clip off .dir;1 suffix, and package version $defpm = $defname; # Fallback in case for some reason a user has copied the files for an # extension into a working directory whose name doesn't reflect the # extension's name. We'll use the name of a unique .pm file, or the # first .pm file with a matching .xs file. if (not -e "${defpm}.pm") { @pm = glob('*.pm'); s/.pm$// for @pm; if (@pm == 1) { ($defpm = $pm[0]) =~ s/.pm$//; } elsif (@pm) { %xs = map { s/.xs$//; ($_,1) } glob('*.xs'); ## no critic if (keys %xs) { foreach my $pm (@pm) { $defpm = $pm, last if exists $xs{$pm}; } } } } if (open(my $pm, '<', "${defpm}.pm")){ while (<$pm>) { if (/^\s*package\s+([^;]+)/i) { $defname = $1; last; } } print "Warning (non-fatal): Couldn't find package name in ${defpm}.pm;\n\t", "defaulting package name to $defname\n" if eof($pm); close $pm; } else { print "Warning (non-fatal): Couldn't find ${defpm}.pm;\n\t", "defaulting package name to $defname\n"; } $defname =~ s#[\d.\-_]+$##; $defname; } =item find_perl (override) Use VMS file specification syntax and CLI commands to find and invoke Perl images. =cut sub find_perl { my($self, $ver, $names, $dirs, $trace) = @_; my($vmsfile,@sdirs,@snames,@cand); my($rslt); my($inabs) = 0; local *TCF; if( $self->{PERL_CORE} ) { # Check in relative directories first, so we pick up the current # version of Perl if we're running MakeMaker as part of the main build. @sdirs = sort { my($absa) = $self->file_name_is_absolute($a); my($absb) = $self->file_name_is_absolute($b); if ($absa && $absb) { return $a cmp $b } else { return $absa ? 1 : ($absb ? -1 : ($a cmp $b)); } } @$dirs; # Check miniperl before perl, and check names likely to contain # version numbers before "generic" names, so we pick up an # executable that's less likely to be from an old installation. @snames = sort { my($ba) = $a =~ m!([^:>\]/]+)$!; # basename my($bb) = $b =~ m!([^:>\]/]+)$!; my($ahasdir) = (length($a) - length($ba) > 0); my($bhasdir) = (length($b) - length($bb) > 0); if ($ahasdir and not $bhasdir) { return 1; } elsif ($bhasdir and not $ahasdir) { return -1; } else { $bb =~ /\d/ <=> $ba =~ /\d/ or substr($ba,0,1) cmp substr($bb,0,1) or length($bb) <=> length($ba) } } @$names; } else { @sdirs = @$dirs; @snames = @$names; } # Image names containing Perl version use '_' instead of '.' under VMS s/\.(\d+)$/_$1/ for @snames; if ($trace >= 2){ print "Looking for perl $ver by these names:\n"; print "\t@snames,\n"; print "in these dirs:\n"; print "\t@sdirs\n"; } foreach my $dir (@sdirs){ next unless defined $dir; # $self->{PERL_SRC} may be undefined $inabs++ if $self->file_name_is_absolute($dir); if ($inabs == 1) { # We've covered relative dirs; everything else is an absolute # dir (probably an installed location). First, we'll try # potential command names, to see whether we can avoid a long # MCR expression. foreach my $name (@snames) { push(@cand,$name) if $name =~ /^[\w\-\$]+$/; } $inabs++; # Should happen above in next $dir, but just in case... } foreach my $name (@snames){ push @cand, ($name !~ m![/:>\]]!) ? $self->catfile($dir,$name) : $self->fixpath($name,0); } } foreach my $name (@cand) { print "Checking $name\n" if $trace >= 2; # If it looks like a potential command, try it without the MCR if ($name =~ /^[\w\-\$]+$/) { open(my $tcf, ">", "temp_mmvms.com") or die('unable to open temp file'); print $tcf "\$ set message/nofacil/nosever/noident/notext\n"; print $tcf "\$ $name -e \"require $ver; print \"\"VER_OK\\n\"\"\"\n"; close $tcf; $rslt = `\@temp_mmvms.com` ; unlink('temp_mmvms.com'); if ($rslt =~ /VER_OK/) { print "Using PERL=$name\n" if $trace; return $name; } } next unless $vmsfile = $self->maybe_command($name); $vmsfile =~ s/;[\d\-]*$//; # Clip off version number; we can use a newer version as well print "Executing $vmsfile\n" if ($trace >= 2); open(my $tcf, '>', "temp_mmvms.com") or die('unable to open temp file'); print $tcf "\$ set message/nofacil/nosever/noident/notext\n"; print $tcf "\$ mcr $vmsfile -e \"require $ver; print \"\"VER_OK\\n\"\"\" \n"; close $tcf; $rslt = `\@temp_mmvms.com`; unlink('temp_mmvms.com'); if ($rslt =~ /VER_OK/) { print "Using PERL=MCR $vmsfile\n" if $trace; return "MCR $vmsfile"; } } print "Unable to find a perl $ver (by these names: @$names, in these dirs: @$dirs)\n"; 0; # false and not empty } =item _fixin_replace_shebang (override) Helper routine for L<< MM->fixin()|ExtUtils::MM_Unix/fixin >>, overridden because there's no such thing as an actual shebang line that will be interpreted by the shell, so we just prepend $Config{startperl} and preserve the shebang line argument for any switches it may contain. =cut sub _fixin_replace_shebang { my ( $self, $file, $line ) = @_; my ( undef, $arg ) = split ' ', $line, 2; return $Config{startperl} . "\n" . $Config{sharpbang} . "perl $arg\n"; } =item maybe_command (override) Follows VMS naming conventions for executable files. If the name passed in doesn't exactly match an executable file, appends F<.Exe> (or equivalent) to check for executable image, and F<.Com> to check for DCL procedure. If this fails, checks directories in DCL$PATH and finally F for an executable file having the name specified, with or without the F<.Exe>-equivalent suffix. =cut sub maybe_command { my($self,$file) = @_; return $file if -x $file && ! -d _; my(@dirs) = (''); my(@exts) = ('',$Config{'exe_ext'},'.exe','.com'); if ($file !~ m![/:>\]]!) { for (my $i = 0; defined $ENV{"DCL\$PATH;$i"}; $i++) { my $dir = $ENV{"DCL\$PATH;$i"}; $dir .= ':' unless $dir =~ m%[\]:]$%; push(@dirs,$dir); } push(@dirs,'Sys$System:'); foreach my $dir (@dirs) { my $sysfile = "$dir$file"; foreach my $ext (@exts) { return $file if -x "$sysfile$ext" && ! -d _; } } } return 0; } =item pasthru (override) The list of macro definitions to be passed through must be specified using the /MACRO qualifier and must not add another /DEFINE qualifier. We prepend our own comma here to the contents of $(PASTHRU_DEFINE) because it is often empty and a comma always present in CCFLAGS would generate a missing qualifier value error. =cut sub pasthru { my($self) = shift; my $pasthru = $self->SUPER::pasthru; $pasthru =~ s|(PASTHRU\s*=\s*)|$1/MACRO=(|; $pasthru =~ s|\n\z|)\n|m; $pasthru =~ s|/defi?n?e?=\(?([^\),]+)\)?|,$1|ig; return $pasthru; } =item pm_to_blib (override) VMS wants a dot in every file so we can't have one called 'pm_to_blib', it becomes 'pm_to_blib.' and MMS/K isn't smart enough to know that when you have a target called 'pm_to_blib' it should look for 'pm_to_blib.'. So in VMS its pm_to_blib.ts. =cut sub pm_to_blib { my $self = shift; my $make = $self->SUPER::pm_to_blib; $make =~ s{^pm_to_blib :}{pm_to_blib.ts :}m; $make =~ s{\$\(TOUCH\) pm_to_blib}{\$(TOUCH) pm_to_blib.ts}; $make = <<'MAKE' . $make; # Dummy target to match Unix target name; we use pm_to_blib.ts as # timestamp file to avoid repeated invocations under VMS pm_to_blib : pm_to_blib.ts $(NOECHO) $(NOOP) MAKE return $make; } =item perl_script (override) If name passed in doesn't specify a readable file, appends F<.com> or F<.pl> and tries again, since it's customary to have file types on all files under VMS. =cut sub perl_script { my($self,$file) = @_; return $file if -r $file && ! -d _; return "$file.com" if -r "$file.com"; return "$file.pl" if -r "$file.pl"; return ''; } =item replace_manpage_separator Use as separator a character which is legal in a VMS-syntax file name. =cut sub replace_manpage_separator { my($self,$man) = @_; $man = unixify($man); $man =~ s#/+#__#g; $man; } =item init_DEST (override) Because of the difficulty concatenating VMS filepaths we must pre-expand the DEST* variables. =cut sub init_DEST { my $self = shift; $self->SUPER::init_DEST; # Expand DEST variables. foreach my $var ($self->installvars) { my $destvar = 'DESTINSTALL'.$var; $self->{$destvar} = $self->eliminate_macros($self->{$destvar}); } } =item init_DIRFILESEP No separator between a directory path and a filename on VMS. =cut sub init_DIRFILESEP { my($self) = shift; $self->{DIRFILESEP} = ''; return 1; } =item init_main (override) =cut sub init_main { my($self) = shift; $self->SUPER::init_main; $self->{DEFINE} ||= ''; if ($self->{DEFINE} ne '') { my(@terms) = split(/\s+/,$self->{DEFINE}); my(@defs,@udefs); foreach my $def (@terms) { next unless $def; my $targ = \@defs; if ($def =~ s/^-([DU])//) { # If it was a Unix-style definition $targ = \@udefs if $1 eq 'U'; $def =~ s/='(.*)'$/=$1/; # then remove shell-protection '' $def =~ s/^'(.*)'$/$1/; # from entire term or argument } if ($def =~ /=/) { $def =~ s/"/""/g; # Protect existing " from DCL $def = qq["$def"]; # and quote to prevent parsing of = } push @$targ, $def; } $self->{DEFINE} = ''; if (@defs) { $self->{DEFINE} = '/Define=(' . join(',',@defs) . ')'; } if (@udefs) { $self->{DEFINE} .= '/Undef=(' . join(',',@udefs) . ')'; } } } =item init_tools (override) Provide VMS-specific forms of various utility commands. Sets DEV_NULL to nothing because I don't know how to do it on VMS. Changes EQUALIZE_TIMESTAMP to set revision date of target file to one second later than source file, since MMK interprets precisely equal revision dates for a source and target file as a sign that the target needs to be updated. =cut sub init_tools { my($self) = @_; $self->{NOOP} = 'Continue'; $self->{NOECHO} ||= '@ '; $self->{MAKEFILE} ||= $self->{FIRST_MAKEFILE} || 'Descrip.MMS'; $self->{FIRST_MAKEFILE} ||= $self->{MAKEFILE}; $self->{MAKE_APERL_FILE} ||= 'Makeaperl.MMS'; $self->{MAKEFILE_OLD} ||= $self->eliminate_macros('$(FIRST_MAKEFILE)_old'); # # If an extension is not specified, then MMS/MMK assumes an # an extension of .MMS. If there really is no extension, # then a trailing "." needs to be appended to specify a # a null extension. # $self->{MAKEFILE} .= '.' unless $self->{MAKEFILE} =~ m/\./; $self->{FIRST_MAKEFILE} .= '.' unless $self->{FIRST_MAKEFILE} =~ m/\./; $self->{MAKE_APERL_FILE} .= '.' unless $self->{MAKE_APERL_FILE} =~ m/\./; $self->{MAKEFILE_OLD} .= '.' unless $self->{MAKEFILE_OLD} =~ m/\./; $self->{MACROSTART} ||= '/Macro=('; $self->{MACROEND} ||= ')'; $self->{USEMAKEFILE} ||= '/Descrip='; $self->{EQUALIZE_TIMESTAMP} ||= '$(ABSPERLRUN) -we "open F,qq{>>$ARGV[1]};close F;utime(0,(stat($ARGV[0]))[9]+1,$ARGV[1])"'; $self->{MOD_INSTALL} ||= $self->oneliner(<<'CODE', ['-MExtUtils::Install']); install([ from_to => {split('\|', )}, verbose => '$(VERBINST)', uninstall_shadows => '$(UNINST)', dir_mode => '$(PERM_DIR)' ]); CODE $self->{UMASK_NULL} = '! '; $self->SUPER::init_tools; # Use the default shell $self->{SHELL} ||= 'Posix'; # Redirection on VMS goes before the command, not after as on Unix. # $(DEV_NULL) is used once and its not worth going nuts over making # it work. However, Unix's DEV_NULL is quite wrong for VMS. $self->{DEV_NULL} = ''; return; } =item init_platform (override) Add PERL_VMS, MM_VMS_REVISION and MM_VMS_VERSION. MM_VMS_REVISION is for backwards compatibility before MM_VMS had a $VERSION. =cut sub init_platform { my($self) = shift; $self->{MM_VMS_REVISION} = $Revision; $self->{MM_VMS_VERSION} = $VERSION; $self->{PERL_VMS} = $self->catdir($self->{PERL_SRC}, 'VMS') if $self->{PERL_SRC}; } =item platform_constants =cut sub platform_constants { my($self) = shift; my $make_frag = ''; foreach my $macro (qw(PERL_VMS MM_VMS_REVISION MM_VMS_VERSION)) { next unless defined $self->{$macro}; $make_frag .= "$macro = $self->{$macro}\n"; } return $make_frag; } =item init_VERSION (override) Override the *DEFINE_VERSION macros with VMS semantics. Translate the MAKEMAKER filepath to VMS style. =cut sub init_VERSION { my $self = shift; $self->SUPER::init_VERSION; $self->{DEFINE_VERSION} = '"$(VERSION_MACRO)=""$(VERSION)"""'; $self->{XS_DEFINE_VERSION} = '"$(XS_VERSION_MACRO)=""$(XS_VERSION)"""'; $self->{MAKEMAKER} = vmsify($INC{'ExtUtils/MakeMaker.pm'}); } =item constants (override) Fixes up numerous file and directory macros to insure VMS syntax regardless of input syntax. Also makes lists of files comma-separated. =cut sub constants { my($self) = @_; # Be kind about case for pollution for (@ARGV) { $_ = uc($_) if /POLLUTE/i; } # Cleanup paths for directories in MMS macros. foreach my $macro ( qw [ INST_BIN INST_SCRIPT INST_LIB INST_ARCHLIB PERL_LIB PERL_ARCHLIB PERL_ARCHLIBDEP PERL_INC PERL_SRC ], (map { 'INSTALL'.$_ } $self->installvars), (map { 'DESTINSTALL'.$_ } $self->installvars) ) { next unless defined $self->{$macro}; next if $macro =~ /MAN/ && $self->{$macro} eq 'none'; $self->{$macro} = $self->fixpath($self->{$macro},1); } # Cleanup paths for files in MMS macros. foreach my $macro ( qw[LIBPERL_A FIRST_MAKEFILE MAKEFILE_OLD MAKE_APERL_FILE MYEXTLIB] ) { next unless defined $self->{$macro}; $self->{$macro} = $self->fixpath($self->{$macro},0); } # Fixup files for MMS macros # XXX is this list complete? for my $macro (qw/ FULLEXT VERSION_FROM / ) { next unless defined $self->{$macro}; $self->{$macro} = $self->fixpath($self->{$macro},0); } for my $macro (qw/ OBJECT LDFROM / ) { next unless defined $self->{$macro}; # Must expand macros before splitting on unescaped whitespace. $self->{$macro} = $self->eliminate_macros($self->{$macro}); if ($self->{$macro} =~ /(?{$macro} =~ s/(\\)?\n+\s+/ /g; $self->{$macro} = $self->wraplist( map $self->fixpath($_,0), split /,?(?{$macro} ); } else { $self->{$macro} = $self->fixpath($self->{$macro},0); } } for my $macro (qw/ XS MAN1PODS MAN3PODS PM /) { # Where is the space coming from? --jhi next unless $self ne " " && defined $self->{$macro}; my %tmp = (); for my $key (keys %{$self->{$macro}}) { $tmp{$self->fixpath($key,0)} = $self->fixpath($self->{$macro}{$key},0); } $self->{$macro} = \%tmp; } for my $macro (qw/ C O_FILES H /) { next unless defined $self->{$macro}; my @tmp = (); for my $val (@{$self->{$macro}}) { push(@tmp,$self->fixpath($val,0)); } $self->{$macro} = \@tmp; } # mms/k does not define a $(MAKE) macro. $self->{MAKE} = '$(MMS)$(MMSQUALIFIERS)'; return $self->SUPER::constants; } =item special_targets Clear the default .SUFFIXES and put in our own list. =cut sub special_targets { my $self = shift; my $make_frag .= <<'MAKE_FRAG'; .SUFFIXES : .SUFFIXES : $(OBJ_EXT) .c .cpp .cxx .xs MAKE_FRAG return $make_frag; } =item cflags (override) Bypass shell script and produce qualifiers for CC directly (but warn user if a shell script for this extension exists). Fold multiple /Defines into one, since some C compilers pay attention to only one instance of this qualifier on the command line. =cut sub cflags { my($self,$libperl) = @_; my($quals) = $self->{CCFLAGS} || $Config{'ccflags'}; my($definestr,$undefstr,$flagoptstr) = ('','',''); my($incstr) = '/Include=($(PERL_INC)'; my($name,$sys,@m); ( $name = $self->{NAME} . "_cflags" ) =~ s/:/_/g ; print "Unix shell script ".$Config{"$self->{'BASEEXT'}_cflags"}. " required to modify CC command for $self->{'BASEEXT'}\n" if ($Config{$name}); if ($quals =~ / -[DIUOg]/) { while ($quals =~ / -([Og])(\d*)\b/) { my($type,$lvl) = ($1,$2); $quals =~ s/ -$type$lvl\b\s*//; if ($type eq 'g') { $flagoptstr = '/NoOptimize'; } else { $flagoptstr = '/Optimize' . (defined($lvl) ? "=$lvl" : ''); } } while ($quals =~ / -([DIU])(\S+)/) { my($type,$def) = ($1,$2); $quals =~ s/ -$type$def\s*//; $def =~ s/"/""/g; if ($type eq 'D') { $definestr .= qq["$def",]; } elsif ($type eq 'I') { $incstr .= ',' . $self->fixpath($def,1); } else { $undefstr .= qq["$def",]; } } } if (length $quals and $quals !~ m!/!) { warn "MM_VMS: Ignoring unrecognized CCFLAGS elements \"$quals\"\n"; $quals = ''; } $definestr .= q["PERL_POLLUTE",] if $self->{POLLUTE}; if (length $definestr) { chop($definestr); $quals .= "/Define=($definestr)"; } if (length $undefstr) { chop($undefstr); $quals .= "/Undef=($undefstr)"; } # Deal with $self->{DEFINE} here since some C compilers pay attention # to only one /Define clause on command line, so we have to # conflate the ones from $Config{'ccflags'} and $self->{DEFINE} # ($self->{DEFINE} has already been VMSified in constants() above) if ($self->{DEFINE}) { $quals .= $self->{DEFINE}; } for my $type (qw(Def Undef)) { my(@terms); while ($quals =~ m:/${type}i?n?e?=([^/]+):ig) { my $term = $1; $term =~ s:^\((.+)\)$:$1:; push @terms, $term; } if ($type eq 'Def') { push @terms, qw[ $(DEFINE_VERSION) $(XS_DEFINE_VERSION) ]; } if (@terms) { $quals =~ s:/${type}i?n?e?=[^/]+::ig; # PASTHRU_DEFINE will have its own comma $quals .= "/${type}ine=(" . join(',',@terms) . ($type eq 'Def' ? '$(PASTHRU_DEFINE)' : '') . ')'; } } $libperl or $libperl = $self->{LIBPERL_A} || "libperl.olb"; # Likewise with $self->{INC} and /Include if ($self->{'INC'}) { my(@includes) = split(/\s+/,$self->{INC}); foreach (@includes) { s/^-I//; $incstr .= ','.$self->fixpath($_,1); } } $quals .= "$incstr)"; # $quals =~ s/,,/,/g; $quals =~ s/\(,/(/g; $self->{CCFLAGS} = $quals; $self->{PERLTYPE} ||= ''; $self->{OPTIMIZE} ||= $flagoptstr || $Config{'optimize'}; if ($self->{OPTIMIZE} !~ m!/!) { if ($self->{OPTIMIZE} =~ m!-g!) { $self->{OPTIMIZE} = '/Debug/NoOptimize' } elsif ($self->{OPTIMIZE} =~ /-O(\d*)/) { $self->{OPTIMIZE} = '/Optimize' . (defined($1) ? "=$1" : ''); } else { warn "MM_VMS: Can't parse OPTIMIZE \"$self->{OPTIMIZE}\"; using default\n" if length $self->{OPTIMIZE}; $self->{OPTIMIZE} = '/Optimize'; } } return $self->{CFLAGS} = qq{ CCFLAGS = $self->{CCFLAGS} OPTIMIZE = $self->{OPTIMIZE} PERLTYPE = $self->{PERLTYPE} }; } =item const_cccmd (override) Adds directives to point C preprocessor to the right place when handling #include Esys/foo.hE directives. Also constructs CC command line a bit differently than MM_Unix method. =cut sub const_cccmd { my($self,$libperl) = @_; my(@m); return $self->{CONST_CCCMD} if $self->{CONST_CCCMD}; return '' unless $self->needs_linking(); if ($Config{'vms_cc_type'} eq 'gcc') { push @m,' .FIRST ',$self->{NOECHO},'If F$TrnLnm("Sys").eqs."" Then Define/NoLog SYS GNU_CC_Include:[VMS]'; } elsif ($Config{'vms_cc_type'} eq 'vaxc') { push @m,' .FIRST ',$self->{NOECHO},'If F$TrnLnm("Sys").eqs."" .and. F$TrnLnm("VAXC$Include").eqs."" Then Define/NoLog SYS Sys$Library ',$self->{NOECHO},'If F$TrnLnm("Sys").eqs."" .and. F$TrnLnm("VAXC$Include").nes."" Then Define/NoLog SYS VAXC$Include'; } else { push @m,' .FIRST ',$self->{NOECHO},'If F$TrnLnm("Sys").eqs."" .and. F$TrnLnm("DECC$System_Include").eqs."" Then Define/NoLog SYS ', ($Config{'archname'} eq 'VMS_AXP' ? 'Sys$Library' : 'DECC$Library_Include'),' ',$self->{NOECHO},'If F$TrnLnm("Sys").eqs."" .and. F$TrnLnm("DECC$System_Include").nes."" Then Define/NoLog SYS DECC$System_Include'; } push(@m, "\n\nCCCMD = $Config{'cc'} \$(CCFLAGS)\$(OPTIMIZE)\n"); $self->{CONST_CCCMD} = join('',@m); } =item tools_other (override) Throw in some dubious extra macros for Makefile args. Also keep around the old $(SAY) macro in case somebody's using it. =cut sub tools_other { my($self) = @_; # XXX Are these necessary? Does anyone override them? They're longer # than just typing the literal string. my $extra_tools = <<'EXTRA_TOOLS'; # Just in case anyone is using the old macro. USEMACROS = $(MACROSTART) SAY = $(ECHO) EXTRA_TOOLS return $self->SUPER::tools_other . $extra_tools; } =item init_dist (override) VMSish defaults for some values. macro description default ZIPFLAGS flags to pass to ZIP -Vu COMPRESS compression command to gzip use for tarfiles SUFFIX suffix to put on -gz compressed files SHAR shar command to use vms_share DIST_DEFAULT default target to use to tardist create a distribution DISTVNAME Use VERSION_SYM instead of $(DISTNAME)-$(VERSION_SYM) VERSION for the name =cut sub init_dist { my($self) = @_; $self->{ZIPFLAGS} ||= '-Vu'; $self->{COMPRESS} ||= 'gzip'; $self->{SUFFIX} ||= '-gz'; $self->{SHAR} ||= 'vms_share'; $self->{DIST_DEFAULT} ||= 'zipdist'; $self->SUPER::init_dist; $self->{DISTVNAME} = "$self->{DISTNAME}-$self->{VERSION_SYM}" unless $self->{ARGS}{DISTVNAME}; return; } =item c_o (override) Use VMS syntax on command line. In particular, $(DEFINE) and $(PERL_INC) have been pulled into $(CCCMD). Also use MM[SK] macros. =cut sub c_o { my($self) = @_; return '' unless $self->needs_linking(); ' .c$(OBJ_EXT) : $(CCCMD) $(CCCDLFLAGS) $(MMS$TARGET_NAME).c /OBJECT=$(MMS$TARGET_NAME)$(OBJ_EXT) .cpp$(OBJ_EXT) : $(CCCMD) $(CCCDLFLAGS) $(MMS$TARGET_NAME).cpp /OBJECT=$(MMS$TARGET_NAME)$(OBJ_EXT) .cxx$(OBJ_EXT) : $(CCCMD) $(CCCDLFLAGS) $(MMS$TARGET_NAME).cxx /OBJECT=$(MMS$TARGET_NAME)$(OBJ_EXT) '; } =item xs_c (override) Use MM[SK] macros. =cut sub xs_c { my($self) = @_; return '' unless $self->needs_linking(); ' .xs.c : $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $(MMS$TARGET_NAME).xs >$(MMS$TARGET_NAME).xsc $(MV) $(MMS$TARGET_NAME).xsc $(MMS$TARGET_NAME).c '; } =item xs_o (override) Use MM[SK] macros, and VMS command line for C compiler. =cut sub xs_o { my ($self) = @_; return '' unless $self->needs_linking(); my $frag = ' .xs$(OBJ_EXT) : $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $(MMS$TARGET_NAME).xs >$(MMS$TARGET_NAME).xsc $(MV) $(MMS$TARGET_NAME).xsc $(MMS$TARGET_NAME).c $(CCCMD) $(CCCDLFLAGS) $(MMS$TARGET_NAME).c /OBJECT=$(MMS$TARGET_NAME)$(OBJ_EXT) '; if ($self->{XSMULTI}) { for my $ext ($self->_xs_list_basenames) { my $version = $self->parse_version("$ext.pm"); my $ccflags = $self->{CCFLAGS}; $ccflags =~ s/\$\(DEFINE_VERSION\)/\"VERSION_MACRO=\\"\"$version\\"\"/; $ccflags =~ s/\$\(XS_DEFINE_VERSION\)/\"XS_VERSION_MACRO=\\"\"$version\\"\"/; $self->_xsbuild_replace_macro($ccflags, 'xs', $ext, 'INC'); $self->_xsbuild_replace_macro($ccflags, 'xs', $ext, 'DEFINE'); $frag .= _sprintf562 <<'EOF', $ext, $ccflags; %1$s$(OBJ_EXT) : %1$s.xs $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $(MMS$TARGET_NAME).xs > $(MMS$TARGET_NAME).xsc $(MV) $(MMS$TARGET_NAME).xsc $(MMS$TARGET_NAME).c $(CC)%2$s$(OPTIMIZE) $(CCCDLFLAGS) $(MMS$TARGET_NAME).c /OBJECT=$(MMS$TARGET_NAME)$(OBJ_EXT) EOF } } $frag; } =item _xsbuild_replace_macro (override) There is no simple replacement possible since a qualifier and all its subqualifiers must be considered together, so we use our own utility routine for the replacement. =cut sub _xsbuild_replace_macro { my ($self, undef, $xstype, $ext, $varname) = @_; my $value = $self->_xsbuild_value($xstype, $ext, $varname); return unless defined $value; $_[1] = _vms_replace_qualifier($self, $_[1], $value, $varname); } =item _xsbuild_value (override) Convert the extension spec to Unix format, as that's what will match what's in the XSBUILD data structure. =cut sub _xsbuild_value { my ($self, $xstype, $ext, $varname) = @_; $ext = unixify($ext); return $self->SUPER::_xsbuild_value($xstype, $ext, $varname); } sub _vms_replace_qualifier { my ($self, $flags, $newflag, $macro) = @_; my $qual_type; my $type_suffix; my $quote_subquals = 0; my @subquals_new = split /\s+/, $newflag; if ($macro eq 'DEFINE') { $qual_type = 'Def'; $type_suffix = 'ine'; map { $_ =~ s/^-D// } @subquals_new; $quote_subquals = 1; } elsif ($macro eq 'INC') { $qual_type = 'Inc'; $type_suffix = 'lude'; map { $_ =~ s/^-I//; $_ = $self->fixpath($_) } @subquals_new; } my @subquals = (); while ($flags =~ m:/${qual_type}\S{0,4}=([^/]+):ig) { my $term = $1; $term =~ s/\"//g; $term =~ s:^\((.+)\)$:$1:; push @subquals, split /,/, $term; } for my $new (@subquals_new) { my ($sq_new, $sqval_new) = split /=/, $new; my $replaced_old = 0; for my $old (@subquals) { my ($sq, $sqval) = split /=/, $old; if ($sq_new eq $sq) { $old = $sq_new; $old .= '=' . $sqval_new if defined($sqval_new) and length($sqval_new); $replaced_old = 1; last; } } push @subquals, $new unless $replaced_old; } if (@subquals) { $flags =~ s:/${qual_type}\S{0,4}=[^/]+::ig; # add quotes if requested but not for unexpanded macros map { $_ = qq/"$_"/ if $_ !~ m/^\$\(/ } @subquals if $quote_subquals; $flags .= "/${qual_type}$type_suffix=(" . join(',',@subquals) . ')'; } return $flags; } sub xs_dlsyms_ext { '.opt'; } =item dlsyms (override) Create VMS linker options files specifying universal symbols for this extension's shareable image(s), and listing other shareable images or libraries to which it should be linked. =cut sub dlsyms { my ($self, %attribs) = @_; return '' unless $self->needs_linking; $self->xs_dlsyms_iterator; } sub xs_make_dlsyms { my ($self, $attribs, $target, $dep, $name, $dlbase, $funcs, $funclist, $imports, $vars, $extra) = @_; my @m; my $instloc; if ($self->{XSMULTI}) { my ($v, $d, $f) = File::Spec->splitpath($target); my @d = File::Spec->splitdir($d); shift @d if $d[0] eq 'lib'; $instloc = $self->catfile('$(INST_ARCHLIB)', 'auto', @d, $f); push @m,"\ndynamic :: $instloc\n\t\$(NOECHO) \$(NOOP)\n" unless $self->{SKIPHASH}{'dynamic'}; push @m,"\nstatic :: $instloc\n\t\$(NOECHO) \$(NOOP)\n" unless $self->{SKIPHASH}{'static'}; push @m, "\n", sprintf <<'EOF', $instloc, $target; %s : %s $(CP) $(MMS$SOURCE) $(MMS$TARGET) EOF } else { push @m,"\ndynamic :: \$(INST_ARCHAUTODIR)$self->{BASEEXT}.opt\n\t\$(NOECHO) \$(NOOP)\n" unless $self->{SKIPHASH}{'dynamic'}; push @m,"\nstatic :: \$(INST_ARCHAUTODIR)$self->{BASEEXT}.opt\n\t\$(NOECHO) \$(NOOP)\n" unless $self->{SKIPHASH}{'static'}; push @m, "\n", sprintf <<'EOF', $target; $(INST_ARCHAUTODIR)$(BASEEXT).opt : %s $(CP) $(MMS$SOURCE) $(MMS$TARGET) EOF } push @m, "\n$target : $dep\n\t", q!$(PERLRUN) -MExtUtils::Mksymlists -e "Mksymlists('NAME'=>'!, $name, q!', 'DLBASE' => '!,$dlbase, q!', 'DL_FUNCS' => !,neatvalue($funcs), q!, 'FUNCLIST' => !,neatvalue($funclist), q!, 'IMPORTS' => !,neatvalue($imports), q!, 'DL_VARS' => !, neatvalue($vars); push @m, $extra if defined $extra; push @m, qq!);"\n\t!; # Can't use dlbase as it's been through mod2fname. my $olb_base = basename($target, '.opt'); if ($self->{XSMULTI}) { # We've been passed everything but the kitchen sink -- and the location of the # static library we're using to build the dynamic library -- so concoct that # location from what we do have. my $olb_dir = $self->catdir(dirname($instloc), $olb_base); push @m, qq!\$(PERL) -e "print ""${olb_dir}${olb_base}\$(LIB_EXT)/Include=!; push @m, ($Config{d_vms_case_sensitive_symbols} ? uc($olb_base) : $olb_base); push @m, '\n' . $olb_dir . $olb_base . '$(LIB_EXT)/Library\n"";" >>$(MMS$TARGET)',"\n"; } else { push @m, qq!\$(PERL) -e "print ""\$(INST_ARCHAUTODIR)${olb_base}\$(LIB_EXT)/Include=!; if ($self->{OBJECT} =~ /\bBASEEXT\b/ or $self->{OBJECT} =~ /\b$self->{BASEEXT}\b/i) { push @m, ($Config{d_vms_case_sensitive_symbols} ? uc($self->{BASEEXT}) :'$(BASEEXT)'); } else { # We don't have a "main" object file, so pull 'em all in # Upcase module names if linker is being case-sensitive my($upcase) = $Config{d_vms_case_sensitive_symbols}; my(@omods) = split ' ', $self->eliminate_macros($self->{OBJECT}); for (@omods) { s/\.[^.]*$//; # Trim off file type s[\$\(\w+_EXT\)][]; # even as a macro s/.*[:>\/\]]//; # Trim off dir spec $_ = uc if $upcase; }; my(@lines); my $tmp = shift @omods; foreach my $elt (@omods) { $tmp .= ",$elt"; if (length($tmp) > 80) { push @lines, $tmp; $tmp = ''; } } push @lines, $tmp; push @m, '(', join( qq[, -\\n\\t"";" >>\$(MMS\$TARGET)\n\t\$(PERL) -e "print ""], @lines),')'; } push @m, '\n$(INST_ARCHAUTODIR)' . $olb_base . '$(LIB_EXT)/Library\n"";" >>$(MMS$TARGET)',"\n"; } if (length $self->{LDLOADLIBS}) { my($line) = ''; foreach my $lib (split ' ', $self->{LDLOADLIBS}) { $lib =~ s%\$%\\\$%g; # Escape '$' in VMS filespecs if (length($line) + length($lib) > 160) { push @m, "\t\$(PERL) -e \"print qq{$line}\" >>\$(MMS\$TARGET)\n"; $line = $lib . '\n'; } else { $line .= $lib . '\n'; } } push @m, "\t\$(PERL) -e \"print qq{$line}\" >>\$(MMS\$TARGET)\n" if $line; } join '', @m; } =item xs_obj_opt Override to fixup -o flags. =cut sub xs_obj_opt { my ($self, $output_file) = @_; "/OBJECT=$output_file"; } =item dynamic_lib (override) Use VMS Link command. =cut sub xs_dynamic_lib_macros { my ($self, $attribs) = @_; my $otherldflags = $attribs->{OTHERLDFLAGS} || ""; my $inst_dynamic_dep = $attribs->{INST_DYNAMIC_DEP} || ""; sprintf <<'EOF', $otherldflags, $inst_dynamic_dep; # This section creates the dynamically loadable objects from relevant # objects and possibly $(MYEXTLIB). OTHERLDFLAGS = %s INST_DYNAMIC_DEP = %s EOF } sub xs_make_dynamic_lib { my ($self, $attribs, $from, $to, $todir, $ldfrom, $exportlist) = @_; my $shr = $Config{'dbgprefix'} . 'PerlShr'; $exportlist =~ s/.def$/.opt/; # it's a linker options file # 1 2 3 4 5 _sprintf562 <<'EOF', $to, $todir, $exportlist, $shr, "$shr Sys\$Share:$shr.$Config{'dlext'}"; %1$s : $(INST_STATIC) $(PERL_INC)perlshr_attr.opt %2$s$(DFSEP).exists %3$s $(PERL_ARCHIVE) $(INST_DYNAMIC_DEP) If F$TrnLNm("%4$s").eqs."" Then Define/NoLog/User %5$s Link $(LDFLAGS) /Shareable=$(MMS$TARGET)$(OTHERLDFLAGS) %3$s/Option,$(PERL_INC)perlshr_attr.opt/Option EOF } =item xs_make_static_lib (override) Use VMS commands to manipulate object library. =cut sub xs_make_static_lib { my ($self, $object, $to, $todir) = @_; my @objects; if ($self->{XSMULTI}) { # The extension name should be the main object file name minus file type. my $lib = $object; $lib =~ s/\$\(OBJ_EXT\)\z//; my $override = $self->_xsbuild_value('xs', $lib, 'OBJECT'); $object = $override if defined $override; @objects = map { $self->fixpath($_,0) } split /(?{MYEXTLIB}; push(@m,"\t",'If F$Search("$(MMS$TARGET)").eqs."" Then Library/Object/Create $(MMS$TARGET)',"\n"); # if there was a library to copy, then we can't use MMS$SOURCE_LIST, # 'cause it's a library and you can't stick them in other libraries. # In that case, we use $OBJECT instead and hope for the best if ($self->{MYEXTLIB}) { for my $obj (@objects) { push(@m,"\t",'Library/Object/Replace $(MMS$TARGET) ' . $obj,"\n"); } } else { push(@m,"\t",'Library/Object/Replace $(MMS$TARGET) $(MMS$SOURCE_LIST)',"\n"); } push @m, "\t\$(NOECHO) \$(PERL) -e 1 >\$(INST_ARCHAUTODIR)extralibs.ld\n"; foreach my $lib (split ' ', $self->{EXTRALIBS}) { push(@m,"\t",'$(NOECHO) $(PERL) -e "print qq{',$lib,'\n}" >>$(INST_ARCHAUTODIR)extralibs.ld',"\n"); } join('',@m); } =item static_lib_pure_cmd (override) Use VMS commands to manipulate object library. =cut sub static_lib_pure_cmd { my ($self, $from) = @_; sprintf <<'MAKE_FRAG', $from; If F$Search("$(MMS$TARGET)").eqs."" Then Library/Object/Create $(MMS$TARGET) Library/Object/Replace $(MMS$TARGET) %s MAKE_FRAG } =item xs_static_lib_is_xs =cut sub xs_static_lib_is_xs { return 1; } =item extra_clean_files Clean up some OS specific files. Plus the temp file used to shorten a lot of commands. And the name mangler database. =cut sub extra_clean_files { return qw( *.Map *.Dmp *.Lis *.cpp *.$(DLEXT) *.Opt $(BASEEXT).bso .MM_Tmp cxx_repository ); } =item zipfile_target =item tarfile_target =item shdist_target Syntax for invoking shar, tar and zip differs from that for Unix. =cut sub zipfile_target { my($self) = shift; return <<'MAKE_FRAG'; $(DISTVNAME).zip : distdir $(PREOP) $(ZIP) "$(ZIPFLAGS)" $(MMS$TARGET) [.$(DISTVNAME)...]*.*; $(RM_RF) $(DISTVNAME) $(POSTOP) MAKE_FRAG } sub tarfile_target { my($self) = shift; return <<'MAKE_FRAG'; $(DISTVNAME).tar$(SUFFIX) : distdir $(PREOP) $(TO_UNIX) $(TAR) "$(TARFLAGS)" $(DISTVNAME).tar [.$(DISTVNAME)...] $(RM_RF) $(DISTVNAME) $(COMPRESS) $(DISTVNAME).tar $(POSTOP) MAKE_FRAG } sub shdist_target { my($self) = shift; return <<'MAKE_FRAG'; shdist : distdir $(PREOP) $(SHAR) [.$(DISTVNAME)...]*.*; $(DISTVNAME).share $(RM_RF) $(DISTVNAME) $(POSTOP) MAKE_FRAG } # --- Test and Installation Sections --- =item install (override) Work around DCL's 255 character limit several times,and use VMS-style command line quoting in a few cases. =cut sub install { my($self, %attribs) = @_; my(@m); push @m, q[ install :: all pure_install doc_install $(NOECHO) $(NOOP) install_perl :: all pure_perl_install doc_perl_install $(NOECHO) $(NOOP) install_site :: all pure_site_install doc_site_install $(NOECHO) $(NOOP) install_vendor :: all pure_vendor_install doc_vendor_install $(NOECHO) $(NOOP) pure_install :: pure_$(INSTALLDIRS)_install $(NOECHO) $(NOOP) doc_install :: doc_$(INSTALLDIRS)_install $(NOECHO) $(NOOP) pure__install : pure_site_install $(NOECHO) $(ECHO) "INSTALLDIRS not defined, defaulting to INSTALLDIRS=site" doc__install : doc_site_install $(NOECHO) $(ECHO) "INSTALLDIRS not defined, defaulting to INSTALLDIRS=site" # This hack brought to you by DCL's 255-character command line limit pure_perl_install :: ]; push @m, q[ $(NOECHO) $(PERLRUN) "-MFile::Spec" -e "print 'read|'.File::Spec->catfile('$(PERL_ARCHLIB)','auto','$(FULLEXT)','.packlist').'|'" >.MM_tmp $(NOECHO) $(PERLRUN) "-MFile::Spec" -e "print 'write|'.File::Spec->catfile('$(DESTINSTALLARCHLIB)','auto','$(FULLEXT)','.packlist').'|'" >>.MM_tmp ] unless $self->{NO_PACKLIST}; push @m, q[ $(NOECHO) $(ECHO_N) "$(INST_LIB)|$(DESTINSTALLPRIVLIB)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_ARCHLIB)|$(DESTINSTALLARCHLIB)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_BIN)|$(DESTINSTALLBIN)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_SCRIPT)|$(DESTINSTALLSCRIPT)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_MAN1DIR) $(DESTINSTALLMAN1DIR) " >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_MAN3DIR)|$(DESTINSTALLMAN3DIR)" >>.MM_tmp $(NOECHO) $(MOD_INSTALL) <.MM_tmp $(NOECHO) $(RM_F) .MM_tmp $(NOECHO) $(WARN_IF_OLD_PACKLIST) "].$self->catfile($self->{SITEARCHEXP},'auto',$self->{FULLEXT},'.packlist').q[" # Likewise pure_site_install :: ]; push @m, q[ $(NOECHO) $(PERLRUN) "-MFile::Spec" -e "print 'read|'.File::Spec->catfile('$(SITEARCHEXP)','auto','$(FULLEXT)','.packlist').'|'" >.MM_tmp $(NOECHO) $(PERLRUN) "-MFile::Spec" -e "print 'write|'.File::Spec->catfile('$(DESTINSTALLSITEARCH)','auto','$(FULLEXT)','.packlist').'|'" >>.MM_tmp ] unless $self->{NO_PACKLIST}; push @m, q[ $(NOECHO) $(ECHO_N) "$(INST_LIB)|$(DESTINSTALLSITELIB)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_ARCHLIB)|$(DESTINSTALLSITEARCH)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_BIN)|$(DESTINSTALLSITEBIN)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_SCRIPT)|$(DESTINSTALLSCRIPT)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_MAN1DIR)|$(DESTINSTALLSITEMAN1DIR)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_MAN3DIR)|$(DESTINSTALLSITEMAN3DIR)" >>.MM_tmp $(NOECHO) $(MOD_INSTALL) <.MM_tmp $(NOECHO) $(RM_F) .MM_tmp $(NOECHO) $(WARN_IF_OLD_PACKLIST) "].$self->catfile($self->{PERL_ARCHLIB},'auto',$self->{FULLEXT},'.packlist').q[" pure_vendor_install :: ]; push @m, q[ $(NOECHO) $(PERLRUN) "-MFile::Spec" -e "print 'read|'.File::Spec->catfile('$(VENDORARCHEXP)','auto','$(FULLEXT)','.packlist').'|'" >.MM_tmp $(NOECHO) $(PERLRUN) "-MFile::Spec" -e "print 'write|'.File::Spec->catfile('$(DESTINSTALLVENDORARCH)','auto','$(FULLEXT)','.packlist').'|'" >>.MM_tmp ] unless $self->{NO_PACKLIST}; push @m, q[ $(NOECHO) $(ECHO_N) "$(INST_LIB)|$(DESTINSTALLVENDORLIB)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_ARCHLIB)|$(DESTINSTALLVENDORARCH)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_BIN)|$(DESTINSTALLVENDORBIN)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_SCRIPT)|$(DESTINSTALLSCRIPT)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_MAN1DIR)|$(DESTINSTALLVENDORMAN1DIR)|" >>.MM_tmp $(NOECHO) $(ECHO_N) "$(INST_MAN3DIR)|$(DESTINSTALLVENDORMAN3DIR)" >>.MM_tmp $(NOECHO) $(MOD_INSTALL) <.MM_tmp $(NOECHO) $(RM_F) .MM_tmp ]; push @m, q[ # Ditto doc_perl_install :: $(NOECHO) $(NOOP) # And again doc_site_install :: $(NOECHO) $(NOOP) doc_vendor_install :: $(NOECHO) $(NOOP) ] if $self->{NO_PERLLOCAL}; push @m, q[ # Ditto doc_perl_install :: $(NOECHO) $(ECHO) "Appending installation info to ].$self->catfile($self->{DESTINSTALLARCHLIB}, 'perllocal.pod').q[" $(NOECHO) $(MKPATH) $(DESTINSTALLARCHLIB) $(NOECHO) $(ECHO_N) "installed into|$(INSTALLPRIVLIB)|" >.MM_tmp $(NOECHO) $(ECHO_N) "LINKTYPE|$(LINKTYPE)|VERSION|$(VERSION)|EXE_FILES|$(EXE_FILES) " >>.MM_tmp $(NOECHO) $(DOC_INSTALL) "Module" "$(NAME)" <.MM_tmp >>].$self->catfile($self->{DESTINSTALLARCHLIB},'perllocal.pod').q[ $(NOECHO) $(RM_F) .MM_tmp # And again doc_site_install :: $(NOECHO) $(ECHO) "Appending installation info to ].$self->catfile($self->{DESTINSTALLARCHLIB}, 'perllocal.pod').q[" $(NOECHO) $(MKPATH) $(DESTINSTALLARCHLIB) $(NOECHO) $(ECHO_N) "installed into|$(INSTALLSITELIB)|" >.MM_tmp $(NOECHO) $(ECHO_N) "LINKTYPE|$(LINKTYPE)|VERSION|$(VERSION)|EXE_FILES|$(EXE_FILES) " >>.MM_tmp $(NOECHO) $(DOC_INSTALL) "Module" "$(NAME)" <.MM_tmp >>].$self->catfile($self->{DESTINSTALLARCHLIB},'perllocal.pod').q[ $(NOECHO) $(RM_F) .MM_tmp doc_vendor_install :: $(NOECHO) $(ECHO) "Appending installation info to ].$self->catfile($self->{DESTINSTALLARCHLIB}, 'perllocal.pod').q[" $(NOECHO) $(MKPATH) $(DESTINSTALLARCHLIB) $(NOECHO) $(ECHO_N) "installed into|$(INSTALLVENDORLIB)|" >.MM_tmp $(NOECHO) $(ECHO_N) "LINKTYPE|$(LINKTYPE)|VERSION|$(VERSION)|EXE_FILES|$(EXE_FILES) " >>.MM_tmp $(NOECHO) $(DOC_INSTALL) "Module" "$(NAME)" <.MM_tmp >>].$self->catfile($self->{DESTINSTALLARCHLIB},'perllocal.pod').q[ $(NOECHO) $(RM_F) .MM_tmp ] unless $self->{NO_PERLLOCAL}; push @m, q[ uninstall :: uninstall_from_$(INSTALLDIRS)dirs $(NOECHO) $(NOOP) uninstall_from_perldirs :: $(NOECHO) $(UNINSTALL) ].$self->catfile($self->{PERL_ARCHLIB},'auto',$self->{FULLEXT},'.packlist').q[ uninstall_from_sitedirs :: $(NOECHO) $(UNINSTALL) ].$self->catfile($self->{SITEARCHEXP},'auto',$self->{FULLEXT},'.packlist').q[ uninstall_from_vendordirs :: $(NOECHO) $(UNINSTALL) ].$self->catfile($self->{VENDORARCHEXP},'auto',$self->{FULLEXT},'.packlist').q[ ]; join('',@m); } =item perldepend (override) Use VMS-style syntax for files; it's cheaper to just do it directly here than to have the L method call C repeatedly. Also, if we have to rebuild Config.pm, use MM[SK] to do it. =cut sub perldepend { my($self) = @_; my(@m); if ($self->{OBJECT}) { # Need to add an object file dependency on the perl headers. # this is very important for XS modules in perl.git development. push @m, $self->_perl_header_files_fragment(""); # empty separator on VMS as its in the $(PERL_INC) } if ($self->{PERL_SRC}) { my(@macros); my($mmsquals) = '$(USEMAKEFILE)[.vms]$(FIRST_MAKEFILE)'; push(@macros,'__AXP__=1') if $Config{'archname'} eq 'VMS_AXP'; push(@macros,'DECC=1') if $Config{'vms_cc_type'} eq 'decc'; push(@macros,'GNUC=1') if $Config{'vms_cc_type'} eq 'gcc'; push(@macros,'SOCKET=1') if $Config{'d_has_sockets'}; push(@macros,qq["CC=$Config{'cc'}"]) if $Config{'cc'} =~ m!/!; $mmsquals .= '$(USEMACROS)' . join(',',@macros) . '$(MACROEND)' if @macros; push(@m,q[ # Check for unpropagated config.sh changes. Should never happen. # We do NOT just update config.h because that is not sufficient. # An out of date config.h is not fatal but complains loudly! $(PERL_INC)config.h : $(PERL_SRC)config.sh $(NOOP) $(PERL_ARCHLIB)Config.pm : $(PERL_SRC)config.sh $(NOECHO) Write Sys$Error "$(PERL_ARCHLIB)Config.pm may be out of date with config.h or genconfig.pl" olddef = F$Environment("Default") Set Default $(PERL_SRC) $(MMS)],$mmsquals,); if ($self->{PERL_ARCHLIB} =~ m|\[-| && $self->{PERL_SRC} =~ m|(\[-+)|) { my($prefix,$target) = ($1,$self->fixpath('$(PERL_ARCHLIB)Config.pm',0)); $target =~ s/\Q$prefix/[/; push(@m," $target"); } else { push(@m,' $(MMS$TARGET)'); } push(@m,q[ Set Default 'olddef' ]); } push(@m, join(" ", map($self->fixpath($_,0),sort values %{$self->{XS}}))." : \$(XSUBPPDEPS)\n") if %{$self->{XS}}; join('',@m); } =item makeaperl (override) Undertake to build a new set of Perl images using VMS commands. Since VMS does dynamic loading, it's not necessary to statically link each extension into the Perl image, so this isn't the normal build path. Consequently, it hasn't really been tested, and may well be incomplete. =cut our %olbs; # needs to be localized sub makeaperl { my($self, %attribs) = @_; my($makefilename, $searchdirs, $static, $extra, $perlinc, $target, $tmpdir, $libperl) = @attribs{qw(MAKE DIRS STAT EXTRA INCL TARGET TMP LIBPERL)}; my(@m); push @m, " # --- MakeMaker makeaperl section --- MAP_TARGET = $target "; return join '', @m if $self->{PARENT}; my($dir) = join ":", @{$self->{DIR}}; unless ($self->{MAKEAPERL}) { push @m, q{ $(MAKE_APERL_FILE) : $(FIRST_MAKEFILE) $(NOECHO) $(ECHO) "Writing ""$(MMS$TARGET)"" for this $(MAP_TARGET)" $(NOECHO) $(PERLRUNINST) \ Makefile.PL DIR=}, $dir, q{ \ FIRST_MAKEFILE=$(MAKE_APERL_FILE) LINKTYPE=static \ MAKEAPERL=1 NORECURS=1 }; push @m, map(q[ \\\n\t\t"$_"], @ARGV),q{ $(MAP_TARGET) :: $(MAKE_APERL_FILE) $(MAKE)$(USEMAKEFILE)$(MAKE_APERL_FILE) static $(MMS$TARGET) }; push @m, "\n"; return join '', @m; } my($linkcmd,@optlibs,@staticpkgs,$extralist,$targdir,$libperldir,%libseen); local($_); # The front matter of the linkcommand... $linkcmd = join ' ', $Config{'ld'}, grep($_, @Config{qw(large split ldflags ccdlflags)}); $linkcmd =~ s/\s+/ /g; # Which *.olb files could we make use of... local(%olbs); # XXX can this be lexical? $olbs{$self->{INST_ARCHAUTODIR}} = "$self->{BASEEXT}\$(LIB_EXT)"; require File::Find; File::Find::find(sub { return unless m/\Q$self->{LIB_EXT}\E$/; return if m/^libperl/; if( exists $self->{INCLUDE_EXT} ){ my $found = 0; (my $xx = $File::Find::name) =~ s,.*?/auto/,,; $xx =~ s,/?$_,,; $xx =~ s,/,::,g; # Throw away anything not explicitly marked for inclusion. # DynaLoader is implied. foreach my $incl ((@{$self->{INCLUDE_EXT}},'DynaLoader')){ if( $xx eq $incl ){ $found++; last; } } return unless $found; } elsif( exists $self->{EXCLUDE_EXT} ){ (my $xx = $File::Find::name) =~ s,.*?/auto/,,; $xx =~ s,/?$_,,; $xx =~ s,/,::,g; # Throw away anything explicitly marked for exclusion foreach my $excl (@{$self->{EXCLUDE_EXT}}){ return if( $xx eq $excl ); } } $olbs{$ENV{DEFAULT}} = $_; }, grep( -d $_, @{$searchdirs || []})); # We trust that what has been handed in as argument will be buildable $static = [] unless $static; @olbs{@{$static}} = (1) x @{$static}; $extra = [] unless $extra && ref $extra eq 'ARRAY'; # Sort the object libraries in inverse order of # filespec length to try to insure that dependent extensions # will appear before their parents, so the linker will # search the parent library to resolve references. # (e.g. Intuit::DWIM will precede Intuit, so unresolved # references from [.intuit.dwim]dwim.obj can be found # in [.intuit]intuit.olb). for (sort { length($a) <=> length($b) || $a cmp $b } keys %olbs) { next unless $olbs{$_} =~ /\Q$self->{LIB_EXT}\E$/; my($dir) = $self->fixpath($_,1); my($extralibs) = $dir . "extralibs.ld"; my($extopt) = $dir . $olbs{$_}; $extopt =~ s/$self->{LIB_EXT}$/.opt/; push @optlibs, "$dir$olbs{$_}"; # Get external libraries this extension will need if (-f $extralibs ) { my %seenthis; open my $list, "<", $extralibs or warn $!,next; while (<$list>) { chomp; # Include a library in the link only once, unless it's mentioned # multiple times within a single extension's options file, in which # case we assume the builder needed to search it again later in the # link. my $skip = exists($libseen{$_}) && !exists($seenthis{$_}); $libseen{$_}++; $seenthis{$_}++; next if $skip; push @$extra,$_; } } # Get full name of extension for ExtUtils::Miniperl if (-f $extopt) { open my $opt, '<', $extopt or die $!; while (<$opt>) { next unless /(?:UNIVERSAL|VECTOR)=boot_([\w_]+)/; my $pkg = $1; $pkg =~ s#__*#::#g; push @staticpkgs,$pkg; } } } # Place all of the external libraries after all of the Perl extension # libraries in the final link, in order to maximize the opportunity # for XS code from multiple extensions to resolve symbols against the # same external library while only including that library once. push @optlibs, @$extra; $target = "Perl$Config{'exe_ext'}" unless $target; my $shrtarget; ($shrtarget,$targdir) = fileparse($target); $shrtarget =~ s/^([^.]*)/$1Shr/; $shrtarget = $targdir . $shrtarget; $target = "Perlshr.$Config{'dlext'}" unless $target; $tmpdir = "[]" unless $tmpdir; $tmpdir = $self->fixpath($tmpdir,1); if (@optlibs) { $extralist = join(' ',@optlibs); } else { $extralist = ''; } # Let ExtUtils::Liblist find the necessary libs for us (but skip PerlShr) # that's what we're building here). push @optlibs, grep { !/PerlShr/i } split ' ', +($self->ext())[2]; if ($libperl) { unless (-f $libperl || -f ($libperl = $self->catfile($Config{'installarchlib'},'CORE',$libperl))) { print "Warning: $libperl not found\n"; undef $libperl; } } unless ($libperl) { if (defined $self->{PERL_SRC}) { $libperl = $self->catfile($self->{PERL_SRC},"libperl$self->{LIB_EXT}"); } elsif (-f ($libperl = $self->catfile($Config{'installarchlib'},'CORE',"libperl$self->{LIB_EXT}")) ) { } else { print "Warning: $libperl not found If you're going to build a static perl binary, make sure perl is installed otherwise ignore this warning\n"; } } $libperldir = $self->fixpath((fileparse($libperl))[1],1); push @m, ' # Fill in the target you want to produce if it\'s not perl MAP_TARGET = ',$self->fixpath($target,0),' MAP_SHRTARGET = ',$self->fixpath($shrtarget,0)," MAP_LINKCMD = $linkcmd MAP_PERLINC = ", $perlinc ? map('"$_" ',@{$perlinc}) : ''," MAP_EXTRA = $extralist MAP_LIBPERL = ",$self->fixpath($libperl,0),' '; push @m,"\n${tmpdir}Makeaperl.Opt : \$(MAP_EXTRA)\n"; foreach (@optlibs) { push @m,' $(NOECHO) $(PERL) -e "print q{',$_,'}" >>$(MMS$TARGET)',"\n"; } push @m,"\n${tmpdir}PerlShr.Opt :\n\t"; push @m,'$(NOECHO) $(PERL) -e "print q{$(MAP_SHRTARGET)}" >$(MMS$TARGET)',"\n"; push @m,' $(MAP_SHRTARGET) : $(MAP_LIBPERL) Makeaperl.Opt ',"${libperldir}Perlshr_Attr.Opt",' $(MAP_LINKCMD)/Shareable=$(MMS$TARGET) $(MAP_LIBPERL), Makeaperl.Opt/Option ',"${libperldir}Perlshr_Attr.Opt/Option",' $(MAP_TARGET) : $(MAP_SHRTARGET) ',"${tmpdir}perlmain\$(OBJ_EXT) ${tmpdir}PerlShr.Opt",' $(MAP_LINKCMD) ',"${tmpdir}perlmain\$(OBJ_EXT)",', PerlShr.Opt/Option $(NOECHO) $(ECHO) "To install the new ""$(MAP_TARGET)"" binary, say" $(NOECHO) $(ECHO) " $(MAKE)$(USEMAKEFILE)$(FIRST_MAKEFILE) inst_perl $(USEMACROS)MAP_TARGET=$(MAP_TARGET)$(ENDMACRO)" $(NOECHO) $(ECHO) "To remove the intermediate files, say $(NOECHO) $(ECHO) " $(MAKE)$(USEMAKEFILE)$(FIRST_MAKEFILE) map_clean" '; push @m,"\n${tmpdir}perlmain.c : \$(FIRST_MAKEFILE)\n\t\$(NOECHO) \$(PERL) -e 1 >${tmpdir}Writemain.tmp\n"; push @m, "# More from the 255-char line length limit\n"; foreach (@staticpkgs) { push @m,' $(NOECHO) $(PERL) -e "print q{',$_,qq[}" >>${tmpdir}Writemain.tmp\n]; } push @m, sprintf <<'MAKE_FRAG', $tmpdir, $tmpdir; $(NOECHO) $(PERL) $(MAP_PERLINC) -ane "use ExtUtils::Miniperl; writemain(@F)" %sWritemain.tmp >$(MMS$TARGET) $(NOECHO) $(RM_F) %sWritemain.tmp MAKE_FRAG push @m, q[ # Still more from the 255-char line length limit doc_inst_perl : $(NOECHO) $(MKPATH) $(DESTINSTALLARCHLIB) $(NOECHO) $(ECHO) "Perl binary $(MAP_TARGET)|" >.MM_tmp $(NOECHO) $(ECHO) "MAP_STATIC|$(MAP_STATIC)|" >>.MM_tmp $(NOECHO) $(PERL) -pl040 -e " " ].$self->catfile('$(INST_ARCHAUTODIR)','extralibs.all'),q[ >>.MM_tmp $(NOECHO) $(ECHO) -e "MAP_LIBPERL|$(MAP_LIBPERL)|" >>.MM_tmp $(NOECHO) $(DOC_INSTALL) <.MM_tmp >>].$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q[ $(NOECHO) $(RM_F) .MM_tmp ]; push @m, " inst_perl : pure_inst_perl doc_inst_perl \$(NOECHO) \$(NOOP) pure_inst_perl : \$(MAP_TARGET) $self->{CP} \$(MAP_SHRTARGET) ",$self->fixpath($Config{'installbin'},1)," $self->{CP} \$(MAP_TARGET) ",$self->fixpath($Config{'installbin'},1)," clean :: map_clean \$(NOECHO) \$(NOOP) map_clean : \$(RM_F) ${tmpdir}perlmain\$(OBJ_EXT) ${tmpdir}perlmain.c \$(FIRST_MAKEFILE) \$(RM_F) ${tmpdir}Makeaperl.Opt ${tmpdir}PerlShr.Opt \$(MAP_TARGET) "; join '', @m; } # --- Output postprocessing section --- =item maketext_filter (override) Ensure that colons marking targets are preceded by space, in order to distinguish the target delimiter from a colon appearing as part of a filespec. =cut sub maketext_filter { my($self, $text) = @_; $text =~ s/^([^\s:=]+)(:+\s)/$1 $2/mg; return $text; } =item prefixify (override) prefixifying on VMS is simple. Each should simply be: perl_root:[some.dir] which can just be converted to: volume:[your.prefix.some.dir] otherwise you get the default layout. In effect, your search prefix is ignored and $Config{vms_prefix} is used instead. =cut sub prefixify { my($self, $var, $sprefix, $rprefix, $default) = @_; # Translate $(PERLPREFIX) to a real path. $rprefix = $self->eliminate_macros($rprefix); $rprefix = vmspath($rprefix) if $rprefix; $sprefix = vmspath($sprefix) if $sprefix; $default = vmsify($default) unless $default =~ /\[.*\]/; (my $var_no_install = $var) =~ s/^install//; my $path = $self->{uc $var} || $ExtUtils::MM_Unix::Config_Override{lc $var} || $Config{lc $var} || $Config{lc $var_no_install}; if( !$path ) { warn " no Config found for $var.\n" if $Verbose >= 2; $path = $self->_prefixify_default($rprefix, $default); } elsif( !$self->{ARGS}{PREFIX} || !$self->file_name_is_absolute($path) ) { # do nothing if there's no prefix or if its relative } elsif( $sprefix eq $rprefix ) { warn " no new prefix.\n" if $Verbose >= 2; } else { warn " prefixify $var => $path\n" if $Verbose >= 2; warn " from $sprefix to $rprefix\n" if $Verbose >= 2; my($path_vol, $path_dirs) = $self->splitpath( $path ); if( $path_vol eq $Config{vms_prefix}.':' ) { warn " $Config{vms_prefix}: seen\n" if $Verbose >= 2; $path_dirs =~ s{^\[}{\[.} unless $path_dirs =~ m{^\[\.}; $path = $self->_catprefix($rprefix, $path_dirs); } else { $path = $self->_prefixify_default($rprefix, $default); } } print " now $path\n" if $Verbose >= 2; return $self->{uc $var} = $path; } sub _prefixify_default { my($self, $rprefix, $default) = @_; warn " cannot prefix, using default.\n" if $Verbose >= 2; if( !$default ) { warn "No default!\n" if $Verbose >= 1; return; } if( !$rprefix ) { warn "No replacement prefix!\n" if $Verbose >= 1; return ''; } return $self->_catprefix($rprefix, $default); } sub _catprefix { my($self, $rprefix, $default) = @_; my($rvol, $rdirs) = $self->splitpath($rprefix); if( $rvol ) { return $self->catpath($rvol, $self->catdir($rdirs, $default), '' ) } else { return $self->catdir($rdirs, $default); } } =item cd =cut sub cd { my($self, $dir, @cmds) = @_; $dir = vmspath($dir); my $cmd = join "\n\t", map "$_", @cmds; # No leading tab makes it look right when embedded my $make_frag = sprintf <<'MAKE_FRAG', $dir, $cmd; startdir = F$Environment("Default") Set Default %s %s Set Default 'startdir' MAKE_FRAG # No trailing newline makes this easier to embed chomp $make_frag; return $make_frag; } =item oneliner =cut sub oneliner { my($self, $cmd, $switches) = @_; $switches = [] unless defined $switches; # Strip leading and trailing newlines $cmd =~ s{^\n+}{}; $cmd =~ s{\n+$}{}; my @cmds = split /\n/, $cmd; $cmd = join " \n\t -e ", map $self->quote_literal($_), @cmds; $cmd = $self->escape_newlines($cmd); # Switches must be quoted else they will be lowercased. $switches = join ' ', map { qq{"$_"} } @$switches; return qq{\$(ABSPERLRUN) $switches -e $cmd "--"}; } =item B perl trips up on "" thinking it's an input redirect. So we use the native Write command instead. Besides, it's faster. =cut sub echo { my($self, $text, $file, $opts) = @_; # Compatibility with old options if( !ref $opts ) { my $append = $opts; $opts = { append => $append || 0 }; } my $opencmd = $opts->{append} ? 'Open/Append' : 'Open/Write'; $opts->{allow_variables} = 0 unless defined $opts->{allow_variables}; my $ql_opts = { allow_variables => $opts->{allow_variables} }; my @cmds = ("\$(NOECHO) $opencmd MMECHOFILE $file "); push @cmds, map { '$(NOECHO) Write MMECHOFILE '.$self->quote_literal($_, $ql_opts) } split /\n/, $text; push @cmds, '$(NOECHO) Close MMECHOFILE'; return @cmds; } =item quote_literal =cut sub quote_literal { my($self, $text, $opts) = @_; $opts->{allow_variables} = 1 unless defined $opts->{allow_variables}; # I believe this is all we should need. $text =~ s{"}{""}g; $text = $opts->{allow_variables} ? $self->escape_dollarsigns($text) : $self->escape_all_dollarsigns($text); return qq{"$text"}; } =item escape_dollarsigns Quote, don't escape. =cut sub escape_dollarsigns { my($self, $text) = @_; # Quote dollar signs which are not starting a variable $text =~ s{\$ (?!\() }{"\$"}gx; return $text; } =item escape_all_dollarsigns Quote, don't escape. =cut sub escape_all_dollarsigns { my($self, $text) = @_; # Quote dollar signs $text =~ s{\$}{"\$\"}gx; return $text; } =item escape_newlines =cut sub escape_newlines { my($self, $text) = @_; $text =~ s{\n}{-\n}g; return $text; } =item max_exec_len 256 characters. =cut sub max_exec_len { my $self = shift; return $self->{_MAX_EXEC_LEN} ||= 256; } =item init_linker =cut sub init_linker { my $self = shift; $self->{EXPORT_LIST} ||= '$(BASEEXT).opt'; my $shr = $Config{dbgprefix} . 'PERLSHR'; if ($self->{PERL_SRC}) { $self->{PERL_ARCHIVE} ||= $self->catfile($self->{PERL_SRC}, "$shr.$Config{'dlext'}"); } else { $self->{PERL_ARCHIVE} ||= $ENV{$shr} ? $ENV{$shr} : "Sys\$Share:$shr.$Config{'dlext'}"; } $self->{PERL_ARCHIVEDEP} ||= ''; $self->{PERL_ARCHIVE_AFTER} ||= ''; } =item catdir (override) =item catfile (override) Eliminate the macros in the output to the MMS/MMK file. (L used to do this for us, but it's being removed) =cut sub catdir { my $self = shift; # Process the macros on VMS MMS/MMK my @args = map { m{\$\(} ? $self->eliminate_macros($_) : $_ } @_; my $dir = $self->SUPER::catdir(@args); # Fix up the directory and force it to VMS format. $dir = $self->fixpath($dir, 1); return $dir; } sub catfile { my $self = shift; # Process the macros on VMS MMS/MMK my @args = map { m{\$\(} ? $self->eliminate_macros($_) : $_ } @_; my $file = $self->SUPER::catfile(@args); $file = vmsify($file); return $file } =item eliminate_macros Expands MM[KS]/Make macros in a text string, using the contents of identically named elements of C<%$self>, and returns the result as a file specification in Unix syntax. NOTE: This is the canonical version of the method. The version in L is deprecated. =cut sub eliminate_macros { my($self,$path) = @_; return '' unless $path; $self = {} unless ref $self; my($npath) = unixify($path); # sometimes unixify will return a string with an off-by-one trailing null $npath =~ s{\0$}{}; my($complex) = 0; my($head,$macro,$tail); # perform m##g in scalar context so it acts as an iterator while ($npath =~ m#(.*?)\$\((\S+?)\)(.*)#gs) { if (defined $self->{$2}) { ($head,$macro,$tail) = ($1,$2,$3); if (ref $self->{$macro}) { if (ref $self->{$macro} eq 'ARRAY') { $macro = join ' ', @{$self->{$macro}}; } else { print "Note: can't expand macro \$($macro) containing ",ref($self->{$macro}), "\n\t(using MMK-specific deferred substitutuon; MMS will break)\n"; $macro = "\cB$macro\cB"; $complex = 1; } } else { $macro = $self->{$macro}; # Don't unixify if there is unescaped whitespace $macro = unixify($macro) unless ($macro =~ /(?fixpath($path); my $path = $mm->fixpath($path, $is_dir); Catchall routine to clean up problem MM[SK]/Make macros. Expands macros in any directory specification, in order to avoid juxtaposing two VMS-syntax directories when MM[SK] is run. Also expands expressions which are all macro, so that we can tell how long the expansion is, and avoid overrunning DCL's command buffer when MM[KS] is running. fixpath() checks to see whether the result matches the name of a directory in the current default directory and returns a directory or file specification accordingly. C<$is_dir> can be set to true to force fixpath() to consider the path to be a directory or false to force it to be a file. NOTE: This is the canonical version of the method. The version in L is deprecated. =cut sub fixpath { my($self,$path,$force_path) = @_; return '' unless $path; $self = bless {}, $self unless ref $self; my($fixedpath,$prefix,$name); if ($path =~ m#^\$\([^\)]+\)\Z(?!\n)#s || $path =~ m#[/:>\]]#) { if ($force_path or $path =~ /(?:DIR\)|\])\Z(?!\n)/) { $fixedpath = vmspath($self->eliminate_macros($path)); } else { $fixedpath = vmsify($self->eliminate_macros($path)); } } elsif ((($prefix,$name) = ($path =~ m#^\$\(([^\)]+)\)(.+)#s)) && $self->{$prefix}) { my($vmspre) = $self->eliminate_macros("\$($prefix)"); # is it a dir or just a name? $vmspre = ($vmspre =~ m|/| or $prefix =~ /DIR\Z(?!\n)/) ? vmspath($vmspre) : ''; $fixedpath = ($vmspre ? $vmspre : $self->{$prefix}) . $name; $fixedpath = vmspath($fixedpath) if $force_path; } else { $fixedpath = $path; $fixedpath = vmspath($fixedpath) if $force_path; } # No hints, so we try to guess if (!defined($force_path) and $fixedpath !~ /[:>(.\]]/) { $fixedpath = vmspath($fixedpath) if -d $fixedpath; } # Trim off root dirname if it's had other dirs inserted in front of it. $fixedpath =~ s/\.000000([\]>])/$1/; # Special case for VMS absolute directory specs: these will have had device # prepended during trip through Unix syntax in eliminate_macros(), since # Unix syntax has no way to express "absolute from the top of this device's # directory tree". if ($path =~ /^[\[>][^.\-]/) { $fixedpath =~ s/^[^\[<]+//; } return $fixedpath; } =item os_flavor VMS is VMS. =cut sub os_flavor { return('VMS'); } =item is_make_type (override) None of the make types being checked for is viable on VMS, plus our $self->{MAKE} is an unexpanded (and unexpandable) macro whose value is known only to the make utility itself. =cut sub is_make_type { my($self, $type) = @_; return 0; } =item make_type (override) Returns a suitable string describing the type of makefile being written. =cut sub make_type { "$Config{make}-style"; } =back =head1 AUTHOR Original author Charles Bailey F Maintained by Michael G Schwern F See L for patching and contact information. =cut 1; PK!!�[�[perl5/ExtUtils/Manifest.pmnuÏÃ6Ç$package ExtUtils::Manifest; require Exporter; use Config; use File::Basename; use File::Copy 'copy'; use File::Find; use File::Spec 0.8; use Carp; use strict; use warnings; our $VERSION = '1.70'; our @ISA = ('Exporter'); our @EXPORT_OK = qw(mkmanifest manicheck filecheck fullcheck skipcheck manifind maniread manicopy maniadd maniskip ); our $Is_MacOS = $^O eq 'MacOS'; our $Is_VMS = $^O eq 'VMS'; our $Is_VMS_mode = 0; our $Is_VMS_lc = 0; our $Is_VMS_nodot = 0; # No dots in dir names or double dots in files if ($Is_VMS) { require VMS::Filespec if $Is_VMS; my $vms_unix_rpt; my $vms_efs; my $vms_case; $Is_VMS_mode = 1; $Is_VMS_lc = 1; $Is_VMS_nodot = 1; if (eval { local $SIG{__DIE__}; require VMS::Feature; }) { $vms_unix_rpt = VMS::Feature::current("filename_unix_report"); $vms_efs = VMS::Feature::current("efs_charset"); $vms_case = VMS::Feature::current("efs_case_preserve"); } else { my $unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || ''; my $efs_charset = $ENV{'DECC$EFS_CHARSET'} || ''; my $efs_case = $ENV{'DECC$EFS_CASE_PRESERVE'} || ''; $vms_unix_rpt = $unix_rpt =~ /^[ET1]/i; $vms_efs = $efs_charset =~ /^[ET1]/i; $vms_case = $efs_case =~ /^[ET1]/i; } $Is_VMS_lc = 0 if ($vms_case); $Is_VMS_mode = 0 if ($vms_unix_rpt); $Is_VMS_nodot = 0 if ($vms_efs); } our $Debug = $ENV{PERL_MM_MANIFEST_DEBUG} || 0; our $Verbose = defined $ENV{PERL_MM_MANIFEST_VERBOSE} ? $ENV{PERL_MM_MANIFEST_VERBOSE} : 1; our $Quiet = 0; our $MANIFEST = 'MANIFEST'; our $DEFAULT_MSKIP = File::Spec->catfile( dirname(__FILE__), "$MANIFEST.SKIP" ); =head1 NAME ExtUtils::Manifest - utilities to write and check a MANIFEST file =head1 VERSION version 1.70 =head1 SYNOPSIS use ExtUtils::Manifest qw(...funcs to import...); mkmanifest(); my @missing_files = manicheck; my @skipped = skipcheck; my @extra_files = filecheck; my($missing, $extra) = fullcheck; my $found = manifind(); my $manifest = maniread(); manicopy($read,$target); maniadd({$file => $comment, ...}); =head1 DESCRIPTION =head2 Functions ExtUtils::Manifest exports no functions by default. The following are exported on request =over 4 =item mkmanifest mkmanifest(); Writes all files in and below the current directory to your F. It works similar to the result of the Unix command find . > MANIFEST All files that match any regular expression in a file F (if it exists) are ignored. Any existing F file will be saved as F. =cut sub _sort { return sort { lc $a cmp lc $b } @_; } sub mkmanifest { my $manimiss = 0; my $read = (-r 'MANIFEST' && maniread()) or $manimiss++; $read = {} if $manimiss; local *M; my $bakbase = $MANIFEST; $bakbase =~ s/\./_/g if $Is_VMS_nodot; # avoid double dots rename $MANIFEST, "$bakbase.bak" unless $manimiss; open M, "> $MANIFEST" or die "Could not open $MANIFEST: $!"; binmode M, ':raw'; my $skip = maniskip(); my $found = manifind(); my($key,$val,$file,%all); %all = (%$found, %$read); $all{$MANIFEST} = ($Is_VMS_mode ? "$MANIFEST\t\t" : '') . 'This list of files' if $manimiss; # add new MANIFEST to known file list foreach $file (_sort keys %all) { if ($skip->($file)) { # Policy: only remove files if they're listed in MANIFEST.SKIP. # Don't remove files just because they don't exist. warn "Removed from $MANIFEST: $file\n" if $Verbose and exists $read->{$file}; next; } if ($Verbose){ warn "Added to $MANIFEST: $file\n" unless exists $read->{$file}; } my $text = $all{$file}; $file = _unmacify($file); my $tabs = (5 - (length($file)+1)/8); $tabs = 1 if $tabs < 1; $tabs = 0 unless $text; if ($file =~ /\s/) { $file =~ s/([\\'])/\\$1/g; $file = "'$file'"; } print M $file, "\t" x $tabs, $text, "\n"; } close M; } # Geez, shouldn't this use File::Spec or File::Basename or something? # Why so careful about dependencies? sub clean_up_filename { my $filename = shift; $filename =~ s|^\./||; $filename =~ s/^:([^:]+)$/$1/ if $Is_MacOS; if ( $Is_VMS ) { $filename =~ s/\.$//; # trim trailing dot $filename = VMS::Filespec::unixify($filename); # unescape spaces, etc. if( $Is_VMS_lc ) { $filename = lc($filename); $filename = uc($filename) if $filename =~ /^MANIFEST(\.SKIP)?$/i; } } return $filename; } =item manifind my $found = manifind(); returns a hash reference. The keys of the hash are the files found below the current directory. =cut sub manifind { my $p = shift || {}; my $found = {}; my $wanted = sub { my $name = clean_up_filename($File::Find::name); warn "Debug: diskfile $name\n" if $Debug; return if -d $_; $found->{$name} = ""; }; # We have to use "$File::Find::dir/$_" in preprocess, because # $File::Find::name is unavailable. # Also, it's okay to use / here, because MANIFEST files use Unix-style # paths. find({wanted => $wanted, follow_fast => 1}, $Is_MacOS ? ":" : "."); return $found; } =item manicheck my @missing_files = manicheck(); checks if all the files within a C in the current directory really do exist. If C and the tree below the current directory are in sync it silently returns an empty list. Otherwise it returns a list of files which are listed in the C but missing from the directory, and by default also outputs these names to STDERR. =cut sub manicheck { return _check_files(); } =item filecheck my @extra_files = filecheck(); finds files below the current directory that are not mentioned in the C file. An optional file C will be consulted. Any file matching a regular expression in such a file will not be reported as missing in the C file. The list of any extraneous files found is returned, and by default also reported to STDERR. =cut sub filecheck { return _check_manifest(); } =item fullcheck my($missing, $extra) = fullcheck(); does both a manicheck() and a filecheck(), returning then as two array refs. =cut sub fullcheck { return [_check_files()], [_check_manifest()]; } =item skipcheck my @skipped = skipcheck(); lists all the files that are skipped due to your C file. =cut sub skipcheck { my($p) = @_; my $found = manifind(); my $matches = maniskip(); my @skipped = (); foreach my $file (_sort keys %$found){ if (&$matches($file)){ warn "Skipping $file\n" unless $Quiet; push @skipped, $file; next; } } return @skipped; } sub _check_files { my $p = shift; my $dosnames=(defined(&Dos::UseLFN) && Dos::UseLFN()==0); my $read = maniread() || {}; my $found = manifind($p); my(@missfile) = (); foreach my $file (_sort keys %$read){ warn "Debug: manicheck checking from $MANIFEST $file\n" if $Debug; if ($dosnames){ $file = lc $file; $file =~ s=(\.(\w|-)+)=substr ($1,0,4)=ge; $file =~ s=((\w|-)+)=substr ($1,0,8)=ge; } unless ( exists $found->{$file} ) { warn "No such file: $file\n" unless $Quiet; push @missfile, $file; } } return @missfile; } sub _check_manifest { my($p) = @_; my $read = maniread() || {}; my $found = manifind($p); my $skip = maniskip(); my @missentry = (); foreach my $file (_sort keys %$found){ next if $skip->($file); warn "Debug: manicheck checking from disk $file\n" if $Debug; unless ( exists $read->{$file} ) { my $canon = $Is_MacOS ? "\t" . _unmacify($file) : ''; warn "Not in $MANIFEST: $file$canon\n" unless $Quiet; push @missentry, $file; } } return @missentry; } =item maniread my $manifest = maniread(); my $manifest = maniread($manifest_file); reads a named C file (defaults to C in the current directory) and returns a HASH reference with files being the keys and comments being the values of the HASH. Blank lines and lines which start with C<#> in the C file are discarded. =cut sub maniread { my ($mfile) = @_; $mfile ||= $MANIFEST; my $read = {}; local *M; unless (open M, "< $mfile"){ warn "Problem opening $mfile: $!"; return $read; } local $_; while (){ chomp; next if /^\s*#/; my($file, $comment); # filename may contain spaces if enclosed in '' # (in which case, \\ and \' are escapes) if (($file, $comment) = /^'((?:\\[\\']|.+)+)'\s*(.*)/) { $file =~ s/\\([\\'])/$1/g; } else { ($file, $comment) = /^(\S+)\s*(.*)/; } next unless $file; if ($Is_MacOS) { $file = _macify($file); $file =~ s/\\([0-3][0-7][0-7])/sprintf("%c", oct($1))/ge; } elsif ($Is_VMS_mode) { require File::Basename; my($base,$dir) = File::Basename::fileparse($file); # Resolve illegal file specifications in the same way as tar if ($Is_VMS_nodot) { $dir =~ tr/./_/; my(@pieces) = split(/\./,$base); if (@pieces > 2) { $base = shift(@pieces) . '.' . join('_',@pieces); } my $okfile = "$dir$base"; warn "Debug: Illegal name $file changed to $okfile\n" if $Debug; $file = $okfile; } if( $Is_VMS_lc ) { $file = lc($file); $file = uc($file) if $file =~ /^MANIFEST(\.SKIP)?$/i; } } $read->{$file} = $comment; } close M; $read; } =item maniskip my $skipchk = maniskip(); my $skipchk = maniskip($manifest_skip_file); if ($skipchk->($file)) { .. } reads a named C file (defaults to C in the current directory) and returns a CODE reference that tests whether a given filename should be skipped. =cut # returns an anonymous sub that decides if an argument matches sub maniskip { my @skip ; my $mfile = shift || "$MANIFEST.SKIP"; _check_mskip_directives($mfile) if -f $mfile; local(*M, $_); open M, "< $mfile" or open M, "< $DEFAULT_MSKIP" or return sub {0}; while (){ chomp; s/\r//; $_ =~ qr{^\s*(?:(?:'([^\\']*(?:\\.[^\\']*)*)')|([^#\s]\S*))?(?:(?:\s*)|(?:\s+(.*?)\s*))$}; #my $comment = $3; my $filename = $2; if ( defined($1) ) { $filename = $1; $filename =~ s/\\(['\\])/$1/g; } next if (not defined($filename) or not $filename); push @skip, _macify($filename); } close M; return sub {0} unless (scalar @skip > 0); my $opts = $Is_VMS_mode ? '(?i)' : ''; # Make sure each entry is isolated in its own parentheses, in case # any of them contain alternations my $regex = join '|', map "(?:$_)", @skip; return sub { $_[0] =~ qr{$opts$regex} }; } # checks for the special directives # #!include_default # #!include /path/to/some/manifest.skip # in a custom MANIFEST.SKIP for, for including # the content of, respectively, the default MANIFEST.SKIP # and an external manifest.skip file sub _check_mskip_directives { my $mfile = shift; local (*M, $_); my @lines = (); my $flag = 0; unless (open M, "< $mfile") { warn "Problem opening $mfile: $!"; return; } while () { if (/^#!include_default\s*$/) { if (my @default = _include_mskip_file()) { push @lines, @default; warn "Debug: Including default MANIFEST.SKIP\n" if $Debug; $flag++; } next; } if (/^#!include\s+(.*)\s*$/) { my $external_file = $1; if (my @external = _include_mskip_file($external_file)) { push @lines, @external; warn "Debug: Including external $external_file\n" if $Debug; $flag++; } next; } push @lines, $_; } close M; return unless $flag; my $bakbase = $mfile; $bakbase =~ s/\./_/g if $Is_VMS_nodot; # avoid double dots rename $mfile, "$bakbase.bak"; warn "Debug: Saving original $mfile as $bakbase.bak\n" if $Debug; unless (open M, "> $mfile") { warn "Problem opening $mfile: $!"; return; } binmode M, ':raw'; print M $_ for (@lines); close M; return; } # returns an array containing the lines of an external # manifest.skip file, if given, or $DEFAULT_MSKIP sub _include_mskip_file { my $mskip = shift || $DEFAULT_MSKIP; unless (-f $mskip) { warn qq{Included file "$mskip" not found - skipping}; return; } local (*M, $_); unless (open M, "< $mskip") { warn "Problem opening $mskip: $!"; return; } my @lines = (); push @lines, "\n#!start included $mskip\n"; push @lines, $_ while ; close M; push @lines, "#!end included $mskip\n\n"; return @lines; } =item manicopy manicopy(\%src, $dest_dir); manicopy(\%src, $dest_dir, $how); Copies the files that are the keys in %src to the $dest_dir. %src is typically returned by the maniread() function. manicopy( maniread(), $dest_dir ); This function is useful for producing a directory tree identical to the intended distribution tree. $how can be used to specify a different methods of "copying". Valid values are C, which actually copies the files, C which creates hard links, and C which mostly links the files but copies any symbolic link to make a tree without any symbolic link. C is the default. =cut sub manicopy { my($read,$target,$how)=@_; croak "manicopy() called without target argument" unless defined $target; $how ||= 'cp'; require File::Path; require File::Basename; $target = VMS::Filespec::unixify($target) if $Is_VMS_mode; File::Path::mkpath([ $target ],! $Quiet,$Is_VMS ? undef : 0755); foreach my $file (keys %$read){ if ($Is_MacOS) { if ($file =~ m!:!) { my $dir = _maccat($target, $file); $dir =~ s/[^:]+$//; File::Path::mkpath($dir,1,0755); } cp_if_diff($file, _maccat($target, $file), $how); } else { $file = VMS::Filespec::unixify($file) if $Is_VMS_mode; if ($file =~ m!/!) { # Ilya, that hurts, I fear, or maybe not? my $dir = File::Basename::dirname($file); $dir = VMS::Filespec::unixify($dir) if $Is_VMS_mode; File::Path::mkpath(["$target/$dir"],! $Quiet,$Is_VMS ? undef : 0755); } cp_if_diff($file, "$target/$file", $how); } } } sub cp_if_diff { my($from, $to, $how)=@_; if (! -f $from) { carp "$from not found"; return; } my($diff) = 0; local(*F,*T); open(F,"< $from\0") or die "Can't read $from: $!\n"; if (open(T,"< $to\0")) { local $_; while () { $diff++,last if $_ ne ; } $diff++ unless eof(T); close T; } else { $diff++; } close F; if ($diff) { if (-e $to) { unlink($to) or confess "unlink $to: $!"; } STRICT_SWITCH: { best($from,$to), last STRICT_SWITCH if $how eq 'best'; cp($from,$to), last STRICT_SWITCH if $how eq 'cp'; ln($from,$to), last STRICT_SWITCH if $how eq 'ln'; croak("ExtUtils::Manifest::cp_if_diff " . "called with illegal how argument [$how]. " . "Legal values are 'best', 'cp', and 'ln'."); } } } sub cp { my ($srcFile, $dstFile) = @_; my ($access,$mod) = (stat $srcFile)[8,9]; copy($srcFile,$dstFile); utime $access, $mod + ($Is_VMS ? 1 : 0), $dstFile; _manicopy_chmod($srcFile, $dstFile); } sub ln { my ($srcFile, $dstFile) = @_; # Fix-me - VMS can support links. return &cp if $Is_VMS or ($^O eq 'MSWin32' and Win32::IsWin95()); link($srcFile, $dstFile); unless( _manicopy_chmod($srcFile, $dstFile) ) { unlink $dstFile; return; } 1; } # 1) Strip off all group and world permissions. # 2) Let everyone read it. # 3) If the owner can execute it, everyone can. sub _manicopy_chmod { my($srcFile, $dstFile) = @_; my $perm = 0444 | (stat $srcFile)[2] & 0700; chmod( $perm | ( $perm & 0100 ? 0111 : 0 ), $dstFile ); } # Files that are often modified in the distdir. Don't hard link them. my @Exceptions = qw(MANIFEST META.yml SIGNATURE); sub best { my ($srcFile, $dstFile) = @_; my $is_exception = grep $srcFile =~ /$_/, @Exceptions; if ($is_exception or !$Config{d_link} or -l $srcFile) { cp($srcFile, $dstFile); } else { ln($srcFile, $dstFile) or cp($srcFile, $dstFile); } } sub _macify { my($file) = @_; return $file unless $Is_MacOS; $file =~ s|^\./||; if ($file =~ m|/|) { $file =~ s|/+|:|g; $file = ":$file"; } $file; } sub _maccat { my($f1, $f2) = @_; return "$f1/$f2" unless $Is_MacOS; $f1 .= ":$f2"; $f1 =~ s/([^:]:):/$1/g; return $f1; } sub _unmacify { my($file) = @_; return $file unless $Is_MacOS; $file =~ s|^:||; $file =~ s|([/ \n])|sprintf("\\%03o", unpack("c", $1))|ge; $file =~ y|:|/|; $file; } =item maniadd maniadd({ $file => $comment, ...}); Adds an entry to an existing F unless its already there. $file will be normalized (ie. Unixified). B =cut sub maniadd { my($additions) = shift; _normalize($additions); _fix_manifest($MANIFEST); my $manifest = maniread(); my @needed = grep { !exists $manifest->{$_} } keys %$additions; return 1 unless @needed; open(MANIFEST, ">>$MANIFEST") or die "maniadd() could not open $MANIFEST: $!"; binmode MANIFEST, ':raw'; foreach my $file (_sort @needed) { my $comment = $additions->{$file} || ''; if ($file =~ /\s/) { $file =~ s/([\\'])/\\$1/g; $file = "'$file'"; } printf MANIFEST "%-40s %s\n", $file, $comment; } close MANIFEST or die "Error closing $MANIFEST: $!"; return 1; } # Make sure this MANIFEST is consistently written with native # newlines and has a terminal newline. sub _fix_manifest { my $manifest_file = shift; open MANIFEST, $MANIFEST or die "Could not open $MANIFEST: $!"; local $/; my @manifest = split /(\015\012|\012|\015)/, , -1; close MANIFEST; my $must_rewrite = ""; if ($manifest[-1] eq ""){ # sane case: last line had a terminal newline pop @manifest; for (my $i=1; $i<=$#manifest; $i+=2) { unless ($manifest[$i] eq "\n") { $must_rewrite = "not a newline at pos $i"; last; } } } else { $must_rewrite = "last line without newline"; } if ( $must_rewrite ) { 1 while unlink $MANIFEST; # avoid multiple versions on VMS open MANIFEST, ">", $MANIFEST or die "(must_rewrite=$must_rewrite) Could not open >$MANIFEST: $!"; binmode MANIFEST, ':raw'; for (my $i=0; $i<=$#manifest; $i+=2) { print MANIFEST "$manifest[$i]\n"; } close MANIFEST or die "could not write $MANIFEST: $!"; } } # UNIMPLEMENTED sub _normalize { return; } =back =head2 MANIFEST A list of files in the distribution, one file per line. The MANIFEST always uses Unix filepath conventions even if you're not on Unix. This means F style not F. Anything between white space and an end of line within a C file is considered to be a comment. Any line beginning with # is also a comment. Beginning with ExtUtils::Manifest 1.52, a filename may contain whitespace characters if it is enclosed in single quotes; single quotes or backslashes in that filename must be backslash-escaped. # this a comment some/file some/other/file comment about some/file 'some/third file' comment =head2 MANIFEST.SKIP The file MANIFEST.SKIP may contain regular expressions of files that should be ignored by mkmanifest() and filecheck(). The regular expressions should appear one on each line. Blank lines and lines which start with C<#> are skipped. Use C<\#> if you need a regular expression to start with a C<#>. For example: # Version control files and dirs. \bRCS\b \bCVS\b ,v$ \B\.svn\b # Makemaker generated files and dirs. ^MANIFEST\. ^Makefile$ ^blib/ ^MakeMaker-\d # Temp, old and emacs backup files. ~$ \.old$ ^#.*#$ ^\.# If no MANIFEST.SKIP file is found, a default set of skips will be used, similar to the example above. If you want nothing skipped, simply make an empty MANIFEST.SKIP file. In one's own MANIFEST.SKIP file, certain directives can be used to include the contents of other MANIFEST.SKIP files. At present two such directives are recognized. =over 4 =item #!include_default This inserts the contents of the default MANIFEST.SKIP file =item #!include /Path/to/another/manifest.skip This inserts the contents of the specified external file =back The included contents will be inserted into the MANIFEST.SKIP file in between I<#!start included /path/to/manifest.skip> and I<#!end included /path/to/manifest.skip> markers. The original MANIFEST.SKIP is saved as MANIFEST.SKIP.bak. =head2 EXPORT_OK C<&mkmanifest>, C<&manicheck>, C<&filecheck>, C<&fullcheck>, C<&maniread>, and C<&manicopy> are exportable. =head2 GLOBAL VARIABLES C<$ExtUtils::Manifest::MANIFEST> defaults to C. Changing it results in both a different C and a different C file. This is useful if you want to maintain different distributions for different audiences (say a user version and a developer version including RCS). C<$ExtUtils::Manifest::Quiet> defaults to 0. If set to a true value, all functions act silently. C<$ExtUtils::Manifest::Debug> defaults to 0. If set to a true value, or if PERL_MM_MANIFEST_DEBUG is true, debugging output will be produced. =head1 DIAGNOSTICS All diagnostic output is sent to C. =over 4 =item C I is reported if a file is found which is not in C. =item C I is reported if a file is skipped due to an entry in C. =item C I is reported if a file mentioned in a C file does not exist. =item C I<$!> is reported if C could not be opened. =item C I is reported by mkmanifest() if $Verbose is set and a file is added to MANIFEST. $Verbose is set to 1 by default. =back =head1 ENVIRONMENT =over 4 =item B Turns on debugging =back =head1 SEE ALSO L which has handy targets for most of the functionality. =head1 AUTHOR Andreas Koenig C Currently maintained by the Perl Toolchain Gang. =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1996- by Andreas Koenig. 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 1; PK!žh,ˆˆperl5/ExtUtils/MM.pmnuÏÃ6Ç$package ExtUtils::MM; use strict; use warnings; use ExtUtils::MakeMaker::Config; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::Liblist; require ExtUtils::MakeMaker; our @ISA = qw(ExtUtils::Liblist ExtUtils::MakeMaker); =head1 NAME ExtUtils::MM - OS adjusted ExtUtils::MakeMaker subclass =head1 SYNOPSIS require ExtUtils::MM; my $mm = MM->new(...); =head1 DESCRIPTION B ExtUtils::MM is a subclass of L which automatically chooses the appropriate OS specific subclass for you (ie. L, etc...). It also provides a convenient alias via the MM class (I didn't want MakeMaker modules outside of ExtUtils/). This class might turn out to be a temporary solution, but MM won't go away. =cut { # Convenient alias. package MM; our @ISA = qw(ExtUtils::MM); sub DESTROY {} } sub _is_win95 { # miniperl might not have the Win32 functions available and we need # to run in miniperl. my $have_win32 = eval { require Win32 }; return $have_win32 && defined &Win32::IsWin95 ? Win32::IsWin95() : ! defined $ENV{SYSTEMROOT}; } my %Is = (); $Is{VMS} = $^O eq 'VMS'; $Is{OS2} = $^O eq 'os2'; $Is{MacOS} = $^O eq 'MacOS'; if( $^O eq 'MSWin32' ) { _is_win95() ? $Is{Win95} = 1 : $Is{Win32} = 1; } $Is{UWIN} = $^O =~ /^uwin(-nt)?$/; $Is{Cygwin} = $^O eq 'cygwin'; $Is{NW5} = $Config{osname} eq 'NetWare'; # intentional $Is{BeOS} = ($^O =~ /beos/i or $^O eq 'haiku'); $Is{DOS} = $^O eq 'dos'; if( $Is{NW5} ) { $^O = 'NetWare'; delete $Is{Win32}; } $Is{VOS} = $^O eq 'vos'; $Is{QNX} = $^O eq 'qnx'; $Is{AIX} = $^O eq 'aix'; $Is{Darwin} = $^O eq 'darwin'; $Is{OS390} = $^O eq 'os390'; $Is{Unix} = !grep { $_ } values %Is; map { delete $Is{$_} unless $Is{$_} } keys %Is; _assert( keys %Is == 1 ); my($OS) = keys %Is; my $class = "ExtUtils::MM_$OS"; eval "require $class" unless $INC{"ExtUtils/MM_$OS.pm"}; ## no critic die $@ if $@; unshift @ISA, $class; sub _assert { my $sanity = shift; die sprintf "Assert failed at %s line %d\n", (caller)[1,2] unless $sanity; return; } PK!ZÊXÄÝÝperl5/ExtUtils/MM_OS390.pmnuÏÃ6Ç$package ExtUtils::MM_OS390; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use ExtUtils::MakeMaker::Config; require ExtUtils::MM_Unix; our @ISA = qw(ExtUtils::MM_Unix); =head1 NAME ExtUtils::MM_OS390 - OS390 specific subclass of ExtUtils::MM_Unix =head1 SYNOPSIS Don't use this module directly. Use ExtUtils::MM and let it choose. =head1 DESCRIPTION This is a subclass of L which contains functionality for OS390. Unless otherwise stated it works just like ExtUtils::MM_Unix. =head2 Overriden methods =over =item xs_make_dynamic_lib Defines the recipes for the C section. =cut sub xs_make_dynamic_lib { my ($self, $attribs, $object, $to, $todir, $ldfrom, $exportlist, $dlsyms) = @_; $exportlist = '' if $exportlist ne '$(EXPORT_LIST)'; my $armaybe = $self->_xs_armaybe($attribs); my @m = sprintf '%s : %s $(MYEXTLIB) %s$(DFSEP).exists %s $(PERL_ARCHIVEDEP) $(PERL_ARCHIVE_AFTER) $(INST_DYNAMIC_DEP) %s'."\n", $to, $object, $todir, $exportlist, ($dlsyms || ''); my $dlsyms_arg = $self->xs_dlsyms_arg($dlsyms); if ($armaybe ne ':'){ $ldfrom = 'tmp$(LIB_EXT)'; push(@m," \$(ARMAYBE) cr $ldfrom $object\n"); push(@m," \$(RANLIB) $ldfrom\n"); } # For example in AIX the shared objects/libraries from previous builds # linger quite a while in the shared dynalinker cache even when nobody # is using them. This is painful if one for instance tries to restart # a failed build because the link command will fail unnecessarily 'cos # the shared object/library is 'busy'. push(@m," \$(RM_F) \$\@\n"); my $libs = '$(LDLOADLIBS)'; my $ld_run_path_shell = ""; if ($self->{LD_RUN_PATH} ne "") { $ld_run_path_shell = 'LD_RUN_PATH="$(LD_RUN_PATH)" '; } push @m, sprintf <<'MAKE', $ld_run_path_shell, $dlsyms_arg, $self->xs_obj_opt('$@'), $ldfrom, $libs, $exportlist; %s$(LD) $(LDDLFLAGS) %s $(OTHERLDFLAGS) %s $(MYEXTLIB) %s \ $(PERL_ARCHIVE) %s $(PERL_ARCHIVE_AFTER) %s \ $(INST_DYNAMIC_FIX) $(CHMOD) $(PERM_RWX) $@ MAKE join '', @m; } 1; =back =head1 AUTHOR Michael G Schwern with code from ExtUtils::MM_Unix =head1 SEE ALSO L =cut __END__ PK! Á�ËËperl5/ExtUtils/MANIFEST.SKIPnuÏÃ6Ç$# Avoid version control files. \bRCS\b \bCVS\b \bSCCS\b ,v$ \B\.svn\b \B\.git\b \B\.gitignore\b \b_darcs\b \B\.cvsignore$ # Avoid VMS specific MakeMaker generated files \bDescrip.MMS$ \bDESCRIP.MMS$ \bdescrip.mms$ # Avoid Makemaker generated and utility files. \bMANIFEST\.bak \bMakefile$ \bblib/ \bMakeMaker-\d \bpm_to_blib\.ts$ \bpm_to_blib$ \bblibdirs\.ts$ # 6.18 through 6.25 generated this \b_eumm/ # 7.05_05 and above # Avoid Module::Build generated and utility files. \bBuild$ \b_build/ \bBuild.bat$ \bBuild.COM$ \bBUILD.COM$ \bbuild.com$ # and Module::Build::Tiny generated files \b_build_params$ # Avoid temp and backup files. ~$ \.old$ \#$ \b\.# \.bak$ \.tmp$ \.# \.rej$ \..*\.sw.?$ # Avoid OS-specific files/dirs # Mac OSX metadata \B\.DS_Store # Mac OSX SMB mount metadata files \B\._ # Avoid Devel::Cover and Devel::CoverX::Covered files. \bcover_db\b \bcovered\b # Avoid prove files \B\.prove$ # Avoid MYMETA files ^MYMETA\. PK!Ø¢~<&&perl5/ExtUtils/MM_BeOS.pmnuÏÃ6Ç$package ExtUtils::MM_BeOS; use strict; use warnings; =head1 NAME ExtUtils::MM_BeOS - methods to override UN*X behaviour in ExtUtils::MakeMaker =head1 SYNOPSIS use ExtUtils::MM_BeOS; # Done internally by ExtUtils::MakeMaker if needed =head1 DESCRIPTION See L for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. =over 4 =cut use ExtUtils::MakeMaker::Config; use File::Spec; require ExtUtils::MM_Any; require ExtUtils::MM_Unix; our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix ); our $VERSION = '7.50'; $VERSION =~ tr/_//d; =item os_flavor BeOS is BeOS. =cut sub os_flavor { return('BeOS'); } =item init_linker libperl.a equivalent to be linked to dynamic extensions. =cut sub init_linker { my($self) = shift; $self->{PERL_ARCHIVE} ||= File::Spec->catdir('$(PERL_INC)',$Config{libperl}); $self->{PERL_ARCHIVEDEP} ||= ''; $self->{PERL_ARCHIVE_AFTER} ||= ''; $self->{EXPORT_LIST} ||= ''; } =back =cut 1; __END__ PK!Ñ’¹C66perl5/ExtUtils/ParseXS.podnuÏÃ6Ç$=head1 NAME ExtUtils::ParseXS - converts Perl XS code into C code =head1 SYNOPSIS use ExtUtils::ParseXS; my $pxs = ExtUtils::ParseXS->new; $pxs->process_file( filename => 'foo.xs' ); $pxs->process_file( filename => 'foo.xs', output => 'bar.c', 'C++' => 1, typemap => 'path/to/typemap', hiertype => 1, except => 1, versioncheck => 1, linenumbers => 1, optimize => 1, prototypes => 1, ); # Legacy non-OO interface using a singleton: use ExtUtils::ParseXS qw(process_file); process_file( filename => 'foo.xs' ); =head1 DESCRIPTION C will compile XS code into C code by embedding the constructs necessary to let C functions manipulate Perl values and creates the glue necessary to let Perl access those functions. The compiler uses typemaps to determine how to map C function parameters and variables to Perl values. The compiler will search for typemap files called I. It will use the following search path to find default typemaps, with the rightmost typemap taking precedence. ../../../typemap:../../typemap:../typemap:typemap =head1 EXPORT None by default. C and/or C may be exported upon request. Using the functional interface is discouraged. =head1 METHODS =over 4 =item $pxs->new() Returns a new, empty XS parser/compiler object. =item $pxs->process_file() This method processes an XS file and sends output to a C file. The method may be called as a function (this is the legacy interface) and will then use a singleton as invocant. Named parameters control how the processing is done. The following parameters are accepted: =over 4 =item B Adds C to the C code. Default is false. =item B Retains C<::> in type names so that C++ hierarchical types can be mapped. Default is false. =item B Adds exception handling stubs to the C code. Default is false. =item B Indicates that a user-supplied typemap should take precedence over the default typemaps. A single typemap may be specified as a string, or multiple typemaps can be specified in an array reference, with the last typemap having the highest precedence. =item B Generates prototype code for all xsubs. Default is false. =item B Makes sure at run time that the object file (derived from the C<.xs> file) and the C<.pm> files have the same version number. Default is true. =item B Adds C<#line> directives to the C output so error messages will look like they came from the original XS file. Default is true. =item B Enables certain optimizations. The only optimization that is currently affected is the use of Is by the output C code (see L). Not optimizing may significantly slow down the generated code, but this is the way B of 5.005 and earlier operated. Default is to optimize. =item B Enable recognition of C, C and C declarations. Default is true. =item B Enable recognition of ANSI-like descriptions of function signature. Default is true. =item B I I have no clue what this does. Strips function prefixes? =back =item $pxs->report_error_count() This method returns the number of [a certain kind of] errors encountered during processing of the XS file. The method may be called as a function (this is the legacy interface) and will then use a singleton as invocant. =back =head1 AUTHOR Based on xsubpp code, written by Larry Wall. Maintained by: =over 4 =item * Ken Williams, =item * David Golden, =item * James Keenan, =item * Steffen Mueller, =back =head1 COPYRIGHT Copyright 2002-2014 by Ken Williams, David Golden and other contributors. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Based on the C code by Larry Wall and the Perl 5 Porters, which was released under the same license terms. =head1 SEE ALSO L, ExtUtils::xsubpp, ExtUtils::MakeMaker, L, L. =cut PK!ÂŽ3^«h«hperl5/ExtUtils/Typemaps.pmnuÏÃ6Ç$package ExtUtils::Typemaps; use 5.006001; use strict; use warnings; our $VERSION = '3.35'; require ExtUtils::ParseXS; require ExtUtils::ParseXS::Constants; require ExtUtils::Typemaps::InputMap; require ExtUtils::Typemaps::OutputMap; require ExtUtils::Typemaps::Type; =head1 NAME ExtUtils::Typemaps - Read/Write/Modify Perl/XS typemap files =head1 SYNOPSIS # read/create file my $typemap = ExtUtils::Typemaps->new(file => 'typemap'); # alternatively create an in-memory typemap # $typemap = ExtUtils::Typemaps->new(); # alternatively create an in-memory typemap by parsing a string # $typemap = ExtUtils::Typemaps->new(string => $sometypemap); # add a mapping $typemap->add_typemap(ctype => 'NV', xstype => 'T_NV'); $typemap->add_inputmap( xstype => 'T_NV', code => '$var = ($type)SvNV($arg);' ); $typemap->add_outputmap( xstype => 'T_NV', code => 'sv_setnv($arg, (NV)$var);' ); $typemap->add_string(string => $typemapstring); # will be parsed and merged # remove a mapping (same for remove_typemap and remove_outputmap...) $typemap->remove_inputmap(xstype => 'SomeType'); # save a typemap to a file $typemap->write(file => 'anotherfile.map'); # merge the other typemap into this one $typemap->merge(typemap => $another_typemap); =head1 DESCRIPTION This module can read, modify, create and write Perl XS typemap files. If you don't know what a typemap is, please confer the L and L manuals. The module is not entirely round-trip safe: For example it currently simply strips all comments. The order of entries in the maps is, however, preserved. We check for duplicate entries in the typemap, but do not check for missing C entries for C or C entries since these might be hidden in a different typemap. =head1 METHODS =cut =head2 new Returns a new typemap object. Takes an optional C parameter. If set, the given file will be read. If the file doesn't exist, an empty typemap is returned. Alternatively, if the C parameter is given, the supplied string will be parsed instead of a file. =cut sub new { my $class = shift; my %args = @_; if (defined $args{file} and defined $args{string}) { die("Cannot handle both 'file' and 'string' arguments to constructor"); } my $self = bless { file => undef, %args, typemap_section => [], typemap_lookup => {}, input_section => [], input_lookup => {}, output_section => [], output_lookup => {}, } => $class; $self->_init(); return $self; } sub _init { my $self = shift; if (defined $self->{string}) { $self->_parse(\($self->{string}), $self->{lineno_offset}, $self->{fake_filename}); delete $self->{string}; } elsif (defined $self->{file} and -e $self->{file}) { open my $fh, '<', $self->{file} or die "Cannot open typemap file '" . $self->{file} . "' for reading: $!"; local $/ = undef; my $string = <$fh>; $self->_parse(\$string, $self->{lineno_offset}, $self->{file}); } } =head2 file Get/set the file that the typemap is written to when the C method is called. =cut sub file { $_[0]->{file} = $_[1] if @_ > 1; $_[0]->{file} } =head2 add_typemap Add a C entry to the typemap. Required named arguments: The C (e.g. C 'double'>) and the C (e.g. C 'T_NV'>). Optional named arguments: C 1> forces removal/replacement of existing C entries of the same C. C 1> triggers a I<"first come first serve"> logic by which new entries that conflict with existing entries are silently ignored. As an alternative to the named parameters usage, you may pass in an C object as first argument, a copy of which will be added to the typemap. In that case, only the C or C named parameters may be used after the object. Example: $map->add_typemap($type_obj, replace => 1); =cut sub add_typemap { my $self = shift; my $type; my %args; if ((@_ % 2) == 1) { my $orig = shift; $type = $orig->new(); %args = @_; } else { %args = @_; my $ctype = $args{ctype}; die("Need ctype argument") if not defined $ctype; my $xstype = $args{xstype}; die("Need xstype argument") if not defined $xstype; $type = ExtUtils::Typemaps::Type->new( xstype => $xstype, 'prototype' => $args{'prototype'}, ctype => $ctype, ); } if ($args{skip} and $args{replace}) { die("Cannot use both 'skip' and 'replace'"); } if ($args{replace}) { $self->remove_typemap(ctype => $type->ctype); } elsif ($args{skip}) { return() if exists $self->{typemap_lookup}{$type->ctype}; } else { $self->validate(typemap_xstype => $type->xstype, ctype => $type->ctype); } # store push @{$self->{typemap_section}}, $type; # remember type for lookup, too. $self->{typemap_lookup}{$type->tidy_ctype} = $#{$self->{typemap_section}}; return 1; } =head2 add_inputmap Add an C entry to the typemap. Required named arguments: The C (e.g. C 'T_NV'>) and the C to associate with it for input. Optional named arguments: C 1> forces removal/replacement of existing C entries of the same C. C 1> triggers a I<"first come first serve"> logic by which new entries that conflict with existing entries are silently ignored. As an alternative to the named parameters usage, you may pass in an C object as first argument, a copy of which will be added to the typemap. In that case, only the C or C named parameters may be used after the object. Example: $map->add_inputmap($type_obj, replace => 1); =cut sub add_inputmap { my $self = shift; my $input; my %args; if ((@_ % 2) == 1) { my $orig = shift; $input = $orig->new(); %args = @_; } else { %args = @_; my $xstype = $args{xstype}; die("Need xstype argument") if not defined $xstype; my $code = $args{code}; die("Need code argument") if not defined $code; $input = ExtUtils::Typemaps::InputMap->new( xstype => $xstype, code => $code, ); } if ($args{skip} and $args{replace}) { die("Cannot use both 'skip' and 'replace'"); } if ($args{replace}) { $self->remove_inputmap(xstype => $input->xstype); } elsif ($args{skip}) { return() if exists $self->{input_lookup}{$input->xstype}; } else { $self->validate(inputmap_xstype => $input->xstype); } # store push @{$self->{input_section}}, $input; # remember type for lookup, too. $self->{input_lookup}{$input->xstype} = $#{$self->{input_section}}; return 1; } =head2 add_outputmap Add an C entry to the typemap. Works exactly the same as C. =cut sub add_outputmap { my $self = shift; my $output; my %args; if ((@_ % 2) == 1) { my $orig = shift; $output = $orig->new(); %args = @_; } else { %args = @_; my $xstype = $args{xstype}; die("Need xstype argument") if not defined $xstype; my $code = $args{code}; die("Need code argument") if not defined $code; $output = ExtUtils::Typemaps::OutputMap->new( xstype => $xstype, code => $code, ); } if ($args{skip} and $args{replace}) { die("Cannot use both 'skip' and 'replace'"); } if ($args{replace}) { $self->remove_outputmap(xstype => $output->xstype); } elsif ($args{skip}) { return() if exists $self->{output_lookup}{$output->xstype}; } else { $self->validate(outputmap_xstype => $output->xstype); } # store push @{$self->{output_section}}, $output; # remember type for lookup, too. $self->{output_lookup}{$output->xstype} = $#{$self->{output_section}}; return 1; } =head2 add_string Parses a string as a typemap and merge it into the typemap object. Required named argument: C to specify the string to parse. =cut sub add_string { my $self = shift; my %args = @_; die("Need 'string' argument") if not defined $args{string}; # no, this is not elegant. my $other = ExtUtils::Typemaps->new(string => $args{string}); $self->merge(typemap => $other); } =head2 remove_typemap Removes a C entry from the typemap. Required named argument: C to specify the entry to remove from the typemap. Alternatively, you may pass a single C object. =cut sub remove_typemap { my $self = shift; my $ctype; if (@_ > 1) { my %args = @_; $ctype = $args{ctype}; die("Need ctype argument") if not defined $ctype; $ctype = tidy_type($ctype); } else { $ctype = $_[0]->tidy_ctype; } return $self->_remove($ctype, $self->{typemap_section}, $self->{typemap_lookup}); } =head2 remove_inputmap Removes an C entry from the typemap. Required named argument: C to specify the entry to remove from the typemap. Alternatively, you may pass a single C object. =cut sub remove_inputmap { my $self = shift; my $xstype; if (@_ > 1) { my %args = @_; $xstype = $args{xstype}; die("Need xstype argument") if not defined $xstype; } else { $xstype = $_[0]->xstype; } return $self->_remove($xstype, $self->{input_section}, $self->{input_lookup}); } =head2 remove_inputmap Removes an C entry from the typemap. Required named argument: C to specify the entry to remove from the typemap. Alternatively, you may pass a single C object. =cut sub remove_outputmap { my $self = shift; my $xstype; if (@_ > 1) { my %args = @_; $xstype = $args{xstype}; die("Need xstype argument") if not defined $xstype; } else { $xstype = $_[0]->xstype; } return $self->_remove($xstype, $self->{output_section}, $self->{output_lookup}); } sub _remove { my $self = shift; my $rm = shift; my $array = shift; my $lookup = shift; # Just fetch the index of the item from the lookup table my $index = $lookup->{$rm}; return() if not defined $index; # Nuke the item from storage splice(@$array, $index, 1); # Decrement the storage position of all items thereafter foreach my $key (keys %$lookup) { if ($lookup->{$key} > $index) { $lookup->{$key}--; } } return(); } =head2 get_typemap Fetches an entry of the TYPEMAP section of the typemap. Mandatory named arguments: The C of the entry. Returns the C object for the entry if found. =cut sub get_typemap { my $self = shift; die("Need named parameters, got uneven number") if @_ % 2; my %args = @_; my $ctype = $args{ctype}; die("Need ctype argument") if not defined $ctype; $ctype = tidy_type($ctype); my $index = $self->{typemap_lookup}{$ctype}; return() if not defined $index; return $self->{typemap_section}[$index]; } =head2 get_inputmap Fetches an entry of the INPUT section of the typemap. Mandatory named arguments: The C of the entry or the C of the typemap that can be used to find the C. To wit, the following pieces of code are equivalent: my $type = $typemap->get_typemap(ctype => $ctype) my $input_map = $typemap->get_inputmap(xstype => $type->xstype); my $input_map = $typemap->get_inputmap(ctype => $ctype); Returns the C object for the entry if found. =cut sub get_inputmap { my $self = shift; die("Need named parameters, got uneven number") if @_ % 2; my %args = @_; my $xstype = $args{xstype}; my $ctype = $args{ctype}; die("Need xstype or ctype argument") if not defined $xstype and not defined $ctype; die("Need xstype OR ctype arguments, not both") if defined $xstype and defined $ctype; if (defined $ctype) { my $tm = $self->get_typemap(ctype => $ctype); $xstype = $tm && $tm->xstype; return() if not defined $xstype; } my $index = $self->{input_lookup}{$xstype}; return() if not defined $index; return $self->{input_section}[$index]; } =head2 get_outputmap Fetches an entry of the OUTPUT section of the typemap. Mandatory named arguments: The C of the entry or the C of the typemap that can be used to resolve the C. (See above for an example.) Returns the C object for the entry if found. =cut sub get_outputmap { my $self = shift; die("Need named parameters, got uneven number") if @_ % 2; my %args = @_; my $xstype = $args{xstype}; my $ctype = $args{ctype}; die("Need xstype or ctype argument") if not defined $xstype and not defined $ctype; die("Need xstype OR ctype arguments, not both") if defined $xstype and defined $ctype; if (defined $ctype) { my $tm = $self->get_typemap(ctype => $ctype); $xstype = $tm && $tm->xstype; return() if not defined $xstype; } my $index = $self->{output_lookup}{$xstype}; return() if not defined $index; return $self->{output_section}[$index]; } =head2 write Write the typemap to a file. Optionally takes a C argument. If given, the typemap will be written to the specified file. If not, the typemap is written to the currently stored file name (see L above, this defaults to the file it was read from if any). =cut sub write { my $self = shift; my %args = @_; my $file = defined $args{file} ? $args{file} : $self->file(); die("write() needs a file argument (or set the file name of the typemap using the 'file' method)") if not defined $file; open my $fh, '>', $file or die "Cannot open typemap file '$file' for writing: $!"; print $fh $self->as_string(); close $fh; } =head2 as_string Generates and returns the string form of the typemap. =cut sub as_string { my $self = shift; my $typemap = $self->{typemap_section}; my @code; push @code, "TYPEMAP\n"; foreach my $entry (@$typemap) { # type kind proto # /^(.*?\S)\s+(\S+)\s*($ExtUtils::ParseXS::Constants::PrototypeRegexp*)$/o push @code, $entry->ctype . "\t" . $entry->xstype . ($entry->proto ne '' ? "\t".$entry->proto : '') . "\n"; } my $input = $self->{input_section}; if (@$input) { push @code, "\nINPUT\n"; foreach my $entry (@$input) { push @code, $entry->xstype, "\n", $entry->code, "\n"; } } my $output = $self->{output_section}; if (@$output) { push @code, "\nOUTPUT\n"; foreach my $entry (@$output) { push @code, $entry->xstype, "\n", $entry->code, "\n"; } } return join '', @code; } =head2 as_embedded_typemap Generates and returns the string form of the typemap with the appropriate prefix around it for verbatim inclusion into an XS file as an embedded typemap. This will return a string like TYPEMAP: <as_string; my @ident_cand = qw(END_TYPEMAP END_OF_TYPEMAP END); my $icand = 0; my $cand_suffix = ""; while ($string =~ /^\Q$ident_cand[$icand]$cand_suffix\E\s*$/m) { $icand++; if ($icand == @ident_cand) { $icand = 0; ++$cand_suffix; } } my $marker = "$ident_cand[$icand]$cand_suffix"; return "TYPEMAP: <<$marker;\n$string\n$marker\n"; } =head2 merge Merges a given typemap into the object. Note that a failed merge operation leaves the object in an inconsistent state so clone it if necessary. Mandatory named arguments: Either C $another_typemap_obj> or C $path_to_typemap_file> but not both. Optional arguments: C 1> to force replacement of existing typemap entries without warning or C 1> to skip entries that exist already in the typemap. =cut sub merge { my $self = shift; my %args = @_; if (exists $args{typemap} and exists $args{file}) { die("Need {file} OR {typemap} argument. Not both!"); } elsif (not exists $args{typemap} and not exists $args{file}) { die("Need {file} or {typemap} argument!"); } my @params; push @params, 'replace' => $args{replace} if exists $args{replace}; push @params, 'skip' => $args{skip} if exists $args{skip}; my $typemap = $args{typemap}; if (not defined $typemap) { $typemap = ref($self)->new(file => $args{file}, @params); } # FIXME breaking encapsulation. Add accessor code. foreach my $entry (@{$typemap->{typemap_section}}) { $self->add_typemap( $entry, @params ); } foreach my $entry (@{$typemap->{input_section}}) { $self->add_inputmap( $entry, @params ); } foreach my $entry (@{$typemap->{output_section}}) { $self->add_outputmap( $entry, @params ); } return 1; } =head2 is_empty Returns a bool indicating whether this typemap is entirely empty. =cut sub is_empty { my $self = shift; return @{ $self->{typemap_section} } == 0 && @{ $self->{input_section} } == 0 && @{ $self->{output_section} } == 0; } =head2 list_mapped_ctypes Returns a list of the C types that are mappable by this typemap object. =cut sub list_mapped_ctypes { my $self = shift; return sort keys %{ $self->{typemap_lookup} }; } =head2 _get_typemap_hash Returns a hash mapping the C types to the XS types: { 'char **' => 'T_PACKEDARRAY', 'bool_t' => 'T_IV', 'AV *' => 'T_AVREF', 'InputStream' => 'T_IN', 'double' => 'T_DOUBLE', # ... } This is documented because it is used by C, but it's not intended for general consumption. May be removed at any time. =cut sub _get_typemap_hash { my $self = shift; my $lookup = $self->{typemap_lookup}; my $storage = $self->{typemap_section}; my %rv; foreach my $ctype (keys %$lookup) { $rv{$ctype} = $storage->[ $lookup->{$ctype} ]->xstype; } return \%rv; } =head2 _get_inputmap_hash Returns a hash mapping the XS types (identifiers) to the corresponding INPUT code: { 'T_CALLBACK' => ' $var = make_perl_cb_$type($arg) ', 'T_OUT' => ' $var = IoOFP(sv_2io($arg)) ', 'T_REF_IV_PTR' => ' if (sv_isa($arg, \\"${ntype}\\")) { # ... } This is documented because it is used by C, but it's not intended for general consumption. May be removed at any time. =cut sub _get_inputmap_hash { my $self = shift; my $lookup = $self->{input_lookup}; my $storage = $self->{input_section}; my %rv; foreach my $xstype (keys %$lookup) { $rv{$xstype} = $storage->[ $lookup->{$xstype} ]->code; # Squash trailing whitespace to one line break # This isn't strictly necessary, but makes the output more similar # to the original ExtUtils::ParseXS. $rv{$xstype} =~ s/\s*\z/\n/; } return \%rv; } =head2 _get_outputmap_hash Returns a hash mapping the XS types (identifiers) to the corresponding OUTPUT code: { 'T_CALLBACK' => ' sv_setpvn($arg, $var.context.value().chp(), $var.context.value().size()); ', 'T_OUT' => ' { GV *gv = newGVgen("$Package"); if ( do_open(gv, "+>&", 3, FALSE, 0, 0, $var) ) sv_setsv( $arg, sv_bless(newRV((SV*)gv), gv_stashpv("$Package",1)) ); else $arg = &PL_sv_undef; } ', # ... } This is documented because it is used by C, but it's not intended for general consumption. May be removed at any time. =cut sub _get_outputmap_hash { my $self = shift; my $lookup = $self->{output_lookup}; my $storage = $self->{output_section}; my %rv; foreach my $xstype (keys %$lookup) { $rv{$xstype} = $storage->[ $lookup->{$xstype} ]->code; # Squash trailing whitespace to one line break # This isn't strictly necessary, but makes the output more similar # to the original ExtUtils::ParseXS. $rv{$xstype} =~ s/\s*\z/\n/; } return \%rv; } =head2 _get_prototype_hash Returns a hash mapping the C types of the typemap to their corresponding prototypes. { 'char **' => '$', 'bool_t' => '$', 'AV *' => '$', 'InputStream' => '$', 'double' => '$', # ... } This is documented because it is used by C, but it's not intended for general consumption. May be removed at any time. =cut sub _get_prototype_hash { my $self = shift; my $lookup = $self->{typemap_lookup}; my $storage = $self->{typemap_section}; my %rv; foreach my $ctype (keys %$lookup) { $rv{$ctype} = $storage->[ $lookup->{$ctype} ]->proto || '$'; } return \%rv; } # make sure that the provided types wouldn't collide with what's # in the object already. sub validate { my $self = shift; my %args = @_; if ( exists $args{ctype} and exists $self->{typemap_lookup}{tidy_type($args{ctype})} ) { die("Multiple definition of ctype '$args{ctype}' in TYPEMAP section"); } if ( exists $args{inputmap_xstype} and exists $self->{input_lookup}{$args{inputmap_xstype}} ) { die("Multiple definition of xstype '$args{inputmap_xstype}' in INPUTMAP section"); } if ( exists $args{outputmap_xstype} and exists $self->{output_lookup}{$args{outputmap_xstype}} ) { die("Multiple definition of xstype '$args{outputmap_xstype}' in OUTPUTMAP section"); } return 1; } =head2 clone Creates and returns a clone of a full typemaps object. Takes named parameters: If C is true, the clone will share the actual individual type/input/outputmap objects, but not share their storage. Use with caution. Without C, the clone will be fully independent. =cut sub clone { my $proto = shift; my %args = @_; my $self; if ($args{shallow}) { $self = bless( { %$proto, typemap_section => [@{$proto->{typemap_section}}], typemap_lookup => {%{$proto->{typemap_lookup}}}, input_section => [@{$proto->{input_section}}], input_lookup => {%{$proto->{input_lookup}}}, output_section => [@{$proto->{output_section}}], output_lookup => {%{$proto->{output_lookup}}}, } => ref($proto) ); } else { $self = bless( { %$proto, typemap_section => [map $_->new, @{$proto->{typemap_section}}], typemap_lookup => {%{$proto->{typemap_lookup}}}, input_section => [map $_->new, @{$proto->{input_section}}], input_lookup => {%{$proto->{input_lookup}}}, output_section => [map $_->new, @{$proto->{output_section}}], output_lookup => {%{$proto->{output_lookup}}}, } => ref($proto) ); } return $self; } =head2 tidy_type Function to (heuristically) canonicalize a C type. Works to some degree with C++ types. $halfway_canonical_type = tidy_type($ctype); Moved from C. =cut sub tidy_type { local $_ = shift; # for templated C++ types, do some bit of flawed canonicalization # wrt. templates at least if (/[<>]/) { s/\s*([<>])\s*/$1/g; s/>>/> >/g; } # rationalise any '*' by joining them into bunches and removing whitespace s#\s*(\*+)\s*#$1#g; s#(\*+)# $1 #g ; # trim leading & trailing whitespace s/^\s+//; s/\s+$//; # change multiple whitespace into a single space s/\s+/ /g; $_; } sub _parse { my $self = shift; my $stringref = shift; my $lineno_offset = shift; $lineno_offset = 0 if not defined $lineno_offset; my $filename = shift; $filename = '' if not defined $filename; my $replace = $self->{replace}; my $skip = $self->{skip}; die "Can only replace OR skip" if $replace and $skip; my @add_params; push @add_params, replace => 1 if $replace; push @add_params, skip => 1 if $skip; # TODO comments should round-trip, currently ignoring # TODO order of sections, multiple sections of same type # Heavily influenced by ExtUtils::ParseXS my $section = 'typemap'; my $lineno = $lineno_offset; my $junk = ""; my $current = \$junk; my @input_expr; my @output_expr; while ($$stringref =~ /^(.*)$/gcm) { local $_ = $1; ++$lineno; chomp; next if /^\s*#/; if (/^INPUT\s*$/) { $section = 'input'; $current = \$junk; next; } elsif (/^OUTPUT\s*$/) { $section = 'output'; $current = \$junk; next; } elsif (/^TYPEMAP\s*$/) { $section = 'typemap'; $current = \$junk; next; } if ($section eq 'typemap') { my $line = $_; s/^\s+//; s/\s+$//; next if $_ eq '' or /^#/; my($type, $kind, $proto) = /^(.*?\S)\s+(\S+)\s*($ExtUtils::ParseXS::Constants::PrototypeRegexp*)$/o or warn("Warning: File '$filename' Line $lineno '$line' TYPEMAP entry needs 2 or 3 columns\n"), next; # prototype defaults to '$' $proto = '$' unless $proto; warn("Warning: File '$filename' Line $lineno '$line' Invalid prototype '$proto'\n") unless _valid_proto_string($proto); $self->add_typemap( ExtUtils::Typemaps::Type->new( xstype => $kind, proto => $proto, ctype => $type ), @add_params ); } elsif (/^\s/) { s/\s+$//; $$current .= $$current eq '' ? $_ : "\n".$_; } elsif ($_ eq '') { next; } elsif ($section eq 'input') { s/\s+$//; push @input_expr, {xstype => $_, code => ''}; $current = \$input_expr[-1]{code}; } else { # output section s/\s+$//; push @output_expr, {xstype => $_, code => ''}; $current = \$output_expr[-1]{code}; } } # end while lines foreach my $inexpr (@input_expr) { $self->add_inputmap( ExtUtils::Typemaps::InputMap->new(%$inexpr), @add_params ); } foreach my $outexpr (@output_expr) { $self->add_outputmap( ExtUtils::Typemaps::OutputMap->new(%$outexpr), @add_params ); } return 1; } # taken from ExtUtils::ParseXS sub _valid_proto_string { my $string = shift; if ($string =~ /^$ExtUtils::ParseXS::Constants::PrototypeRegexp+$/o) { return $string; } return 0 ; } # taken from ExtUtils::ParseXS (C_string) sub _escape_backslashes { my $string = shift; $string =~ s[\\][\\\\]g; $string; } =head1 CAVEATS Inherits some evil code from C. =head1 SEE ALSO The parser is heavily inspired from the one in L. For details on typemaps: L, L. =head1 AUTHOR Steffen Mueller C<> =head1 COPYRIGHT & LICENSE Copyright 2009, 2010, 2011, 2012, 2013 Steffen Mueller This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK!$Ñ=¥‹‹perl5/ExtUtils/MM_QNX.pmnuÏÃ6Ç$package ExtUtils::MM_QNX; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Unix; our @ISA = qw(ExtUtils::MM_Unix); =head1 NAME ExtUtils::MM_QNX - QNX specific subclass of ExtUtils::MM_Unix =head1 SYNOPSIS Don't use this module directly. Use ExtUtils::MM and let it choose. =head1 DESCRIPTION This is a subclass of L which contains functionality for QNX. Unless otherwise stated it works just like ExtUtils::MM_Unix. =head2 Overridden methods =head3 extra_clean_files Add .err files corresponding to each .c file. =cut sub extra_clean_files { my $self = shift; my @errfiles = @{$self->{C}}; for ( @errfiles ) { s/.c$/.err/; } return( @errfiles, 'perlmain.err' ); } =head1 AUTHOR Michael G Schwern with code from ExtUtils::MM_Unix =head1 SEE ALSO L =cut 1; PK!Š©öÁöÁperl5/ExtUtils/MM_Unix.pmnuÏÃ6Ç$package ExtUtils::MM_Unix; require 5.006; use strict; use warnings; use Carp; use ExtUtils::MakeMaker::Config; use File::Basename qw(basename dirname); our %Config_Override; use ExtUtils::MakeMaker qw($Verbose neatvalue _sprintf562); # If we make $VERSION an our variable parse_version() breaks use vars qw($VERSION); $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Any; our @ISA = qw(ExtUtils::MM_Any); my %Is; BEGIN { $Is{OS2} = $^O eq 'os2'; $Is{Win32} = $^O eq 'MSWin32' || $Config{osname} eq 'NetWare'; $Is{Dos} = $^O eq 'dos'; $Is{VMS} = $^O eq 'VMS'; $Is{OSF} = $^O eq 'dec_osf'; $Is{IRIX} = $^O eq 'irix'; $Is{NetBSD} = $^O eq 'netbsd'; $Is{Interix} = $^O eq 'interix'; $Is{SunOS4} = $^O eq 'sunos'; $Is{Solaris} = $^O eq 'solaris'; $Is{SunOS} = $Is{SunOS4} || $Is{Solaris}; $Is{BSD} = ($^O =~ /^(?:free|net|open)bsd$/ or grep( $^O eq $_, qw(bsdos interix dragonfly) ) ); $Is{Android} = $^O =~ /android/; if ( $^O eq 'darwin' && $^X eq '/usr/bin/perl' ) { my @osvers = split /\./, $Config{osvers}; $Is{ApplCor} = ( $osvers[0] >= 18 ); } } BEGIN { if( $Is{VMS} ) { # For things like vmsify() require VMS::Filespec; VMS::Filespec->import; } } =head1 NAME ExtUtils::MM_Unix - methods used by ExtUtils::MakeMaker =head1 SYNOPSIS require ExtUtils::MM_Unix; =head1 DESCRIPTION The methods provided by this package are designed to be used in conjunction with L. When MakeMaker writes a Makefile, it creates one or more objects that inherit their methods from a package L. MM itself doesn't provide any methods, but it ISA ExtUtils::MM_Unix class. The inheritance tree of MM lets operating specific packages take the responsibility for all the methods provided by MM_Unix. We are trying to reduce the number of the necessary overrides by defining rather primitive operations within ExtUtils::MM_Unix. If you are going to write a platform specific MM package, please try to limit the necessary overrides to primitive methods, and if it is not possible to do so, let's work out how to achieve that gain. If you are overriding any of these methods in your Makefile.PL (in the MY class), please report that to the makemaker mailing list. We are trying to minimize the necessary method overrides and switch to data driven Makefile.PLs wherever possible. In the long run less methods will be overridable via the MY class. =head1 METHODS The following description of methods is still under development. Please refer to the code for not suitably documented sections and complain loudly to the makemaker@perl.org mailing list. Better yet, provide a patch. Not all of the methods below are overridable in a Makefile.PL. Overridable methods are marked as (o). All methods are overridable by a platform specific MM_*.pm file. Cross-platform methods are being moved into L. If you can't find something that used to be in here, look in MM_Any. =cut # So we don't have to keep calling the methods over and over again, # we have these globals to cache the values. Faster and shrtr. my $Curdir = __PACKAGE__->curdir; my $Updir = __PACKAGE__->updir; =head2 Methods =over 4 =item os_flavor Simply says that we're Unix. =cut sub os_flavor { return('Unix'); } =item c_o (o) Defines the suffix rules to compile different flavors of C files to object files. =cut sub c_o { # --- Translation Sections --- my($self) = shift; return '' unless $self->needs_linking(); my(@m); my $command = '$(CCCMD)'; my $flags = '$(CCCDLFLAGS) "-I$(PERL_INC)" $(PASTHRU_DEFINE) $(DEFINE)'; if ( $Is{ApplCor} ) { $flags =~ s/"-I(\$\(PERL_INC\))"/-iwithsysroot "$1"/; } if (my $cpp = $Config{cpprun}) { my $cpp_cmd = $self->const_cccmd; $cpp_cmd =~ s/^CCCMD\s*=\s*\$\(CC\)/$cpp/; push @m, qq{ .c.i: $cpp_cmd $flags \$*.c > \$*.i }; } my $m_o = $self->{XSMULTI} ? $self->xs_obj_opt('$*.s') : ''; push @m, sprintf <<'EOF', $command, $flags, $m_o; .c.s : %s -S %s $*.c %s EOF my @exts = qw(c cpp cxx cc); push @exts, 'C' if !$Is{OS2} and !$Is{Win32} and !$Is{Dos}; #Case-specific $m_o = $self->{XSMULTI} ? $self->xs_obj_opt('$*$(OBJ_EXT)') : ''; my $dbgout = $self->dbgoutflag; for my $ext (@exts) { push @m, "\n.$ext\$(OBJ_EXT) :\n\t$command $flags " .($dbgout?"$dbgout ":'') ."\$*.$ext" . ( $m_o ? " $m_o" : '' ) . "\n"; } return join "", @m; } =item xs_obj_opt Takes the object file as an argument, and returns the portion of compile command-line that will output to the specified object file. =cut sub xs_obj_opt { my ($self, $output_file) = @_; "-o $output_file"; } =item dbgoutflag Returns a CC flag that tells the CC to emit a separate debugging symbol file when compiling an object file. =cut sub dbgoutflag { ''; } =item cflags (o) Does very much the same as the cflags script in the perl distribution. It doesn't return the whole compiler command line, but initializes all of its parts. The const_cccmd method then actually returns the definition of the CCCMD macro which uses these parts. =cut #' sub cflags { my($self,$libperl)=@_; return $self->{CFLAGS} if $self->{CFLAGS}; return '' unless $self->needs_linking(); my($prog, $uc, $perltype, %cflags); $libperl ||= $self->{LIBPERL_A} || "libperl$self->{LIB_EXT}" ; $libperl =~ s/\.\$\(A\)$/$self->{LIB_EXT}/; @cflags{qw(cc ccflags optimize shellflags)} = @Config{qw(cc ccflags optimize shellflags)}; # Perl 5.21.4 adds the (gcc) warning (-Wall ...) and std (-std=c89) # flags to the %Config, and the modules in the core should be built # with the warning flags, but NOT the -std=c89 flags (the latter # would break using any system header files that are strict C99). my @ccextraflags = qw(ccwarnflags); if ($ENV{PERL_CORE}) { for my $x (@ccextraflags) { if (exists $Config{$x}) { $cflags{$x} = $Config{$x}; } } } my($optdebug) = ""; $cflags{shellflags} ||= ''; my(%map) = ( D => '-DDEBUGGING', E => '-DEMBED', DE => '-DDEBUGGING -DEMBED', M => '-DEMBED -DMULTIPLICITY', DM => '-DDEBUGGING -DEMBED -DMULTIPLICITY', ); if ($libperl =~ /libperl(\w*)\Q$self->{LIB_EXT}/){ $uc = uc($1); } else { $uc = ""; # avoid warning } $perltype = $map{$uc} ? $map{$uc} : ""; if ($uc =~ /^D/) { $optdebug = "-g"; } my($name); ( $name = $self->{NAME} . "_cflags" ) =~ s/:/_/g ; if ($prog = $Config{$name}) { # Expand hints for this extension via the shell print "Processing $name hint:\n" if $Verbose; my(@o)=`cc=\"$cflags{cc}\" ccflags=\"$cflags{ccflags}\" optimize=\"$cflags{optimize}\" perltype=\"$cflags{perltype}\" optdebug=\"$cflags{optdebug}\" eval '$prog' echo cc=\$cc echo ccflags=\$ccflags echo optimize=\$optimize echo perltype=\$perltype echo optdebug=\$optdebug `; foreach my $line (@o){ chomp $line; if ($line =~ /(.*?)=\s*(.*)\s*$/){ $cflags{$1} = $2; print " $1 = $2\n" if $Verbose; } else { print "Unrecognised result from hint: '$line'\n"; } } } if ($optdebug) { $cflags{optimize} = $optdebug; } for (qw(ccflags optimize perltype)) { $cflags{$_} ||= ''; $cflags{$_} =~ s/^\s+//; $cflags{$_} =~ s/\s+/ /g; $cflags{$_} =~ s/\s+$//; $self->{uc $_} ||= $cflags{$_}; } if ($self->{POLLUTE}) { $self->{CCFLAGS} .= ' -DPERL_POLLUTE '; } for my $x (@ccextraflags) { next unless exists $cflags{$x}; $self->{CCFLAGS} .= $cflags{$x} =~ m!^\s! ? $cflags{$x} : ' ' . $cflags{$x}; } my $pollute = ''; if ($Config{usemymalloc} and not $Config{bincompat5005} and not $Config{ccflags} =~ /-DPERL_POLLUTE_MALLOC\b/ and $self->{PERL_MALLOC_OK}) { $pollute = '$(PERL_MALLOC_DEF)'; } return $self->{CFLAGS} = qq{ CCFLAGS = $self->{CCFLAGS} OPTIMIZE = $self->{OPTIMIZE} PERLTYPE = $self->{PERLTYPE} MPOLLUTE = $pollute }; } =item const_cccmd (o) Returns the full compiler call for C programs and stores the definition in CONST_CCCMD. =cut sub const_cccmd { my($self,$libperl)=@_; return $self->{CONST_CCCMD} if $self->{CONST_CCCMD}; return '' unless $self->needs_linking(); return $self->{CONST_CCCMD} = q{CCCMD = $(CC) -c $(PASTHRU_INC) $(INC) \\ $(CCFLAGS) $(OPTIMIZE) \\ $(PERLTYPE) $(MPOLLUTE) $(DEFINE_VERSION) \\ $(XS_DEFINE_VERSION)}; } =item const_config (o) Sets SHELL if needed, then defines a couple of constants in the Makefile that are imported from %Config. =cut sub const_config { # --- Constants Sections --- my($self) = shift; my @m = $self->specify_shell(); # Usually returns empty string push @m, <<"END"; # These definitions are from config.sh (via $INC{'Config.pm'}). # They may have been overridden via Makefile.PL or on the command line. END my(%once_only); foreach my $key (@{$self->{CONFIG}}){ # SITE*EXP macros are defined in &constants; avoid duplicates here next if $once_only{$key}; push @m, uc($key) , ' = ' , $self->{uc $key}, "\n"; $once_only{$key} = 1; } join('', @m); } =item const_loadlibs (o) Defines EXTRALIBS, LDLOADLIBS, BSLOADLIBS, LD_RUN_PATH. See L for details. =cut sub const_loadlibs { my($self) = shift; return "" unless $self->needs_linking; my @m; push @m, qq{ # $self->{NAME} might depend on some other libraries: # See ExtUtils::Liblist for details # }; for my $tmp (qw/ EXTRALIBS LDLOADLIBS BSLOADLIBS /) { next unless defined $self->{$tmp}; push @m, "$tmp = $self->{$tmp}\n"; } # don't set LD_RUN_PATH if empty for my $tmp (qw/ LD_RUN_PATH /) { next unless $self->{$tmp}; push @m, "$tmp = $self->{$tmp}\n"; } return join "", @m; } =item constants (o) my $make_frag = $mm->constants; Prints out macros for lots of constants. =cut sub constants { my($self) = @_; my @m = (); $self->{DFSEP} = '$(DIRFILESEP)'; # alias for internal use for my $macro (qw( AR_STATIC_ARGS DIRFILESEP DFSEP NAME NAME_SYM VERSION VERSION_MACRO VERSION_SYM DEFINE_VERSION XS_VERSION XS_VERSION_MACRO XS_DEFINE_VERSION INST_ARCHLIB INST_SCRIPT INST_BIN INST_LIB INST_MAN1DIR INST_MAN3DIR MAN1EXT MAN3EXT MAN1SECTION MAN3SECTION INSTALLDIRS INSTALL_BASE DESTDIR PREFIX PERLPREFIX SITEPREFIX VENDORPREFIX ), (map { ("INSTALL".$_, "DESTINSTALL".$_) } $self->installvars), qw( PERL_LIB PERL_ARCHLIB PERL_ARCHLIBDEP LIBPERL_A MYEXTLIB FIRST_MAKEFILE MAKEFILE_OLD MAKE_APERL_FILE PERLMAINCC PERL_SRC PERL_INC PERL_INCDEP PERL FULLPERL ABSPERL PERLRUN FULLPERLRUN ABSPERLRUN PERLRUNINST FULLPERLRUNINST ABSPERLRUNINST PERL_CORE PERM_DIR PERM_RW PERM_RWX ) ) { next unless defined $self->{$macro}; # pathnames can have sharp signs in them; escape them so # make doesn't think it is a comment-start character. $self->{$macro} =~ s/#/\\#/g; $self->{$macro} = $self->quote_dep($self->{$macro}) if $ExtUtils::MakeMaker::macro_dep{$macro}; push @m, "$macro = $self->{$macro}\n"; } push @m, qq{ MAKEMAKER = $self->{MAKEMAKER} MM_VERSION = $self->{MM_VERSION} MM_REVISION = $self->{MM_REVISION} }; push @m, q{ # FULLEXT = Pathname for extension directory (eg Foo/Bar/Oracle). # BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT. (eg Oracle) # PARENT_NAME = NAME without BASEEXT and no trailing :: (eg Foo::Bar) # DLBASE = Basename part of dynamic library. May be just equal BASEEXT. }; for my $macro (qw/ MAKE FULLEXT BASEEXT PARENT_NAME DLBASE VERSION_FROM INC DEFINE OBJECT LDFROM LINKTYPE BOOTDEP / ) { next unless defined $self->{$macro}; push @m, "$macro = $self->{$macro}\n"; } push @m, " # Handy lists of source code files: XS_FILES = ".$self->wraplist(sort keys %{$self->{XS}})." C_FILES = ".$self->wraplist(sort @{$self->{C}})." O_FILES = ".$self->wraplist(sort @{$self->{O_FILES}})." H_FILES = ".$self->wraplist(sort @{$self->{H}})." MAN1PODS = ".$self->wraplist(sort keys %{$self->{MAN1PODS}})." MAN3PODS = ".$self->wraplist(sort keys %{$self->{MAN3PODS}})." "; push @m, q{ SDKROOT := $(shell xcrun --show-sdk-path) PERL_SYSROOT = $(SDKROOT) } if $Is{ApplCor} && $self->{'PERL_INC'} =~ m!^/System/Library/Perl/!; push @m, q{ # Where is the Config information that we are using/depend on CONFIGDEP = $(PERL_ARCHLIBDEP)$(DFSEP)Config.pm $(PERL_SYSROOT)$(PERL_INCDEP)$(DFSEP)config.h } if $Is{ApplCor}; push @m, q{ # Where is the Config information that we are using/depend on CONFIGDEP = $(PERL_ARCHLIBDEP)$(DFSEP)Config.pm $(PERL_INCDEP)$(DFSEP)config.h } if -e $self->catfile( $self->{PERL_INC}, 'config.h' ) && !$Is{ApplCor}; push @m, qq{ # Where to build things INST_LIBDIR = $self->{INST_LIBDIR} INST_ARCHLIBDIR = $self->{INST_ARCHLIBDIR} INST_AUTODIR = $self->{INST_AUTODIR} INST_ARCHAUTODIR = $self->{INST_ARCHAUTODIR} INST_STATIC = $self->{INST_STATIC} INST_DYNAMIC = $self->{INST_DYNAMIC} INST_BOOT = $self->{INST_BOOT} }; push @m, qq{ # Extra linker info EXPORT_LIST = $self->{EXPORT_LIST} PERL_ARCHIVE = $self->{PERL_ARCHIVE} PERL_ARCHIVEDEP = $self->{PERL_ARCHIVEDEP} PERL_ARCHIVE_AFTER = $self->{PERL_ARCHIVE_AFTER} }; push @m, " TO_INST_PM = ".$self->wraplist(map $self->quote_dep($_), sort keys %{$self->{PM}})."\n"; join('',@m); } =item depend (o) Same as macro for the depend attribute. =cut sub depend { my($self,%attribs) = @_; my(@m,$key,$val); for my $key (sort keys %attribs){ my $val = $attribs{$key}; next unless defined $key and defined $val; push @m, "$key : $val\n"; } join "", @m; } =item init_DEST $mm->init_DEST Defines the DESTDIR and DEST* variables paralleling the INSTALL*. =cut sub init_DEST { my $self = shift; # Initialize DESTDIR $self->{DESTDIR} ||= ''; # Make DEST variables. foreach my $var ($self->installvars) { my $destvar = 'DESTINSTALL'.$var; $self->{$destvar} ||= '$(DESTDIR)$(INSTALL'.$var.')'; } } =item init_dist $mm->init_dist; Defines a lot of macros for distribution support. macro description default TAR tar command to use tar TARFLAGS flags to pass to TAR cvf ZIP zip command to use zip ZIPFLAGS flags to pass to ZIP -r COMPRESS compression command to gzip --best use for tarfiles SUFFIX suffix to put on .gz compressed files SHAR shar command to use shar PREOP extra commands to run before making the archive POSTOP extra commands to run after making the archive TO_UNIX a command to convert linefeeds to Unix style in your archive CI command to checkin your ci -u sources to version control RCS_LABEL command to label your sources rcs -Nv$(VERSION_SYM): -q just after CI is run DIST_CP $how argument to manicopy() best when the distdir is created DIST_DEFAULT default target to use to tardist create a distribution DISTVNAME name of the resulting archive $(DISTNAME)-$(VERSION) (minus suffixes) =cut sub init_dist { my $self = shift; $self->{TAR} ||= 'tar'; $self->{TARFLAGS} ||= 'cvf'; $self->{ZIP} ||= 'zip'; $self->{ZIPFLAGS} ||= '-r'; $self->{COMPRESS} ||= 'gzip --best'; $self->{SUFFIX} ||= '.gz'; $self->{SHAR} ||= 'shar'; $self->{PREOP} ||= '$(NOECHO) $(NOOP)'; # eg update MANIFEST $self->{POSTOP} ||= '$(NOECHO) $(NOOP)'; # eg remove the distdir $self->{TO_UNIX} ||= '$(NOECHO) $(NOOP)'; $self->{CI} ||= 'ci -u'; $self->{RCS_LABEL}||= 'rcs -Nv$(VERSION_SYM): -q'; $self->{DIST_CP} ||= 'best'; $self->{DIST_DEFAULT} ||= 'tardist'; ($self->{DISTNAME} = $self->{NAME}) =~ s{::}{-}g unless $self->{DISTNAME}; $self->{DISTVNAME} ||= $self->{DISTNAME}.'-'.$self->{VERSION}; } =item dist (o) my $dist_macros = $mm->dist(%overrides); Generates a make fragment defining all the macros initialized in init_dist. %overrides can be used to override any of the above. =cut sub dist { my($self, %attribs) = @_; my $make = ''; if ( $attribs{SUFFIX} && $attribs{SUFFIX} !~ m!^\.! ) { $attribs{SUFFIX} = '.' . $attribs{SUFFIX}; } foreach my $key (qw( TAR TARFLAGS ZIP ZIPFLAGS COMPRESS SUFFIX SHAR PREOP POSTOP TO_UNIX CI RCS_LABEL DIST_CP DIST_DEFAULT DISTNAME DISTVNAME )) { my $value = $attribs{$key} || $self->{$key}; $make .= "$key = $value\n"; } return $make; } =item dist_basics (o) Defines the targets distclean, distcheck, skipcheck, manifest, veryclean. =cut sub dist_basics { my($self) = shift; return <<'MAKE_FRAG'; distclean :: realclean distcheck $(NOECHO) $(NOOP) distcheck : $(PERLRUN) "-MExtUtils::Manifest=fullcheck" -e fullcheck skipcheck : $(PERLRUN) "-MExtUtils::Manifest=skipcheck" -e skipcheck manifest : $(PERLRUN) "-MExtUtils::Manifest=mkmanifest" -e mkmanifest veryclean : realclean $(RM_F) *~ */*~ *.orig */*.orig *.bak */*.bak *.old */*.old MAKE_FRAG } =item dist_ci (o) Defines a check in target for RCS. =cut sub dist_ci { my($self) = shift; return sprintf "ci :\n\t%s\n", $self->oneliner(<<'EOF', [qw(-MExtUtils::Manifest=maniread)]); @all = sort keys %{ maniread() }; print(qq{Executing $(CI) @all\n}); system(qq{$(CI) @all}) == 0 or die $!; print(qq{Executing $(RCS_LABEL) ...\n}); system(qq{$(RCS_LABEL) @all}) == 0 or die $!; EOF } =item dist_core (o) my $dist_make_fragment = $MM->dist_core; Puts the targets necessary for 'make dist' together into one make fragment. =cut sub dist_core { my($self) = shift; my $make_frag = ''; foreach my $target (qw(dist tardist uutardist tarfile zipdist zipfile shdist)) { my $method = $target.'_target'; $make_frag .= "\n"; $make_frag .= $self->$method(); } return $make_frag; } =item B my $make_frag = $MM->dist_target; Returns the 'dist' target to make an archive for distribution. This target simply checks to make sure the Makefile is up-to-date and depends on $(DIST_DEFAULT). =cut sub dist_target { my($self) = shift; my $date_check = $self->oneliner(<<'CODE', ['-l']); print 'Warning: Makefile possibly out of date with $(VERSION_FROM)' if -e '$(VERSION_FROM)' and -M '$(VERSION_FROM)' < -M '$(FIRST_MAKEFILE)'; CODE return sprintf <<'MAKE_FRAG', $date_check; dist : $(DIST_DEFAULT) $(FIRST_MAKEFILE) $(NOECHO) %s MAKE_FRAG } =item B my $make_frag = $MM->tardist_target; Returns the 'tardist' target which is simply so 'make tardist' works. The real work is done by the dynamically named tardistfile_target() method, tardist should have that as a dependency. =cut sub tardist_target { my($self) = shift; return <<'MAKE_FRAG'; tardist : $(DISTVNAME).tar$(SUFFIX) $(NOECHO) $(NOOP) MAKE_FRAG } =item B my $make_frag = $MM->zipdist_target; Returns the 'zipdist' target which is simply so 'make zipdist' works. The real work is done by the dynamically named zipdistfile_target() method, zipdist should have that as a dependency. =cut sub zipdist_target { my($self) = shift; return <<'MAKE_FRAG'; zipdist : $(DISTVNAME).zip $(NOECHO) $(NOOP) MAKE_FRAG } =item B my $make_frag = $MM->tarfile_target; The name of this target is the name of the tarball generated by tardist. This target does the actual work of turning the distdir into a tarball. =cut sub tarfile_target { my($self) = shift; return <<'MAKE_FRAG'; $(DISTVNAME).tar$(SUFFIX) : distdir $(PREOP) $(TO_UNIX) $(TAR) $(TARFLAGS) $(DISTVNAME).tar $(DISTVNAME) $(RM_RF) $(DISTVNAME) $(COMPRESS) $(DISTVNAME).tar $(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)' $(POSTOP) MAKE_FRAG } =item zipfile_target my $make_frag = $MM->zipfile_target; The name of this target is the name of the zip file generated by zipdist. This target does the actual work of turning the distdir into a zip file. =cut sub zipfile_target { my($self) = shift; return <<'MAKE_FRAG'; $(DISTVNAME).zip : distdir $(PREOP) $(ZIP) $(ZIPFLAGS) $(DISTVNAME).zip $(DISTVNAME) $(RM_RF) $(DISTVNAME) $(NOECHO) $(ECHO) 'Created $(DISTVNAME).zip' $(POSTOP) MAKE_FRAG } =item uutardist_target my $make_frag = $MM->uutardist_target; Converts the tarfile into a uuencoded file =cut sub uutardist_target { my($self) = shift; return <<'MAKE_FRAG'; uutardist : $(DISTVNAME).tar$(SUFFIX) uuencode $(DISTVNAME).tar$(SUFFIX) $(DISTVNAME).tar$(SUFFIX) > $(DISTVNAME).tar$(SUFFIX)_uu $(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)_uu' MAKE_FRAG } =item shdist_target my $make_frag = $MM->shdist_target; Converts the distdir into a shell archive. =cut sub shdist_target { my($self) = shift; return <<'MAKE_FRAG'; shdist : distdir $(PREOP) $(SHAR) $(DISTVNAME) > $(DISTVNAME).shar $(RM_RF) $(DISTVNAME) $(NOECHO) $(ECHO) 'Created $(DISTVNAME).shar' $(POSTOP) MAKE_FRAG } =item dlsyms (o) Used by some OS' to define DL_FUNCS and DL_VARS and write the *.exp files. Normally just returns an empty string. =cut sub dlsyms { return ''; } =item dynamic_bs (o) Defines targets for bootstrap files. =cut sub dynamic_bs { my($self, %attribs) = @_; return "\nBOOTSTRAP =\n" unless $self->has_link_code(); my @exts; if ($self->{XSMULTI}) { @exts = $self->_xs_list_basenames; } else { @exts = '$(BASEEXT)'; } return join "\n", "BOOTSTRAP = @{[map { qq{$_.bs} } @exts]}\n", map { $self->_xs_make_bs($_) } @exts; } sub _xs_make_bs { my ($self, $basename) = @_; my ($v, $d, $f) = File::Spec->splitpath($basename); my @d = File::Spec->splitdir($d); shift @d if $self->{XSMULTI} and $d[0] eq 'lib'; my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f); $instdir = '$(INST_ARCHAUTODIR)' if $basename eq '$(BASEEXT)'; my $instfile = $self->catfile($instdir, "$f.bs"); my $exists = "$instdir\$(DFSEP).exists"; # match blibdirs_target # 1 2 3 return _sprintf562 <<'MAKE_FRAG', $basename, $instfile, $exists; # As Mkbootstrap might not write a file (if none is required) # we use touch to prevent make continually trying to remake it. # The DynaLoader only reads a non-empty file. %1$s.bs : $(FIRST_MAKEFILE) $(BOOTDEP) $(NOECHO) $(ECHO) "Running Mkbootstrap for %1$s ($(BSLOADLIBS))" $(NOECHO) $(PERLRUN) \ "-MExtUtils::Mkbootstrap" \ -e "Mkbootstrap('%1$s','$(BSLOADLIBS)');" $(NOECHO) $(TOUCH) "%1$s.bs" $(CHMOD) $(PERM_RW) "%1$s.bs" %2$s : %1$s.bs %3$s $(NOECHO) $(RM_RF) %2$s - $(CP_NONEMPTY) %1$s.bs %2$s $(PERM_RW) MAKE_FRAG } =item dynamic_lib (o) Defines how to produce the *.so (or equivalent) files. =cut sub dynamic_lib { my($self, %attribs) = @_; return '' unless $self->needs_linking(); #might be because of a subdir return '' unless $self->has_link_code; my @m = $self->xs_dynamic_lib_macros(\%attribs); my @libs; my $dlsyms_ext = eval { $self->xs_dlsyms_ext }; if ($self->{XSMULTI}) { my @exts = $self->_xs_list_basenames; for my $ext (@exts) { my ($v, $d, $f) = File::Spec->splitpath($ext); my @d = File::Spec->splitdir($d); shift @d if $d[0] eq 'lib'; pop @d if $d[$#d] eq ''; my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f); # Dynamic library names may need special handling. eval { require DynaLoader }; if (defined &DynaLoader::mod2fname) { $f = &DynaLoader::mod2fname([@d, $f]); } my $instfile = $self->catfile($instdir, "$f.\$(DLEXT)"); my $objfile = $self->_xsbuild_value('xs', $ext, 'OBJECT'); $objfile = "$ext\$(OBJ_EXT)" unless defined $objfile; my $ldfrom = $self->_xsbuild_value('xs', $ext, 'LDFROM'); $ldfrom = $objfile unless defined $ldfrom; my $exportlist = "$ext.def"; my @libchunk = ($objfile, $instfile, $instdir, $ldfrom, $exportlist); push @libchunk, $dlsyms_ext ? $ext.$dlsyms_ext : undef; push @libs, \@libchunk; } } else { my @libchunk = qw($(OBJECT) $(INST_DYNAMIC) $(INST_ARCHAUTODIR) $(LDFROM) $(EXPORT_LIST)); push @libchunk, $dlsyms_ext ? '$(BASEEXT)'.$dlsyms_ext : undef; @libs = (\@libchunk); } push @m, map { $self->xs_make_dynamic_lib(\%attribs, @$_); } @libs; return join("\n",@m); } =item xs_dynamic_lib_macros Defines the macros for the C section. =cut sub xs_dynamic_lib_macros { my ($self, $attribs) = @_; my $otherldflags = $attribs->{OTHERLDFLAGS} || ""; my $inst_dynamic_dep = $attribs->{INST_DYNAMIC_DEP} || ""; my $armaybe = $self->_xs_armaybe($attribs); my $ld_opt = $Is{OS2} ? '$(OPTIMIZE) ' : ''; # Useful on other systems too? my $ld_fix = $Is{OS2} ? '|| ( $(RM_F) $@ && sh -c false )' : ''; sprintf <<'EOF', $armaybe, $ld_opt.$otherldflags, $inst_dynamic_dep, $ld_fix; # This section creates the dynamically loadable objects from relevant # objects and possibly $(MYEXTLIB). ARMAYBE = %s OTHERLDFLAGS = %s INST_DYNAMIC_DEP = %s INST_DYNAMIC_FIX = %s EOF } sub _xs_armaybe { my ($self, $attribs) = @_; my $armaybe = $attribs->{ARMAYBE} || $self->{ARMAYBE} || ":"; $armaybe = 'ar' if ($Is{OSF} and $armaybe eq ':'); $armaybe; } =item xs_make_dynamic_lib Defines the recipes for the C section. =cut sub xs_make_dynamic_lib { my ($self, $attribs, $object, $to, $todir, $ldfrom, $exportlist, $dlsyms) = @_; $exportlist = '' if $exportlist ne '$(EXPORT_LIST)'; my $armaybe = $self->_xs_armaybe($attribs); my @m = sprintf '%s : %s $(MYEXTLIB) %s$(DFSEP).exists %s $(PERL_ARCHIVEDEP) $(PERL_ARCHIVE_AFTER) $(INST_DYNAMIC_DEP) %s'."\n", $to, $object, $todir, $exportlist, ($dlsyms || ''); my $dlsyms_arg = $self->xs_dlsyms_arg($dlsyms); if ($armaybe ne ':'){ $ldfrom = 'tmp$(LIB_EXT)'; push(@m," \$(ARMAYBE) cr $ldfrom $object\n"); push(@m," \$(RANLIB) $ldfrom\n"); } $ldfrom = "-all $ldfrom -none" if $Is{OSF}; # The IRIX linker doesn't use LD_RUN_PATH my $ldrun = $Is{IRIX} && $self->{LD_RUN_PATH} ? qq{-rpath "$self->{LD_RUN_PATH}"} : ''; # For example in AIX the shared objects/libraries from previous builds # linger quite a while in the shared dynalinker cache even when nobody # is using them. This is painful if one for instance tries to restart # a failed build because the link command will fail unnecessarily 'cos # the shared object/library is 'busy'. push(@m," \$(RM_F) \$\@\n"); my $libs = '$(LDLOADLIBS)'; if (($Is{NetBSD} || $Is{Interix} || $Is{Android}) && $Config{'useshrplib'} eq 'true') { # Use nothing on static perl platforms, and to the flags needed # to link against the shared libperl library on shared perl # platforms. We peek at lddlflags to see if we need -Wl,-R # or -R to add paths to the run-time library search path. if ($Config{'lddlflags'} =~ /-Wl,-R/) { $libs .= ' "-L$(PERL_INC)" "-Wl,-R$(INSTALLARCHLIB)/CORE" "-Wl,-R$(PERL_ARCHLIB)/CORE" -lperl'; } elsif ($Config{'lddlflags'} =~ /-R/) { $libs .= ' "-L$(PERL_INC)" "-R$(INSTALLARCHLIB)/CORE" "-R$(PERL_ARCHLIB)/CORE" -lperl'; } elsif ( $Is{Android} ) { # The Android linker will not recognize symbols from # libperl unless the module explicitly depends on it. $libs .= ' "-L$(PERL_INC)" -lperl'; } } my $ld_run_path_shell = ""; if ($self->{LD_RUN_PATH} ne "") { $ld_run_path_shell = 'LD_RUN_PATH="$(LD_RUN_PATH)" '; } push @m, sprintf <<'MAKE', $ld_run_path_shell, $ldrun, $dlsyms_arg, $ldfrom, $self->xs_obj_opt('$@'), $libs, $exportlist; %s$(LD) %s $(LDDLFLAGS) %s %s $(OTHERLDFLAGS) %s $(MYEXTLIB) \ $(PERL_ARCHIVE) %s $(PERL_ARCHIVE_AFTER) %s \ $(INST_DYNAMIC_FIX) $(CHMOD) $(PERM_RWX) $@ MAKE join '', @m; } =item exescan Deprecated method. Use libscan instead. =cut sub exescan { my($self,$path) = @_; $path; } =item extliblist Called by init_others, and calls ext ExtUtils::Liblist. See L for details. =cut sub extliblist { my($self,$libs) = @_; require ExtUtils::Liblist; $self->ext($libs, $Verbose); } =item find_perl Finds the executables PERL and FULLPERL =cut sub find_perl { my($self, $ver, $names, $dirs, $trace) = @_; if ($trace >= 2){ print "Looking for perl $ver by these names: @$names in these dirs: @$dirs "; } my $stderr_duped = 0; local *STDERR_COPY; unless ($Is{BSD}) { # >& and lexical filehandles together give 5.6.2 indigestion if( open(STDERR_COPY, '>&STDERR') ) { ## no critic $stderr_duped = 1; } else { warn <file_name_is_absolute($name)) { # /foo/bar $abs = $name; } elsif ($self->canonpath($name) eq $self->canonpath(basename($name))) { # foo $use_dir = 1; } else { # foo/bar $abs = $self->catfile($Curdir, $name); } foreach my $dir ($use_dir ? @$dirs : 1){ next unless defined $dir; # $self->{PERL_SRC} may be undefined $abs = $self->catfile($dir, $name) if $use_dir; print "Checking $abs\n" if ($trace >= 2); next unless $self->maybe_command($abs); print "Executing $abs\n" if ($trace >= 2); my $val; my $version_check = qq{"$abs" -le "require $ver; print qq{VER_OK}"}; # To avoid using the unportable 2>&1 to suppress STDERR, # we close it before running the command. # However, thanks to a thread library bug in many BSDs # ( http://www.freebsd.org/cgi/query-pr.cgi?pr=51535 ) # we cannot use the fancier more portable way in here # but instead need to use the traditional 2>&1 construct. if ($Is{BSD}) { $val = `$version_check 2>&1`; } else { close STDERR if $stderr_duped; $val = `$version_check`; # 5.6.2's 3-arg open doesn't work with >& open STDERR, ">&STDERR_COPY" ## no critic if $stderr_duped; } if ($val =~ /^VER_OK/m) { print "Using PERL=$abs\n" if $trace; return $abs; } elsif ($trace >= 2) { print "Result: '$val' ".($? >> 8)."\n"; } } } print "Unable to find a perl $ver (by these names: @$names, in these dirs: @$dirs)\n"; 0; # false and not empty } =item fixin $mm->fixin(@files); Inserts the sharpbang or equivalent magic number to a set of @files. =cut sub fixin { # stolen from the pink Camel book, more or less my ( $self, @files ) = @_; for my $file (@files) { my $file_new = "$file.new"; my $file_bak = "$file.bak"; open( my $fixin, '<', $file ) or croak "Can't process '$file': $!"; local $/ = "\n"; chomp( my $line = <$fixin> ); next unless $line =~ s/^\s*\#!\s*//; # Not a shebang file. my $shb = $self->_fixin_replace_shebang( $file, $line ); next unless defined $shb; open( my $fixout, ">", "$file_new" ) or do { warn "Can't create new $file: $!\n"; next; }; # Print out the new #! line (or equivalent). local $\; local $/; print $fixout $shb, <$fixin>; close $fixin; close $fixout; chmod 0666, $file_bak; unlink $file_bak; unless ( _rename( $file, $file_bak ) ) { warn "Can't rename $file to $file_bak: $!"; next; } unless ( _rename( $file_new, $file ) ) { warn "Can't rename $file_new to $file: $!"; unless ( _rename( $file_bak, $file ) ) { warn "Can't rename $file_bak back to $file either: $!"; warn "Leaving $file renamed as $file_bak\n"; } next; } unlink $file_bak; } continue { system("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':'; } } sub _rename { my($old, $new) = @_; foreach my $file ($old, $new) { if( $Is{VMS} and basename($file) !~ /\./ ) { # rename() in 5.8.0 on VMS will not rename a file if it # does not contain a dot yet it returns success. $file = "$file."; } } return rename($old, $new); } sub _fixin_replace_shebang { my ( $self, $file, $line ) = @_; # Now figure out the interpreter name. my ( $origcmd, $arg ) = split ' ', $line, 2; (my $cmd = $origcmd) =~ s!^.*/!!; # Now look (in reverse) for interpreter in absolute PATH (unless perl). my $interpreter; if ( defined $ENV{PERL_MM_SHEBANG} && $ENV{PERL_MM_SHEBANG} eq "relocatable" ) { $interpreter = "/usr/bin/env perl"; } elsif ( $cmd =~ m{^perl(?:\z|[^a-z])} ) { if ( $Config{startperl} =~ m,^\#!.*/perl, ) { $interpreter = $Config{startperl}; $interpreter =~ s,^\#!,,; } else { $interpreter = $Config{perlpath}; } } else { my (@absdirs) = reverse grep { $self->file_name_is_absolute($_) } $self->path; $interpreter = ''; foreach my $dir (@absdirs) { my $maybefile = $self->catfile($dir,$cmd); if ( $self->maybe_command($maybefile) ) { warn "Ignoring $interpreter in $file\n" if $Verbose && $interpreter; $interpreter = $maybefile; } } # If the shebang is absolute and exists in PATH, but was not # the first one found, leave it alone if it's actually the # same file as first one. This avoids packages built on # merged-/usr systems with /usr/bin before /bin in the path # breaking when installed on systems without merged /usr if ($origcmd ne $interpreter and $self->file_name_is_absolute($origcmd)) { my $origdir = dirname($origcmd); if ($self->maybe_command($origcmd) && grep { $_ eq $origdir } @absdirs) { my ($odev, $oino) = stat $origcmd; my ($idev, $iino) = stat $interpreter; if ($odev == $idev && $oino == $iino) { warn "$origcmd is the same as $interpreter, leaving alone" if $Verbose; $interpreter = $origcmd; } } } } # Figure out how to invoke interpreter on this machine. my ($does_shbang) = $Config{'sharpbang'} =~ /^\s*\#\!/; my ($shb) = ""; if ($interpreter) { print "Changing sharpbang in $file to $interpreter" if $Verbose; # this is probably value-free on DOSISH platforms if ($does_shbang) { $shb .= "$Config{'sharpbang'}$interpreter"; $shb .= ' ' . $arg if defined $arg; $shb .= "\n"; } } else { warn "Can't find $cmd in PATH, $file unchanged" if $Verbose; return; } return $shb } =item force (o) Writes an empty FORCE: target. =cut sub force { my($self) = shift; '# Phony target to force checking subdirectories. FORCE : $(NOECHO) $(NOOP) '; } =item guess_name Guess the name of this package by examining the working directory's name. MakeMaker calls this only if the developer has not supplied a NAME attribute. =cut # '; sub guess_name { my($self) = @_; use Cwd 'cwd'; my $name = basename(cwd()); $name =~ s|[\-_][\d\.\-]+\z||; # this is new with MM 5.00, we # strip minus or underline # followed by a float or some such print "Warning: Guessing NAME [$name] from current directory name.\n"; $name; } =item has_link_code Returns true if C, XS, MYEXTLIB or similar objects exist within this object that need a compiler. Does not descend into subdirectories as needs_linking() does. =cut sub has_link_code { my($self) = shift; return $self->{HAS_LINK_CODE} if defined $self->{HAS_LINK_CODE}; if ($self->{OBJECT} or @{$self->{C} || []} or $self->{MYEXTLIB}){ $self->{HAS_LINK_CODE} = 1; return 1; } return $self->{HAS_LINK_CODE} = 0; } =item init_dirscan Scans the directory structure and initializes DIR, XS, XS_FILES, C, C_FILES, O_FILES, H, H_FILES, PL_FILES, EXE_FILES. Called by init_main. =cut sub init_dirscan { # --- File and Directory Lists (.xs .pm .pod etc) my($self) = @_; my(%dir, %xs, %c, %o, %h, %pl_files, %pm); my %ignore = map {( $_ => 1 )} qw(Makefile.PL Build.PL test.pl t); # ignore the distdir $Is{VMS} ? $ignore{"$self->{DISTVNAME}.dir"} = 1 : $ignore{$self->{DISTVNAME}} = 1; my $distprefix = $Is{VMS} ? qr/^\Q$self->{DISTNAME}\E-v?[\d\.]+\.dir$/i : qr/^\Q$self->{DISTNAME}\E-v?[\d\.]+$/; @ignore{map lc, keys %ignore} = values %ignore if $Is{VMS}; if ( defined $self->{XS} and !defined $self->{C} ) { my @c_files = grep { m/\.c(pp|xx)?\z/i } values %{$self->{XS}}; my @o_files = grep { m/(?:.(?:o(?:bj)?)|\$\(OBJ_EXT\))\z/i } values %{$self->{XS}}; %c = map { $_ => 1 } @c_files; %o = map { $_ => 1 } @o_files; } foreach my $name ($self->lsdir($Curdir)){ next if $name =~ /\#/; next if $name =~ $distprefix && -d $name; $name = lc($name) if $Is{VMS}; next if $name eq $Curdir or $name eq $Updir or $ignore{$name}; next unless $self->libscan($name); if (-d $name){ next if -l $name; # We do not support symlinks at all next if $self->{NORECURS}; $dir{$name} = $name if (-f $self->catfile($name,"Makefile.PL")); } elsif ($name =~ /\.xs\z/){ my($c); ($c = $name) =~ s/\.xs\z/.c/; $xs{$name} = $c; $c{$c} = 1; } elsif ($name =~ /\.c(pp|xx|c)?\z/i){ # .c .C .cpp .cxx .cc $c{$name} = 1 unless $name =~ m/perlmain\.c/; # See MAP_TARGET } elsif ($name =~ /\.h\z/i){ $h{$name} = 1; } elsif ($name =~ /\.PL\z/) { ($pl_files{$name} = $name) =~ s/\.PL\z// ; } elsif (($Is{VMS} || $Is{Dos}) && $name =~ /[._]pl$/i) { # case-insensitive filesystem, one dot per name, so foo.h.PL # under Unix appears as foo.h_pl under VMS or fooh.pl on Dos local($/); open(my $pl, '<', $name); my $txt = <$pl>; close $pl; if ($txt =~ /Extracting \S+ \(with variable substitutions/) { ($pl_files{$name} = $name) =~ s/[._]pl\z//i ; } else { $pm{$name} = $self->catfile($self->{INST_LIBDIR},$name); } } elsif ($name =~ /\.(p[ml]|pod)\z/){ $pm{$name} = $self->catfile($self->{INST_LIBDIR},$name); } } $self->{PL_FILES} ||= \%pl_files; $self->{DIR} ||= [sort keys %dir]; $self->{XS} ||= \%xs; $self->{C} ||= [sort keys %c]; $self->{H} ||= [sort keys %h]; $self->{PM} ||= \%pm; my @o_files = @{$self->{C}}; %o = (%o, map { $_ => 1 } grep s/\.c(pp|xx|c)?\z/$self->{OBJ_EXT}/i, @o_files); $self->{O_FILES} = [sort keys %o]; } =item init_MANPODS Determines if man pages should be generated and initializes MAN1PODS and MAN3PODS as appropriate. =cut sub init_MANPODS { my $self = shift; # Set up names of manual pages to generate from pods foreach my $man (qw(MAN1 MAN3)) { if ( $self->{"${man}PODS"} or $self->{"INSTALL${man}DIR"} =~ /^(none|\s*)$/ ) { $self->{"${man}PODS"} ||= {}; } else { my $init_method = "init_${man}PODS"; $self->$init_method(); } } # logic similar to picking man${num}ext in perl's Configure script foreach my $num (1,3) { my $installdirs = uc $self->{INSTALLDIRS}; $installdirs = '' if $installdirs eq 'PERL'; my @mandirs = File::Spec->splitdir( $self->_expand_macros( $self->{ "INSTALL${installdirs}MAN${num}DIR" } ) ); my $mandir = pop @mandirs; my $section = $num; foreach ($num, "${num}p", "${num}pm", qw< l n o C L >, "L$num") { if ( $mandir =~ /^(?:man|cat)$_$/ ) { $section = $_; last; } } $self->{"MAN${num}SECTION"} = $section; } } sub _has_pod { my($self, $file) = @_; my($ispod)=0; if (open( my $fh, '<', $file )) { while (<$fh>) { if (/^=(?:head\d+|item|pod)\b/) { $ispod=1; last; } } close $fh; } else { # If it doesn't exist yet, we assume, it has pods in it $ispod = 1; } return $ispod; } =item init_MAN1PODS Initializes MAN1PODS from the list of EXE_FILES. =cut sub init_MAN1PODS { my($self) = @_; if ( exists $self->{EXE_FILES} ) { foreach my $name (@{$self->{EXE_FILES}}) { next unless $self->_has_pod($name); $self->{MAN1PODS}->{$name} = $self->catfile("\$(INST_MAN1DIR)", basename($name).".\$(MAN1EXT)"); } } } =item init_MAN3PODS Initializes MAN3PODS from the list of PM files. =cut sub init_MAN3PODS { my $self = shift; my %manifypods = (); # we collect the keys first, i.e. the files # we have to convert to pod foreach my $name (keys %{$self->{PM}}) { if ($name =~ /\.pod\z/ ) { $manifypods{$name} = $self->{PM}{$name}; } elsif ($name =~ /\.p[ml]\z/ ) { if( $self->_has_pod($name) ) { $manifypods{$name} = $self->{PM}{$name}; } } } my $parentlibs_re = join '|', @{$self->{PMLIBPARENTDIRS}}; # Remove "Configure.pm" and similar, if it's not the only pod listed # To force inclusion, just name it "Configure.pod", or override # MAN3PODS foreach my $name (keys %manifypods) { if ( ($self->{PERL_CORE} and $name =~ /(config|setup).*\.pm/is) or ( $name =~ m/^README\.pod$/i ) # don't manify top-level README.pod ) { delete $manifypods{$name}; next; } my($manpagename) = $name; $manpagename =~ s/\.p(od|m|l)\z//; # everything below lib is ok unless($manpagename =~ s!^\W*($parentlibs_re)\W+!!s) { $manpagename = $self->catfile( split(/::/,$self->{PARENT_NAME}),$manpagename ); } $manpagename = $self->replace_manpage_separator($manpagename); $self->{MAN3PODS}->{$name} = $self->catfile("\$(INST_MAN3DIR)", "$manpagename.\$(MAN3EXT)"); } } =item init_PM Initializes PMLIBDIRS and PM from PMLIBDIRS. =cut sub init_PM { my $self = shift; # Some larger extensions often wish to install a number of *.pm/pl # files into the library in various locations. # The attribute PMLIBDIRS holds an array reference which lists # subdirectories which we should search for library files to # install. PMLIBDIRS defaults to [ 'lib', $self->{BASEEXT} ]. We # recursively search through the named directories (skipping any # which don't exist or contain Makefile.PL files). # For each *.pm or *.pl file found $self->libscan() is called with # the default installation path in $_[1]. The return value of # libscan defines the actual installation location. The default # libscan function simply returns the path. The file is skipped # if libscan returns false. # The default installation location passed to libscan in $_[1] is: # # ./*.pm => $(INST_LIBDIR)/*.pm # ./xyz/... => $(INST_LIBDIR)/xyz/... # ./lib/... => $(INST_LIB)/... # # In this way the 'lib' directory is seen as the root of the actual # perl library whereas the others are relative to INST_LIBDIR # (which includes PARENT_NAME). This is a subtle distinction but one # that's important for nested modules. unless( $self->{PMLIBDIRS} ) { if( $Is{VMS} ) { # Avoid logical name vs directory collisions $self->{PMLIBDIRS} = ['./lib', "./$self->{BASEEXT}"]; } else { $self->{PMLIBDIRS} = ['lib', $self->{BASEEXT}]; } } #only existing directories that aren't in $dir are allowed # Avoid $_ wherever possible: # @{$self->{PMLIBDIRS}} = grep -d && !$dir{$_}, @{$self->{PMLIBDIRS}}; my (@pmlibdirs) = @{$self->{PMLIBDIRS}}; @{$self->{PMLIBDIRS}} = (); my %dir = map { ($_ => $_) } @{$self->{DIR}}; foreach my $pmlibdir (@pmlibdirs) { -d $pmlibdir && !$dir{$pmlibdir} && push @{$self->{PMLIBDIRS}}, $pmlibdir; } unless( $self->{PMLIBPARENTDIRS} ) { @{$self->{PMLIBPARENTDIRS}} = ('lib'); } return if $self->{PM} and $self->{ARGS}{PM}; if (@{$self->{PMLIBDIRS}}){ print "Searching PMLIBDIRS: @{$self->{PMLIBDIRS}}\n" if ($Verbose >= 2); require File::Find; File::Find::find(sub { if (-d $_){ unless ($self->libscan($_)){ $File::Find::prune = 1; } return; } return if /\#/; return if /~$/; # emacs temp files return if /,v$/; # RCS files return if m{\.swp$}; # vim swap files my $path = $File::Find::name; my $prefix = $self->{INST_LIBDIR}; my $striplibpath; my $parentlibs_re = join '|', @{$self->{PMLIBPARENTDIRS}}; $prefix = $self->{INST_LIB} if ($striplibpath = $path) =~ s{^(\W*)($parentlibs_re)\W} {$1}i; my($inst) = $self->catfile($prefix,$striplibpath); local($_) = $inst; # for backwards compatibility $inst = $self->libscan($inst); print "libscan($path) => '$inst'\n" if ($Verbose >= 2); return unless $inst; if ($self->{XSMULTI} and $inst =~ /\.xs\z/) { my($base); ($base = $path) =~ s/\.xs\z//; $self->{XS}{$path} = "$base.c"; push @{$self->{C}}, "$base.c"; push @{$self->{O_FILES}}, "$base$self->{OBJ_EXT}"; } else { $self->{PM}{$path} = $inst; } }, @{$self->{PMLIBDIRS}}); } } =item init_DIRFILESEP Using / for Unix. Called by init_main. =cut sub init_DIRFILESEP { my($self) = shift; $self->{DIRFILESEP} = '/'; } =item init_main Initializes AR, AR_STATIC_ARGS, BASEEXT, CONFIG, DISTNAME, DLBASE, EXE_EXT, FULLEXT, FULLPERL, FULLPERLRUN, FULLPERLRUNINST, INST_*, INSTALL*, INSTALLDIRS, LIB_EXT, LIBPERL_A, MAP_TARGET, NAME, OBJ_EXT, PARENT_NAME, PERL, PERL_ARCHLIB, PERL_INC, PERL_LIB, PERL_SRC, PERLRUN, PERLRUNINST, PREFIX, VERSION, VERSION_SYM, XS_VERSION. =cut sub init_main { my($self) = @_; # --- Initialize Module Name and Paths # NAME = Foo::Bar::Oracle # FULLEXT = Foo/Bar/Oracle # BASEEXT = Oracle # PARENT_NAME = Foo::Bar ### Only UNIX: ### ($self->{FULLEXT} = ### $self->{NAME}) =~ s!::!/!g ; #eg. BSD/Foo/Socket $self->{FULLEXT} = $self->catdir(split /::/, $self->{NAME}); # Copied from DynaLoader: my(@modparts) = split(/::/,$self->{NAME}); my($modfname) = $modparts[-1]; # Some systems have restrictions on files names for DLL's etc. # mod2fname returns appropriate file base name (typically truncated) # It may also edit @modparts if required. # We require DynaLoader to make sure that mod2fname is loaded eval { require DynaLoader }; if (defined &DynaLoader::mod2fname) { $modfname = &DynaLoader::mod2fname(\@modparts); } ($self->{PARENT_NAME}, $self->{BASEEXT}) = $self->{NAME} =~ m!(?:([\w:]+)::)?(\w+)\z! ; $self->{PARENT_NAME} ||= ''; if (defined &DynaLoader::mod2fname) { # As of 5.001m, dl_os2 appends '_' $self->{DLBASE} = $modfname; } else { $self->{DLBASE} = '$(BASEEXT)'; } # --- Initialize PERL_LIB, PERL_SRC # *Real* information: where did we get these two from? ... my $inc_config_dir = dirname($INC{'Config.pm'}); my $inc_carp_dir = dirname($INC{'Carp.pm'}); unless ($self->{PERL_SRC}){ foreach my $dir_count (1..8) { # 8 is the VMS limit for nesting my $dir = $self->catdir(($Updir) x $dir_count); if (-f $self->catfile($dir,"config_h.SH") && -f $self->catfile($dir,"perl.h") && -f $self->catfile($dir,"lib","strict.pm") ) { $self->{PERL_SRC}=$dir ; last; } } } warn "PERL_CORE is set but I can't find your PERL_SRC!\n" if $self->{PERL_CORE} and !$self->{PERL_SRC}; if ($self->{PERL_SRC}){ $self->{PERL_LIB} ||= $self->catdir("$self->{PERL_SRC}","lib"); $self->{PERL_ARCHLIB} = $self->{PERL_LIB}; $self->{PERL_INC} = ($Is{Win32}) ? $self->catdir($self->{PERL_LIB},"CORE") : $self->{PERL_SRC}; # catch a situation that has occurred a few times in the past: unless ( -s $self->catfile($self->{PERL_SRC},'cflags') or $Is{VMS} && -s $self->catfile($self->{PERL_SRC},'vmsish.h') or $Is{Win32} ){ warn qq{ You cannot build extensions below the perl source tree after executing a 'make clean' in the perl source tree. To rebuild extensions distributed with the perl source you should simply Configure (to include those extensions) and then build perl as normal. After installing perl the source tree can be deleted. It is not needed for building extensions by running 'perl Makefile.PL' usually without extra arguments. It is recommended that you unpack and build additional extensions away from the perl source tree. }; } } else { # we should also consider $ENV{PERL5LIB} here my $old = $self->{PERL_LIB} || $self->{PERL_ARCHLIB} || $self->{PERL_INC}; $self->{PERL_LIB} ||= $Config{privlibexp}; $self->{PERL_ARCHLIB} ||= $Config{archlibexp}; $self->{PERL_INC} = $self->catdir("$self->{PERL_ARCHLIB}","CORE"); # wild guess for now my $perl_h; if (not -f ($perl_h = $self->catfile($self->{PERL_INC},"perl.h")) and not $old){ # Maybe somebody tries to build an extension with an # uninstalled Perl outside of Perl build tree my $lib; for my $dir (@INC) { $lib = $dir, last if -e $self->catfile($dir, "Config.pm"); } if ($lib) { # Win32 puts its header files in /perl/src/lib/CORE. # Unix leaves them in /perl/src. my $inc = $Is{Win32} ? $self->catdir($lib, "CORE" ) : dirname $lib; if (-e $self->catfile($inc, "perl.h")) { $self->{PERL_LIB} = $lib; $self->{PERL_ARCHLIB} = $lib; $self->{PERL_INC} = $inc; $self->{UNINSTALLED_PERL} = 1; print <{PERL_LIB} = File::Spec->rel2abs($self->{PERL_LIB}); $self->{PERL_ARCHLIB} = File::Spec->rel2abs($self->{PERL_ARCHLIB}); } $self->{PERL_INCDEP} = $self->{PERL_INC}; $self->{PERL_ARCHLIBDEP} = $self->{PERL_ARCHLIB}; # We get SITELIBEXP and SITEARCHEXP directly via # Get_from_Config. When we are running standard modules, these # won't matter, we will set INSTALLDIRS to "perl". Otherwise we # set it to "site". I prefer that INSTALLDIRS be set from outside # MakeMaker. $self->{INSTALLDIRS} ||= "site"; $self->{MAN1EXT} ||= $Config{man1ext}; $self->{MAN3EXT} ||= $Config{man3ext}; # Get some stuff out of %Config if we haven't yet done so print "CONFIG must be an array ref\n" if ($self->{CONFIG} and ref $self->{CONFIG} ne 'ARRAY'); $self->{CONFIG} = [] unless (ref $self->{CONFIG}); push(@{$self->{CONFIG}}, @ExtUtils::MakeMaker::Get_from_Config); push(@{$self->{CONFIG}}, 'shellflags') if $Config{shellflags}; my(%once_only); foreach my $m (@{$self->{CONFIG}}){ next if $once_only{$m}; print "CONFIG key '$m' does not exist in Config.pm\n" unless exists $Config{$m}; $self->{uc $m} ||= $Config{$m}; $once_only{$m} = 1; } # This is too dangerous: # if ($^O eq "next") { # $self->{AR} = "libtool"; # $self->{AR_STATIC_ARGS} = "-o"; # } # But I leave it as a placeholder $self->{AR_STATIC_ARGS} ||= "cr"; # These should never be needed $self->{OBJ_EXT} ||= '.o'; $self->{LIB_EXT} ||= '.a'; $self->{MAP_TARGET} ||= "perl"; $self->{LIBPERL_A} ||= "libperl$self->{LIB_EXT}"; # make a simple check if we find strict warn "Warning: PERL_LIB ($self->{PERL_LIB}) seems not to be a perl library directory (strict.pm not found)" unless -f $self->catfile("$self->{PERL_LIB}","strict.pm") || $self->{NAME} eq "ExtUtils::MakeMaker"; } =item init_tools Initializes tools to use their common (and faster) Unix commands. =cut sub init_tools { my $self = shift; $self->{ECHO} ||= 'echo'; $self->{ECHO_N} ||= 'echo -n'; $self->{RM_F} ||= "rm -f"; $self->{RM_RF} ||= "rm -rf"; $self->{TOUCH} ||= "touch"; $self->{TEST_F} ||= "test -f"; $self->{TEST_S} ||= "test -s"; $self->{CP} ||= "cp"; $self->{MV} ||= "mv"; $self->{CHMOD} ||= "chmod"; $self->{FALSE} ||= 'false'; $self->{TRUE} ||= 'true'; $self->{LD} ||= 'ld'; return $self->SUPER::init_tools(@_); # After SUPER::init_tools so $Config{shell} has a # chance to get set. $self->{SHELL} ||= '/bin/sh'; return; } =item init_linker Unix has no need of special linker flags. =cut sub init_linker { my($self) = shift; $self->{PERL_ARCHIVE} ||= ''; $self->{PERL_ARCHIVEDEP} ||= ''; $self->{PERL_ARCHIVE_AFTER} ||= ''; $self->{EXPORT_LIST} ||= ''; } =begin _protected =item init_lib2arch $mm->init_lib2arch =end _protected =cut sub init_lib2arch { my($self) = shift; # The user who requests an installation directory explicitly # should not have to tell us an architecture installation directory # as well. We look if a directory exists that is named after the # architecture. If not we take it as a sign that it should be the # same as the requested installation directory. Otherwise we take # the found one. for my $libpair ({l=>"privlib", a=>"archlib"}, {l=>"sitelib", a=>"sitearch"}, {l=>"vendorlib", a=>"vendorarch"}, ) { my $lib = "install$libpair->{l}"; my $Lib = uc $lib; my $Arch = uc "install$libpair->{a}"; if( $self->{$Lib} && ! $self->{$Arch} ){ my($ilib) = $Config{$lib}; $self->prefixify($Arch,$ilib,$self->{$Lib}); unless (-d $self->{$Arch}) { print "Directory $self->{$Arch} not found\n" if $Verbose; $self->{$Arch} = $self->{$Lib}; } print "Defaulting $Arch to $self->{$Arch}\n" if $Verbose; } } } =item init_PERL $mm->init_PERL; Called by init_main. Sets up ABSPERL, PERL, FULLPERL and all the *PERLRUN* permutations. PERL is allowed to be miniperl FULLPERL must be a complete perl ABSPERL is PERL converted to an absolute path *PERLRUN contains everything necessary to run perl, find it's libraries, etc... *PERLRUNINST is *PERLRUN + everything necessary to find the modules being built. =cut sub init_PERL { my($self) = shift; my @defpath = (); foreach my $component ($self->{PERL_SRC}, $self->path(), $Config{binexp}) { push @defpath, $component if defined $component; } # Build up a set of file names (not command names). my $thisperl = $self->canonpath($^X); $thisperl .= $Config{exe_ext} unless # VMS might have a file version # at the end $Is{VMS} ? $thisperl =~ m/$Config{exe_ext}(;\d+)?$/i : $thisperl =~ m/$Config{exe_ext}$/i; # We need a relative path to perl when in the core. $thisperl = $self->abs2rel($thisperl) if $self->{PERL_CORE}; my @perls = ($thisperl); push @perls, map { "$_$Config{exe_ext}" } ("perl$Config{version}", 'perl5', 'perl'); # miniperl has priority over all but the canonical perl when in the # core. Otherwise its a last resort. my $miniperl = "miniperl$Config{exe_ext}"; if( $self->{PERL_CORE} ) { splice @perls, 1, 0, $miniperl; } else { push @perls, $miniperl; } $self->{PERL} ||= $self->find_perl(5.0, \@perls, \@defpath, $Verbose ); my $perl = $self->{PERL}; $perl =~ s/^"//; my $has_mcr = $perl =~ s/^MCR\s*//; my $perlflags = ''; my $stripped_perl; while ($perl) { ($stripped_perl = $perl) =~ s/"$//; last if -x $stripped_perl; last unless $perl =~ s/(\s+\S+)$//; $perlflags = $1.$perlflags; } $self->{PERL} = $stripped_perl; $self->{PERL} = 'MCR '.$self->{PERL} if $has_mcr || $Is{VMS}; # When built for debugging, VMS doesn't create perl.exe but ndbgperl.exe. my $perl_name = 'perl'; $perl_name = 'ndbgperl' if $Is{VMS} && defined $Config{usevmsdebug} && $Config{usevmsdebug} eq 'define'; # XXX This logic is flawed. If "miniperl" is anywhere in the path # it will get confused. It should be fixed to work only on the filename. # Define 'FULLPERL' to be a non-miniperl (used in test: target) unless ($self->{FULLPERL}) { ($self->{FULLPERL} = $self->{PERL}) =~ s/\Q$miniperl\E$/$perl_name$Config{exe_ext}/i; $self->{FULLPERL} = qq{"$self->{FULLPERL}"}.$perlflags; } # Can't have an image name with quotes, and findperl will have # already escaped spaces. $self->{FULLPERL} =~ tr/"//d if $Is{VMS}; # `dmake` can fail for image (aka, executable) names which start with double-quotes # * push quote inward by at least one character (or the drive prefix, if present) # * including any initial directory separator preserves the `file_name_is_absolute` property $self->{FULLPERL} =~ s/^"(\S(:\\|:)?)/$1"/ if $self->is_make_type('dmake'); # Little hack to get around VMS's find_perl putting "MCR" in front # sometimes. $self->{ABSPERL} = $self->{PERL}; $has_mcr = $self->{ABSPERL} =~ s/^MCR\s*//; if( $self->file_name_is_absolute($self->{ABSPERL}) ) { $self->{ABSPERL} = '$(PERL)'; } else { $self->{ABSPERL} = $self->rel2abs($self->{ABSPERL}); # Quote the perl command if it contains whitespace $self->{ABSPERL} = $self->quote_literal($self->{ABSPERL}) if $self->{ABSPERL} =~ /\s/; $self->{ABSPERL} = 'MCR '.$self->{ABSPERL} if $has_mcr; } $self->{PERL} = qq{"$self->{PERL}"}.$perlflags; # Can't have an image name with quotes, and findperl will have # already escaped spaces. $self->{PERL} =~ tr/"//d if $Is{VMS}; # `dmake` can fail for image (aka, executable) names which start with double-quotes # * push quote inward by at least one character (or the drive prefix, if present) # * including any initial directory separator preserves the `file_name_is_absolute` property $self->{PERL} =~ s/^"(\S(:\\|:)?)/$1"/ if $self->is_make_type('dmake'); # Are we building the core? $self->{PERL_CORE} = $ENV{PERL_CORE} unless exists $self->{PERL_CORE}; $self->{PERL_CORE} = 0 unless defined $self->{PERL_CORE}; # Make sure perl can find itself before it's installed. my $lib_paths = $self->{UNINSTALLED_PERL} || $self->{PERL_CORE} ? ( $self->{PERL_ARCHLIB} && $self->{PERL_LIB} && $self->{PERL_ARCHLIB} ne $self->{PERL_LIB} ) ? q{ "-I$(PERL_LIB)" "-I$(PERL_ARCHLIB)"} : q{ "-I$(PERL_LIB)"} : undef; my $inst_lib_paths = $self->{INST_ARCHLIB} ne $self->{INST_LIB} ? 'RUN)'.$perlflags.' "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"' : 'RUN)'.$perlflags.' "-I$(INST_LIB)"'; # How do we run perl? foreach my $perl (qw(PERL FULLPERL ABSPERL)) { my $run = $perl.'RUN'; $self->{$run} = qq{\$($perl)}; $self->{$run} .= $lib_paths if $lib_paths; $self->{$perl.'RUNINST'} = '$('.$perl.$inst_lib_paths; } return 1; } =item init_platform =item platform_constants Add MM_Unix_VERSION. =cut sub init_platform { my($self) = shift; $self->{MM_Unix_VERSION} = $VERSION; $self->{PERL_MALLOC_DEF} = '-DPERL_EXTMALLOC_DEF -Dmalloc=Perl_malloc '. '-Dfree=Perl_mfree -Drealloc=Perl_realloc '. '-Dcalloc=Perl_calloc'; } sub platform_constants { my($self) = shift; my $make_frag = ''; foreach my $macro (qw(MM_Unix_VERSION PERL_MALLOC_DEF)) { next unless defined $self->{$macro}; $make_frag .= "$macro = $self->{$macro}\n"; } return $make_frag; } =item init_PERM $mm->init_PERM Called by init_main. Initializes PERL_* =cut sub init_PERM { my($self) = shift; $self->{PERM_DIR} = 755 unless defined $self->{PERM_DIR}; $self->{PERM_RW} = 644 unless defined $self->{PERM_RW}; $self->{PERM_RWX} = 755 unless defined $self->{PERM_RWX}; return 1; } =item init_xs $mm->init_xs Sets up macros having to do with XS code. Currently just INST_STATIC, INST_DYNAMIC and INST_BOOT. =cut sub init_xs { my $self = shift; if ($self->has_link_code()) { $self->{INST_STATIC} = $self->catfile('$(INST_ARCHAUTODIR)', '$(BASEEXT)$(LIB_EXT)'); $self->{INST_DYNAMIC} = $self->catfile('$(INST_ARCHAUTODIR)', '$(DLBASE).$(DLEXT)'); $self->{INST_BOOT} = $self->catfile('$(INST_ARCHAUTODIR)', '$(BASEEXT).bs'); if ($self->{XSMULTI}) { my @exts = $self->_xs_list_basenames; my (@statics, @dynamics, @boots); for my $ext (@exts) { my ($v, $d, $f) = File::Spec->splitpath($ext); my @d = File::Spec->splitdir($d); shift @d if defined $d[0] and $d[0] eq 'lib'; pop @d if $d[$#d] eq ''; my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f); my $instfile = $self->catfile($instdir, $f); push @statics, "$instfile\$(LIB_EXT)"; # Dynamic library names may need special handling. my $dynfile = $instfile; eval { require DynaLoader }; if (defined &DynaLoader::mod2fname) { $dynfile = $self->catfile($instdir, &DynaLoader::mod2fname([@d, $f])); } push @dynamics, "$dynfile.\$(DLEXT)"; push @boots, "$instfile.bs"; } $self->{INST_STATIC} = join ' ', @statics; $self->{INST_DYNAMIC} = join ' ', @dynamics; $self->{INST_BOOT} = join ' ', @boots; } } else { $self->{INST_STATIC} = ''; $self->{INST_DYNAMIC} = ''; $self->{INST_BOOT} = ''; } } =item install (o) Defines the install target. =cut sub install { my($self, %attribs) = @_; my(@m); push @m, q{ install :: pure_install doc_install $(NOECHO) $(NOOP) install_perl :: pure_perl_install doc_perl_install $(NOECHO) $(NOOP) install_site :: pure_site_install doc_site_install $(NOECHO) $(NOOP) install_vendor :: pure_vendor_install doc_vendor_install $(NOECHO) $(NOOP) pure_install :: pure_$(INSTALLDIRS)_install $(NOECHO) $(NOOP) doc_install :: doc_$(INSTALLDIRS)_install $(NOECHO) $(NOOP) pure__install : pure_site_install $(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site doc__install : doc_site_install $(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site pure_perl_install :: all $(NOECHO) $(MOD_INSTALL) \ }; push @m, q{ read "}.$self->catfile('$(PERL_ARCHLIB)','auto','$(FULLEXT)','.packlist').q{" \ write "}.$self->catfile('$(DESTINSTALLARCHLIB)','auto','$(FULLEXT)','.packlist').q{" \ } unless $self->{NO_PACKLIST}; push @m, q{ "$(INST_LIB)" "$(DESTINSTALLPRIVLIB)" \ "$(INST_ARCHLIB)" "$(DESTINSTALLARCHLIB)" \ "$(INST_BIN)" "$(DESTINSTALLBIN)" \ "$(INST_SCRIPT)" "$(DESTINSTALLSCRIPT)" \ "$(INST_MAN1DIR)" "$(DESTINSTALLMAN1DIR)" \ "$(INST_MAN3DIR)" "$(DESTINSTALLMAN3DIR)" $(NOECHO) $(WARN_IF_OLD_PACKLIST) \ "}.$self->catdir('$(SITEARCHEXP)','auto','$(FULLEXT)').q{" pure_site_install :: all $(NOECHO) $(MOD_INSTALL) \ }; push @m, q{ read "}.$self->catfile('$(SITEARCHEXP)','auto','$(FULLEXT)','.packlist').q{" \ write "}.$self->catfile('$(DESTINSTALLSITEARCH)','auto','$(FULLEXT)','.packlist').q{" \ } unless $self->{NO_PACKLIST}; push @m, q{ "$(INST_LIB)" "$(DESTINSTALLSITELIB)" \ "$(INST_ARCHLIB)" "$(DESTINSTALLSITEARCH)" \ "$(INST_BIN)" "$(DESTINSTALLSITEBIN)" \ "$(INST_SCRIPT)" "$(DESTINSTALLSITESCRIPT)" \ "$(INST_MAN1DIR)" "$(DESTINSTALLSITEMAN1DIR)" \ "$(INST_MAN3DIR)" "$(DESTINSTALLSITEMAN3DIR)" $(NOECHO) $(WARN_IF_OLD_PACKLIST) \ "}.$self->catdir('$(PERL_ARCHLIB)','auto','$(FULLEXT)').q{" pure_vendor_install :: all $(NOECHO) $(MOD_INSTALL) \ }; push @m, q{ read "}.$self->catfile('$(VENDORARCHEXP)','auto','$(FULLEXT)','.packlist').q{" \ write "}.$self->catfile('$(DESTINSTALLVENDORARCH)','auto','$(FULLEXT)','.packlist').q{" \ } unless $self->{NO_PACKLIST}; push @m, q{ "$(INST_LIB)" "$(DESTINSTALLVENDORLIB)" \ "$(INST_ARCHLIB)" "$(DESTINSTALLVENDORARCH)" \ "$(INST_BIN)" "$(DESTINSTALLVENDORBIN)" \ "$(INST_SCRIPT)" "$(DESTINSTALLVENDORSCRIPT)" \ "$(INST_MAN1DIR)" "$(DESTINSTALLVENDORMAN1DIR)" \ "$(INST_MAN3DIR)" "$(DESTINSTALLVENDORMAN3DIR)" }; push @m, q{ doc_perl_install :: all $(NOECHO) $(NOOP) doc_site_install :: all $(NOECHO) $(NOOP) doc_vendor_install :: all $(NOECHO) $(NOOP) } if $self->{NO_PERLLOCAL}; push @m, q{ doc_perl_install :: all $(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod" -$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)" -$(NOECHO) $(DOC_INSTALL) \ "Module" "$(NAME)" \ "installed into" "$(INSTALLPRIVLIB)" \ LINKTYPE "$(LINKTYPE)" \ VERSION "$(VERSION)" \ EXE_FILES "$(EXE_FILES)" \ >> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{" doc_site_install :: all $(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod" -$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)" -$(NOECHO) $(DOC_INSTALL) \ "Module" "$(NAME)" \ "installed into" "$(INSTALLSITELIB)" \ LINKTYPE "$(LINKTYPE)" \ VERSION "$(VERSION)" \ EXE_FILES "$(EXE_FILES)" \ >> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{" doc_vendor_install :: all $(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod" -$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)" -$(NOECHO) $(DOC_INSTALL) \ "Module" "$(NAME)" \ "installed into" "$(INSTALLVENDORLIB)" \ LINKTYPE "$(LINKTYPE)" \ VERSION "$(VERSION)" \ EXE_FILES "$(EXE_FILES)" \ >> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{" } unless $self->{NO_PERLLOCAL}; push @m, q{ uninstall :: uninstall_from_$(INSTALLDIRS)dirs $(NOECHO) $(NOOP) uninstall_from_perldirs :: $(NOECHO) $(UNINSTALL) "}.$self->catfile('$(PERL_ARCHLIB)','auto','$(FULLEXT)','.packlist').q{" uninstall_from_sitedirs :: $(NOECHO) $(UNINSTALL) "}.$self->catfile('$(SITEARCHEXP)','auto','$(FULLEXT)','.packlist').q{" uninstall_from_vendordirs :: $(NOECHO) $(UNINSTALL) "}.$self->catfile('$(VENDORARCHEXP)','auto','$(FULLEXT)','.packlist').q{" }; join("",@m); } =item installbin (o) Defines targets to make and to install EXE_FILES. =cut sub installbin { my($self) = shift; return "" unless $self->{EXE_FILES} && ref $self->{EXE_FILES} eq "ARRAY"; my @exefiles = sort @{$self->{EXE_FILES}}; return "" unless @exefiles; @exefiles = map vmsify($_), @exefiles if $Is{VMS}; my %fromto; for my $from (@exefiles) { my($path)= $self->catfile('$(INST_SCRIPT)', basename($from)); local($_) = $path; # for backwards compatibility my $to = $self->libscan($path); print "libscan($from) => '$to'\n" if ($Verbose >=2); $to = vmsify($to) if $Is{VMS}; $fromto{$from} = $to; } my @to = sort values %fromto; my @m; push(@m, qq{ EXE_FILES = @exefiles pure_all :: @to \$(NOECHO) \$(NOOP) realclean :: }); # realclean can get rather large. push @m, map "\t$_\n", $self->split_command('$(RM_F)', @to); push @m, "\n"; # A target for each exe file. my @froms = sort keys %fromto; for my $from (@froms) { # 1 2 push @m, _sprintf562 <<'MAKE', $from, $fromto{$from}; %2$s : %1$s $(FIRST_MAKEFILE) $(INST_SCRIPT)$(DFSEP).exists $(INST_BIN)$(DFSEP).exists $(NOECHO) $(RM_F) %2$s $(CP) %1$s %2$s $(FIXIN) %2$s -$(NOECHO) $(CHMOD) $(PERM_RWX) %2$s MAKE } join "", @m; } =item linkext (o) Defines the linkext target which in turn defines the LINKTYPE. =cut # LINKTYPE => static or dynamic or '' sub linkext { my($self, %attribs) = @_; my $linktype = $attribs{LINKTYPE}; $linktype = $self->{LINKTYPE} unless defined $linktype; if (defined $linktype and $linktype eq '') { warn "Warning: LINKTYPE set to '', no longer necessary\n"; } $linktype = '$(LINKTYPE)' unless defined $linktype; " linkext :: $linktype \$(NOECHO) \$(NOOP) "; } =item lsdir Takes as arguments a directory name and a regular expression. Returns all entries in the directory that match the regular expression. =cut sub lsdir { # $self my(undef, $dir, $regex) = @_; opendir(my $dh, defined($dir) ? $dir : ".") or return; my @ls = readdir $dh; closedir $dh; @ls = grep(/$regex/, @ls) if defined $regex; @ls; } =item macro (o) Simple subroutine to insert the macros defined by the macro attribute into the Makefile. =cut sub macro { my($self,%attribs) = @_; my @m; foreach my $key (sort keys %attribs) { my $val = $attribs{$key}; push @m, "$key = $val\n"; } join "", @m; } =item makeaperl (o) Called by staticmake. Defines how to write the Makefile to produce a static new perl. By default the Makefile produced includes all the static extensions in the perl library. (Purified versions of library files, e.g., DynaLoader_pure_p1_c0_032.a are automatically ignored to avoid link errors.) =cut sub makeaperl { my($self, %attribs) = @_; my($makefilename, $searchdirs, $static, $extra, $perlinc, $target, $tmp, $libperl) = @attribs{qw(MAKE DIRS STAT EXTRA INCL TARGET TMP LIBPERL)}; s/^(.*)/"-I$1"/ for @{$perlinc || []}; my(@m); push @m, " # --- MakeMaker makeaperl section --- MAP_TARGET = $target FULLPERL = $self->{FULLPERL} MAP_PERLINC = @{$perlinc || []} "; return join '', @m if $self->{PARENT}; my($dir) = join ":", @{$self->{DIR}}; unless ($self->{MAKEAPERL}) { push @m, q{ $(MAP_TARGET) :: $(MAKE_APERL_FILE) $(MAKE) $(USEMAKEFILE) $(MAKE_APERL_FILE) $@ $(MAKE_APERL_FILE) : static $(FIRST_MAKEFILE) pm_to_blib $(NOECHO) $(ECHO) Writing \"$(MAKE_APERL_FILE)\" for this $(MAP_TARGET) $(NOECHO) $(PERLRUNINST) \ Makefile.PL DIR="}, $dir, q{" \ MAKEFILE=$(MAKE_APERL_FILE) LINKTYPE=static \ MAKEAPERL=1 NORECURS=1 CCCDLFLAGS=}; foreach (@ARGV){ my $arg = $_; # avoid lvalue aliasing if ( $arg =~ /(^.*?=)(.*['\s].*)/ ) { $arg = $1 . $self->quote_literal($2); } push @m, " \\\n\t\t$arg"; } push @m, "\n"; return join '', @m; } my $cccmd = $self->const_cccmd($libperl); $cccmd =~ s/^CCCMD\s*=\s*//; $cccmd =~ s/\$\(INC\)/ "-I$self->{PERL_INC}" /; $cccmd .= " $Config{cccdlflags}" if ($Config{useshrplib} eq 'true'); $cccmd =~ s/\(CC\)/\(PERLMAINCC\)/; # The front matter of the linkcommand... my $linkcmd = join ' ', "\$(CC)", grep($_, @Config{qw(ldflags ccdlflags)}); $linkcmd =~ s/\s+/ /g; $linkcmd =~ s,(perl\.exp),\$(PERL_INC)/$1,; # Which *.a files could we make use of... my $staticlib21 = $self->_find_static_libs($searchdirs); # We trust that what has been handed in as argument, will be buildable $static = [] unless $static; @$staticlib21{@{$static}} = (1) x @{$static}; $extra = [] unless $extra && ref $extra eq 'ARRAY'; for (sort keys %$staticlib21) { next unless /\Q$self->{LIB_EXT}\E\z/; $_ = dirname($_) . "/extralibs.ld"; push @$extra, $_; } s/^(.*)/"-I$1"/ for @{$perlinc || []}; $target ||= "perl"; $tmp ||= "."; # MAP_STATIC doesn't look into subdirs yet. Once "all" is made and we # regenerate the Makefiles, MAP_STATIC and the dependencies for # extralibs.all are computed correctly my @map_static = reverse sort keys %$staticlib21; push @m, " MAP_LINKCMD = $linkcmd MAP_STATIC = ", join(" \\\n\t", map { qq{"$_"} } @map_static), " MAP_STATICDEP = ", join(' ', map { $self->quote_dep($_) } @map_static), " MAP_PRELIBS = $Config{perllibs} $Config{cryptlib} "; my $lperl; if (defined $libperl) { ($lperl = $libperl) =~ s/\$\(A\)/$self->{LIB_EXT}/; } unless ($libperl && -f $lperl) { # Ilya's code... my $dir = $self->{PERL_SRC} || "$self->{PERL_ARCHLIB}/CORE"; $dir = "$self->{PERL_ARCHLIB}/.." if $self->{UNINSTALLED_PERL}; $libperl ||= "libperl$self->{LIB_EXT}"; $libperl = "$dir/$libperl"; $lperl ||= "libperl$self->{LIB_EXT}"; $lperl = "$dir/$lperl"; if (! -f $libperl and ! -f $lperl) { # We did not find a static libperl. Maybe there is a shared one? if ($Is{SunOS}) { $lperl = $libperl = "$dir/$Config{libperl}"; # SUNOS ld does not take the full path to a shared library $libperl = '' if $Is{SunOS4}; } } print <{PERL_SRC}); Warning: $libperl not found If you're going to build a static perl binary, make sure perl is installed otherwise ignore this warning EOF } # SUNOS ld does not take the full path to a shared library my $llibperl = $libperl ? '$(MAP_LIBPERL)' : '-lperl'; my $libperl_dep = $self->quote_dep($libperl); push @m, " MAP_LIBPERL = $libperl MAP_LIBPERLDEP = $libperl_dep LLIBPERL = $llibperl "; push @m, ' $(INST_ARCHAUTODIR)/extralibs.all : $(INST_ARCHAUTODIR)$(DFSEP).exists '.join(" \\\n\t", @$extra).' $(NOECHO) $(RM_F) $@ $(NOECHO) $(TOUCH) $@ '; foreach my $catfile (@$extra){ push @m, "\tcat $catfile >> \$\@\n"; } my $ldfrom = $self->{XSMULTI} ? '' : '$(LDFROM)'; # 1 2 3 4 push @m, _sprintf562 <<'EOF', $tmp, $ldfrom, $self->xs_obj_opt('$@'), $makefilename; $(MAP_TARGET) :: %1$s/perlmain$(OBJ_EXT) $(MAP_LIBPERLDEP) $(MAP_STATICDEP) $(INST_ARCHAUTODIR)/extralibs.all $(MAP_LINKCMD) %2$s $(OPTIMIZE) %1$s/perlmain$(OBJ_EXT) %3$s $(MAP_STATIC) "$(LLIBPERL)" `cat $(INST_ARCHAUTODIR)/extralibs.all` $(MAP_PRELIBS) $(NOECHO) $(ECHO) "To install the new '$(MAP_TARGET)' binary, call" $(NOECHO) $(ECHO) " $(MAKE) $(USEMAKEFILE) %4$s inst_perl MAP_TARGET=$(MAP_TARGET)" $(NOECHO) $(ECHO) " $(MAKE) $(USEMAKEFILE) %4$s map_clean" %1$s/perlmain\$(OBJ_EXT): %1$s/perlmain.c EOF push @m, "\t".$self->cd($tmp, qq[$cccmd "-I\$(PERL_INC)" perlmain.c])."\n"; my $maybe_DynaLoader = $Config{usedl} ? 'q(DynaLoader)' : ''; push @m, _sprintf562 <<'EOF', $tmp, $makefilename, $maybe_DynaLoader; %1$s/perlmain.c: %2$s $(NOECHO) $(ECHO) Writing $@ $(NOECHO) $(PERL) $(MAP_PERLINC) "-MExtUtils::Miniperl" \ -e "writemain(grep(s#.*/auto/##s, @ARGV), %3$s)" $(MAP_STATIC) > $@t $(MV) $@t $@ EOF push @m, "\t", q{$(NOECHO) $(PERL) "$(INSTALLSCRIPT)/fixpmain" } if (defined (&Dos::UseLFN) && Dos::UseLFN()==0); push @m, q{ doc_inst_perl : $(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLARCHLIB)/perllocal.pod" -$(NOECHO) $(MKPATH) "$(DESTINSTALLARCHLIB)" -$(NOECHO) $(DOC_INSTALL) \ "Perl binary" "$(MAP_TARGET)" \ MAP_STATIC "$(MAP_STATIC)" \ MAP_EXTRA "`cat $(INST_ARCHAUTODIR)/extralibs.all`" \ MAP_LIBPERL "$(MAP_LIBPERL)" \ >> "}.$self->catfile('$(DESTINSTALLARCHLIB)','perllocal.pod').q{" }; push @m, q{ inst_perl : pure_inst_perl doc_inst_perl pure_inst_perl : $(MAP_TARGET) }.$self->{CP}.q{ $(MAP_TARGET) "}.$self->catfile('$(DESTINSTALLBIN)','$(MAP_TARGET)').q{" clean :: map_clean map_clean : }.$self->{RM_F}.qq{ $tmp/perlmain\$(OBJ_EXT) $tmp/perlmain.c \$(MAP_TARGET) $makefilename \$(INST_ARCHAUTODIR)/extralibs.all }; join '', @m; } # utility method sub _find_static_libs { my ($self, $searchdirs) = @_; # don't use File::Spec here because on Win32 F::F still uses "/" my $installed_version = join('/', 'auto', $self->{FULLEXT}, "$self->{BASEEXT}$self->{LIB_EXT}" ); my %staticlib21; require File::Find; File::Find::find(sub { if ($File::Find::name =~ m{/auto/share\z}) { # in a subdir of auto/share, prune because e.g. # Alien::pkgconfig uses File::ShareDir to put .a files # there. do not want $File::Find::prune = 1; return; } return unless m/\Q$self->{LIB_EXT}\E$/; return unless -f 'extralibs.ld'; # this checks is a "proper" XS installation # Skip perl's libraries. return if m/^libperl/ or m/^perl\Q$self->{LIB_EXT}\E$/; # Skip purified versions of libraries # (e.g., DynaLoader_pure_p1_c0_032.a) return if m/_pure_\w+_\w+_\w+\.\w+$/ and -f "$File::Find::dir/.pure"; if( exists $self->{INCLUDE_EXT} ){ my $found = 0; (my $xx = $File::Find::name) =~ s,.*?/auto/,,s; $xx =~ s,/?$_,,; $xx =~ s,/,::,g; # Throw away anything not explicitly marked for inclusion. # DynaLoader is implied. foreach my $incl ((@{$self->{INCLUDE_EXT}},'DynaLoader')){ if( $xx eq $incl ){ $found++; last; } } return unless $found; } elsif( exists $self->{EXCLUDE_EXT} ){ (my $xx = $File::Find::name) =~ s,.*?/auto/,,s; $xx =~ s,/?$_,,; $xx =~ s,/,::,g; # Throw away anything explicitly marked for exclusion foreach my $excl (@{$self->{EXCLUDE_EXT}}){ return if( $xx eq $excl ); } } # don't include the installed version of this extension. I # leave this line here, although it is not necessary anymore: # I patched minimod.PL instead, so that Miniperl.pm won't # include duplicates # Once the patch to minimod.PL is in the distribution, I can # drop it return if $File::Find::name =~ m:\Q$installed_version\E\z:; return if !$self->xs_static_lib_is_xs($_); use Cwd 'cwd'; $staticlib21{cwd() . "/" . $_}++; }, grep( -d $_, map { $self->catdir($_, 'auto') } @{$searchdirs || []}) ); return \%staticlib21; } =item xs_static_lib_is_xs (o) Called by a utility method of makeaperl. Checks whether a given file is an XS library by seeing whether it defines any symbols starting with C (with an optional leading underscore - needed on MacOS). =cut sub xs_static_lib_is_xs { my ($self, $libfile) = @_; my $devnull = File::Spec->devnull; return `nm $libfile 2>$devnull` =~ /\b_?boot_/; } =item makefile (o) Defines how to rewrite the Makefile. =cut sub makefile { my($self) = shift; my $m; # We do not know what target was originally specified so we # must force a manual rerun to be sure. But as it should only # happen very rarely it is not a significant problem. $m = ' $(OBJECT) : $(FIRST_MAKEFILE) ' if $self->{OBJECT}; my $newer_than_target = $Is{VMS} ? '$(MMS$SOURCE_LIST)' : '$?'; my $mpl_args = join " ", map qq["$_"], @ARGV; my $cross = ''; if (defined $::Cross::platform) { # Inherited from win32/buildext.pl $cross = "-MCross=$::Cross::platform "; } $m .= sprintf <<'MAKE_FRAG', $newer_than_target, $cross, $mpl_args; # We take a very conservative approach here, but it's worth it. # We move Makefile to Makefile.old here to avoid gnu make looping. $(FIRST_MAKEFILE) : Makefile.PL $(CONFIGDEP) $(NOECHO) $(ECHO) "Makefile out-of-date with respect to %s" $(NOECHO) $(ECHO) "Cleaning current config before rebuilding Makefile..." -$(NOECHO) $(RM_F) $(MAKEFILE_OLD) -$(NOECHO) $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) - $(MAKE) $(USEMAKEFILE) $(MAKEFILE_OLD) clean $(DEV_NULL) $(PERLRUN) %sMakefile.PL %s $(NOECHO) $(ECHO) "==> Your Makefile has been rebuilt. <==" $(NOECHO) $(ECHO) "==> Please rerun the $(MAKE) command. <==" $(FALSE) MAKE_FRAG return $m; } =item maybe_command Returns true, if the argument is likely to be a command. =cut sub maybe_command { my($self,$file) = @_; return $file if -x $file && ! -d $file; return; } =item needs_linking (o) Does this module need linking? Looks into subdirectory objects (see also has_link_code()) =cut sub needs_linking { my($self) = shift; my $caller = (caller(0))[3]; confess("needs_linking called too early") if $caller =~ /^ExtUtils::MakeMaker::/; return $self->{NEEDS_LINKING} if defined $self->{NEEDS_LINKING}; if ($self->has_link_code or $self->{MAKEAPERL}){ $self->{NEEDS_LINKING} = 1; return 1; } foreach my $child (keys %{$self->{CHILDREN}}) { if ($self->{CHILDREN}->{$child}->needs_linking) { $self->{NEEDS_LINKING} = 1; return 1; } } return $self->{NEEDS_LINKING} = 0; } =item parse_abstract parse a file and return what you think is the ABSTRACT =cut sub parse_abstract { my($self,$parsefile) = @_; my $result; local $/ = "\n"; open(my $fh, '<', $parsefile) or die "Could not open '$parsefile': $!"; binmode $fh; my $inpod = 0; my $pod_encoding; my $package = $self->{DISTNAME}; $package =~ s/-/::/g; while (<$fh>) { $inpod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $inpod; next if !$inpod; s#\r*\n\z##; # handle CRLF input if ( /^=encoding\s*(.*)$/i ) { $pod_encoding = $1; } if ( /^($package(?:\.pm)? \s+ -+ \s+)(.*)/x ) { $result = $2; next; } next unless $result; if ( $result && ( /^\s*$/ || /^\=/ ) ) { last; } $result = join ' ', $result, $_; } close $fh; if ( $pod_encoding and !( "$]" < 5.008 or !$Config{useperlio} ) ) { # Have to wrap in an eval{} for when running under PERL_CORE # Encode isn't available during build phase and parsing # ABSTRACT isn't important there eval { require Encode; $result = Encode::decode($pod_encoding, $result); } } return $result; } =item parse_version my $version = MM->parse_version($file); Parse a $file and return what $VERSION is set to by the first assignment. It will return the string "undef" if it can't figure out what $VERSION is. $VERSION should be for all to see, so C or plain $VERSION are okay, but C is not. C is also checked for. The first version declaration found is used, but this may change as it differs from how Perl does it. parse_version() will try to C before checking for C<$VERSION> so the following will work. $VERSION = qv(1.2.3); =cut sub parse_version { my($self,$parsefile) = @_; my $result; local $/ = "\n"; local $_; open(my $fh, '<', $parsefile) or die "Could not open '$parsefile': $!"; my $inpod = 0; while (<$fh>) { $inpod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $inpod; next if $inpod || /^\s*#/; chop; next if /^\s*(if|unless|elsif)/; if ( m{^ \s* package \s+ \w[\w\:\']* \s+ (v?[0-9._]+) \s* (;|\{) }x ) { no warnings; $result = $1; } elsif ( m{(?=!])\=[^=]}x ) { $result = $self->get_version($parsefile, $1, $2); } else { next; } last if defined $result; } close $fh; if ( defined $result && $result !~ /^v?[\d_\.]+$/ ) { require version; my $normal = eval { version->new( $result ) }; $result = $normal if defined $normal; } if ( defined $result ) { $result = "undef" unless $result =~ m!^v?[\d_\.\-]+$! or eval { version->parse( $result ) }; } $result = "undef" unless defined $result; return $result; } sub get_version { my ($self, $parsefile, $sigil, $name) = @_; my $line = $_; # from the while() loop in parse_version { package ExtUtils::MakeMaker::_version; undef *version; # in case of unexpected version() sub eval { require version; version::->import; }; no strict; no warnings; local *{$name}; $line = $1 if $line =~ m{^(.+)}s; eval($line); ## no critic return ${$name}; } } =item pasthru (o) Defines the string that is passed to recursive make calls in subdirectories. The variables like C are used in each level, and passed downwards on the command-line with e.g. the value of that level's DEFINE. Example: # Level 0 has DEFINE = -Dfunky # This code will define level 0's PASTHRU=PASTHRU_DEFINE="$(DEFINE) # $(PASTHRU_DEFINE)" # Level 0's $(CCCMD) will include macros $(DEFINE) and $(PASTHRU_DEFINE) # So will level 1's, so when level 1 compiles, it will get right values # And so ad infinitum =cut sub pasthru { my($self) = shift; my(@m); my(@pasthru); my($sep) = $Is{VMS} ? ',' : ''; $sep .= "\\\n\t"; foreach my $key (qw(LIB LIBPERL_A LINKTYPE OPTIMIZE PREFIX INSTALL_BASE) ) { next unless defined $self->{$key}; push @pasthru, "$key=\"\$($key)\""; } foreach my $key (qw(DEFINE INC)) { # default to the make var my $val = qq{\$($key)}; # expand within perl if given since need to use quote_literal # since INC might include space-protecting ""! chomp($val = $self->{$key}) if defined $self->{$key}; $val .= " \$(PASTHRU_$key)"; my $quoted = $self->quote_literal($val); push @pasthru, qq{PASTHRU_$key=$quoted}; } push @m, "\nPASTHRU = ", join ($sep, @pasthru), "\n"; join "", @m; } =item perl_script Takes one argument, a file name, and returns the file name, if the argument is likely to be a perl script. On MM_Unix this is true for any ordinary, readable file. =cut sub perl_script { my($self,$file) = @_; return $file if -r $file && -f _; return; } =item perldepend (o) Defines the dependency from all *.h files that come with the perl distribution. =cut sub perldepend { my($self) = shift; my(@m); my $make_config = $self->cd('$(PERL_SRC)', '$(MAKE) lib/Config.pm'); push @m, sprintf <<'MAKE_FRAG', $make_config if $self->{PERL_SRC}; # Check for unpropogated config.sh changes. Should never happen. # We do NOT just update config.h because that is not sufficient. # An out of date config.h is not fatal but complains loudly! $(PERL_INCDEP)/config.h: $(PERL_SRC)/config.sh -$(NOECHO) $(ECHO) "Warning: $(PERL_INC)/config.h out of date with $(PERL_SRC)/config.sh"; $(FALSE) $(PERL_ARCHLIB)/Config.pm: $(PERL_SRC)/config.sh $(NOECHO) $(ECHO) "Warning: $(PERL_ARCHLIB)/Config.pm may be out of date with $(PERL_SRC)/config.sh" %s MAKE_FRAG return join "", @m unless $self->needs_linking; if ($self->{OBJECT}) { # Need to add an object file dependency on the perl headers. # this is very important for XS modules in perl.git development. push @m, $self->_perl_header_files_fragment("/"); # Directory separator between $(PERL_INC)/header.h } push @m, join(" ", sort values %{$self->{XS}})." : \$(XSUBPPDEPS)\n" if %{$self->{XS}}; return join "\n", @m; } =item pm_to_blib Defines target that copies all files in the hash PM to their destination and autosplits them. See L =cut sub pm_to_blib { my $self = shift; my($autodir) = $self->catdir('$(INST_LIB)','auto'); my $r = q{ pm_to_blib : $(FIRST_MAKEFILE) $(TO_INST_PM) }; # VMS will swallow '' and PM_FILTER is often empty. So use q[] my $pm_to_blib = $self->oneliner(<split_command($pm_to_blib, map { ($self->quote_literal($_) => $self->quote_literal($self->{PM}->{$_})) } sort keys %{$self->{PM}}); $r .= join '', map { "\t\$(NOECHO) $_\n" } @cmds; $r .= qq{\t\$(NOECHO) \$(TOUCH) pm_to_blib\n}; return $r; } # transform dot-separated version string into comma-separated quadruple # examples: '1.2.3.4.5' => '1,2,3,4' # '1.2.3' => '1,2,3,0' sub _ppd_version { my ($self, $string) = @_; return join ',', ((split /\./, $string), (0) x 4)[0..3]; } =item ppd Defines target that creates a PPD (Perl Package Description) file for a binary distribution. =cut sub ppd { my($self) = @_; my $abstract = $self->{ABSTRACT} || ''; $abstract =~ s/\n/\\n/sg; $abstract =~ s//>/g; my $author = join(', ',@{ ref $self->{AUTHOR} eq 'ARRAY' ? $self->{AUTHOR} : [ $self->{AUTHOR} || '']}); $author =~ s//>/g; my $ppd_file = "$self->{DISTNAME}.ppd"; my @ppd_chunks = qq(\n); push @ppd_chunks, sprintf <<'PPD_HTML', $abstract, $author; %s %s PPD_HTML push @ppd_chunks, " \n"; if ( $self->{MIN_PERL_VERSION} ) { my $min_perl_version = $self->_ppd_version($self->{MIN_PERL_VERSION}); push @ppd_chunks, sprintf <<'PPD_PERLVERS', $min_perl_version; PPD_PERLVERS } # Don't add "perl" to requires. perl dependencies are # handles by ARCHITECTURE. my %prereqs = %{$self->{PREREQ_PM}}; delete $prereqs{perl}; # Build up REQUIRE foreach my $prereq (sort keys %prereqs) { my $name = $prereq; $name .= '::' unless $name =~ /::/; my $version = $prereqs{$prereq}; my %attrs = ( NAME => $name ); $attrs{VERSION} = $version if $version; my $attrs = join " ", map { qq[$_="$attrs{$_}"] } sort keys %attrs; push @ppd_chunks, qq( \n); } my $archname = $Config{archname}; # archname did not change from 5.6 to 5.8, but those versions may # not be not binary compatible so now we append the part of the # version that changes when binary compatibility may change if ("$]" >= 5.008) { $archname .= "-$Config{api_revision}.$Config{api_version}"; } push @ppd_chunks, sprintf <<'PPD_OUT', $archname; PPD_OUT if ($self->{PPM_INSTALL_SCRIPT}) { if ($self->{PPM_INSTALL_EXEC}) { push @ppd_chunks, sprintf qq{ %s\n}, $self->{PPM_INSTALL_EXEC}, $self->{PPM_INSTALL_SCRIPT}; } else { push @ppd_chunks, sprintf qq{ %s\n}, $self->{PPM_INSTALL_SCRIPT}; } } if ($self->{PPM_UNINSTALL_SCRIPT}) { if ($self->{PPM_UNINSTALL_EXEC}) { push @ppd_chunks, sprintf qq{ %s\n}, $self->{PPM_UNINSTALL_EXEC}, $self->{PPM_UNINSTALL_SCRIPT}; } else { push @ppd_chunks, sprintf qq{ %s\n}, $self->{PPM_UNINSTALL_SCRIPT}; } } my ($bin_location) = $self->{BINARY_LOCATION} || ''; $bin_location =~ s/\\/\\\\/g; push @ppd_chunks, sprintf <<'PPD_XML', $bin_location; PPD_XML my @ppd_cmds = $self->stashmeta(join('', @ppd_chunks), $ppd_file); return sprintf <<'PPD_OUT', join "\n\t", @ppd_cmds; # Creates a PPD (Perl Package Description) for a binary distribution. ppd : %s PPD_OUT } =item prefixify $MM->prefixify($var, $prefix, $new_prefix, $default); Using either $MM->{uc $var} || $Config{lc $var}, it will attempt to replace it's $prefix with a $new_prefix. Should the $prefix fail to match I a PREFIX was given as an argument to WriteMakefile() it will set it to the $new_prefix + $default. This is for systems whose file layouts don't neatly fit into our ideas of prefixes. This is for heuristics which attempt to create directory structures that mirror those of the installed perl. For example: $MM->prefixify('installman1dir', '/usr', '/home/foo', 'man/man1'); this will attempt to remove '/usr' from the front of the $MM->{INSTALLMAN1DIR} path (initializing it to $Config{installman1dir} if necessary) and replace it with '/home/foo'. If this fails it will simply use '/home/foo/man/man1'. =cut sub prefixify { my($self,$var,$sprefix,$rprefix,$default) = @_; my $path = $self->{uc $var} || $Config_Override{lc $var} || $Config{lc $var} || ''; $rprefix .= '/' if $sprefix =~ m|/$|; warn " prefixify $var => $path\n" if $Verbose >= 2; warn " from $sprefix to $rprefix\n" if $Verbose >= 2; if( $self->{ARGS}{PREFIX} && $path !~ s{^\Q$sprefix\E\b}{$rprefix}s ) { warn " cannot prefix, using default.\n" if $Verbose >= 2; warn " no default!\n" if !$default && $Verbose >= 2; $path = $self->catdir($rprefix, $default) if $default; } print " now $path\n" if $Verbose >= 2; return $self->{uc $var} = $path; } =item processPL (o) Defines targets to run *.PL files. =cut sub processPL { my $self = shift; my $pl_files = $self->{PL_FILES}; return "" unless $pl_files; my $m = ''; foreach my $plfile (sort keys %$pl_files) { my $targets = $pl_files->{$plfile}; my $list = ref($targets) eq 'HASH' ? [ sort keys %$targets ] : ref($targets) eq 'ARRAY' ? $pl_files->{$plfile} : [$pl_files->{$plfile}]; foreach my $target (@$list) { if( $Is{VMS} ) { $plfile = vmsify($self->eliminate_macros($plfile)); $target = vmsify($self->eliminate_macros($target)); } # Normally a .PL file runs AFTER pm_to_blib so it can have # blib in its @INC and load the just built modules. BUT if # the generated module is something in $(TO_INST_PM) which # pm_to_blib depends on then it can't depend on pm_to_blib # else we have a dependency loop. my $pm_dep; my $perlrun; if( defined $self->{PM}{$target} ) { $pm_dep = ''; $perlrun = 'PERLRUN'; } else { $pm_dep = 'pm_to_blib'; $perlrun = 'PERLRUNINST'; } my $extra_inputs = ''; if( ref($targets) eq 'HASH' ) { my $inputs = ref($targets->{$target}) ? $targets->{$target} : [$targets->{$target}]; for my $input (@$inputs) { if( $Is{VMS} ) { $input = vmsify($self->eliminate_macros($input)); } $extra_inputs .= ' '.$input; } } $m .= < in command line arguments. Doesn't handle recursive Makefile C<$(...)> constructs, but handles simple ones. =cut sub quote_paren { my $arg = shift; $arg =~ s{\$\((.+?)\)}{\$\\\\($1\\\\)}g; # protect $(...) $arg =~ s{(?replace_manpage_separator($file_path); Takes the name of a package, which may be a nested package, in the form 'Foo/Bar.pm' and replaces the slash with C<::> or something else safe for a man page file name. Returns the replacement. =cut sub replace_manpage_separator { my($self,$man) = @_; $man =~ s,/+,::,g; return $man; } =item cd =cut sub cd { my($self, $dir, @cmds) = @_; # No leading tab and no trailing newline makes for easier embedding my $make_frag = join "\n\t", map { "cd $dir && $_" } @cmds; return $make_frag; } =item oneliner =cut sub oneliner { my($self, $cmd, $switches) = @_; $switches = [] unless defined $switches; # Strip leading and trailing newlines $cmd =~ s{^\n+}{}; $cmd =~ s{\n+$}{}; my @cmds = split /\n/, $cmd; $cmd = join " \n\t -e ", map $self->quote_literal($_), @cmds; $cmd = $self->escape_newlines($cmd); $switches = join ' ', @$switches; return qq{\$(ABSPERLRUN) $switches -e $cmd --}; } =item quote_literal Quotes macro literal value suitable for being used on a command line so that when expanded by make, will be received by command as given to this method: my $quoted = $mm->quote_literal(q{it isn't}); # returns: # 'it isn'\''t' print MAKEFILE "target:\n\techo $quoted\n"; # when run "make target", will output: # it isn't =cut sub quote_literal { my($self, $text, $opts) = @_; $opts->{allow_variables} = 1 unless defined $opts->{allow_variables}; # Quote single quotes $text =~ s{'}{'\\''}g; $text = $opts->{allow_variables} ? $self->escape_dollarsigns($text) : $self->escape_all_dollarsigns($text); return "'$text'"; } =item escape_newlines =cut sub escape_newlines { my($self, $text) = @_; $text =~ s{\n}{\\\n}g; return $text; } =item max_exec_len Using L::ARG_MAX. Otherwise falling back to 4096. =cut sub max_exec_len { my $self = shift; if (!defined $self->{_MAX_EXEC_LEN}) { if (my $arg_max = eval { require POSIX; &POSIX::ARG_MAX }) { $self->{_MAX_EXEC_LEN} = $arg_max; } else { # POSIX minimum exec size $self->{_MAX_EXEC_LEN} = 4096; } } return $self->{_MAX_EXEC_LEN}; } =item static (o) Defines the static target. =cut sub static { # --- Static Loading Sections --- my($self) = shift; ' ## $(INST_PM) has been moved to the all: target. ## It remains here for awhile to allow for old usage: "make static" static :: $(FIRST_MAKEFILE) $(INST_STATIC) $(NOECHO) $(NOOP) '; } sub static_lib { my($self) = @_; return '' unless $self->has_link_code; my(@m); my @libs; if ($self->{XSMULTI}) { for my $ext ($self->_xs_list_basenames) { my ($v, $d, $f) = File::Spec->splitpath($ext); my @d = File::Spec->splitdir($d); shift @d if $d[0] eq 'lib'; my $instdir = $self->catdir('$(INST_ARCHLIB)', 'auto', @d, $f); my $instfile = $self->catfile($instdir, "$f\$(LIB_EXT)"); my $objfile = "$ext\$(OBJ_EXT)"; push @libs, [ $objfile, $instfile, $instdir ]; } } else { @libs = ([ qw($(OBJECT) $(INST_STATIC) $(INST_ARCHAUTODIR)) ]); } push @m, map { $self->xs_make_static_lib(@$_); } @libs; join "\n", @m; } =item xs_make_static_lib Defines the recipes for the C section. =cut sub xs_make_static_lib { my ($self, $from, $to, $todir) = @_; my @m = sprintf '%s: %s $(MYEXTLIB) %s$(DFSEP).exists'."\n", $to, $from, $todir; push @m, "\t\$(RM_F) \"\$\@\"\n"; push @m, $self->static_lib_fixtures; push @m, $self->static_lib_pure_cmd($from); push @m, "\t\$(CHMOD) \$(PERM_RWX) \$\@\n"; push @m, $self->static_lib_closures($todir); join '', @m; } =item static_lib_closures Records C<$(EXTRALIBS)> in F and F<$(PERL_SRC)/ext.libs>. =cut sub static_lib_closures { my ($self, $todir) = @_; my @m = sprintf <<'MAKE_FRAG', $todir; $(NOECHO) $(ECHO) "$(EXTRALIBS)" > %s$(DFSEP)extralibs.ld MAKE_FRAG # Old mechanism - still available: push @m, <<'MAKE_FRAG' if $self->{PERL_SRC} && $self->{EXTRALIBS}; $(NOECHO) $(ECHO) "$(EXTRALIBS)" >> $(PERL_SRC)$(DFSEP)ext.libs MAKE_FRAG @m; } =item static_lib_fixtures Handles copying C<$(MYEXTLIB)> as starter for final static library that then gets added to. =cut sub static_lib_fixtures { my ($self) = @_; # If this extension has its own library (eg SDBM_File) # then copy that to $(INST_STATIC) and add $(OBJECT) into it. return unless $self->{MYEXTLIB}; "\t\$(CP) \$(MYEXTLIB) \"\$\@\"\n"; } =item static_lib_pure_cmd Defines how to run the archive utility. =cut sub static_lib_pure_cmd { my ($self, $from) = @_; my $ar; if (exists $self->{FULL_AR} && -x $self->{FULL_AR}) { # Prefer the absolute pathed ar if available so that PATH # doesn't confuse us. Perl itself is built with the full_ar. $ar = 'FULL_AR'; } else { $ar = 'AR'; } sprintf <<'MAKE_FRAG', $ar, $from; $(%s) $(AR_STATIC_ARGS) "$@" %s $(RANLIB) "$@" MAKE_FRAG } =item staticmake (o) Calls makeaperl. =cut sub staticmake { my($self, %attribs) = @_; my(@static); my(@searchdirs)=($self->{PERL_ARCHLIB}, $self->{SITEARCHEXP}, $self->{INST_ARCHLIB}); # And as it's not yet built, we add the current extension # but only if it has some C code (or XS code, which implies C code) if (@{$self->{C}}) { @static = $self->catfile($self->{INST_ARCHLIB}, "auto", $self->{FULLEXT}, "$self->{BASEEXT}$self->{LIB_EXT}" ); } # Either we determine now, which libraries we will produce in the # subdirectories or we do it at runtime of the make. # We could ask all subdir objects, but I cannot imagine, why it # would be necessary. # Instead we determine all libraries for the new perl at # runtime. my(@perlinc) = ($self->{INST_ARCHLIB}, $self->{INST_LIB}, $self->{PERL_ARCHLIB}, $self->{PERL_LIB}); $self->makeaperl(MAKE => $self->{MAKEFILE}, DIRS => \@searchdirs, STAT => \@static, INCL => \@perlinc, TARGET => $self->{MAP_TARGET}, TMP => "", LIBPERL => $self->{LIBPERL_A} ); } =item subdir_x (o) Helper subroutine for subdirs =cut sub subdir_x { my($self, $subdir) = @_; my $subdir_cmd = $self->cd($subdir, '$(MAKE) $(USEMAKEFILE) $(FIRST_MAKEFILE) all $(PASTHRU)' ); return sprintf <<'EOT', $subdir_cmd; subdirs :: $(NOECHO) %s EOT } =item subdirs (o) Defines targets to process subdirectories. =cut sub subdirs { # --- Sub-directory Sections --- my($self) = shift; my(@m); # This method provides a mechanism to automatically deal with # subdirectories containing further Makefile.PL scripts. # It calls the subdir_x() method for each subdirectory. foreach my $dir (@{$self->{DIR}}){ push @m, $self->subdir_x($dir); #### print "Including $dir subdirectory\n"; } if (@m){ unshift @m, <<'EOF'; # The default clean, realclean and test targets in this Makefile # have automatically been given entries for each subdir. EOF } else { push(@m, "\n# none") } join('',@m); } =item test (o) Defines the test targets. =cut sub test { my($self, %attribs) = @_; my $tests = $attribs{TESTS} || ''; if (!$tests && -d 't' && defined $attribs{RECURSIVE_TEST_FILES}) { $tests = $self->find_tests_recursive; } elsif (!$tests && -d 't') { $tests = $self->find_tests; } # have to do this because nmake is broken $tests =~ s!/!\\!g if $self->is_make_type('nmake'); # note: 'test.pl' name is also hardcoded in init_dirscan() my @m; my $default_testtype = $Config{usedl} ? 'dynamic' : 'static'; push @m, <{SKIPHASH}{$_}, $linktype, "pure_all"; # no depend on a linktype if SKIPped push @m, "subdirs-test_$linktype :: $directdeps\n"; foreach my $dir (@{ $self->{DIR} }) { my $test = $self->cd($dir, "\$(MAKE) test_$linktype \$(PASTHRU)"); push @m, "\t\$(NOECHO) $test\n"; } push @m, "\n"; if ($tests or -f "test.pl") { for my $testspec ([ '', '' ], [ 'db', ' $(TESTDB_SW)' ]) { my ($db, $switch) = @$testspec; my ($command, $deps); # if testdb, build all but don't test all $deps = $db eq 'db' ? $directdeps : "subdirs-test_$linktype"; if ($linktype eq 'static' and $self->needs_linking) { my $target = File::Spec->rel2abs('$(MAP_TARGET)'); $command = qq{"$target" \$(MAP_PERLINC)}; $deps .= ' $(MAP_TARGET)'; } else { $command = '$(FULLPERLRUN)' . $switch; } push @m, "test${db}_$linktype :: $deps\n"; if ($db eq 'db') { push @m, $self->test_via_script($command, '$(TEST_FILE)') } else { push @m, $self->test_via_script($command, '$(TEST_FILE)') if -f "test.pl"; push @m, $self->test_via_harness($command, '$(TEST_FILES)') if $tests; } push @m, "\n"; } } else { push @m, _sprintf562 <<'EOF', $linktype; testdb_%1$s test_%1$s :: subdirs-test_%1$s $(NOECHO) $(ECHO) 'No tests defined for $(NAME) extension.' EOF } } join "", @m; } =item test_via_harness (override) For some reason which I forget, Unix machines like to have PERL_DL_NONLAZY set for tests. =cut sub test_via_harness { my($self, $perl, $tests) = @_; return $self->SUPER::test_via_harness("PERL_DL_NONLAZY=1 $perl", $tests); } =item test_via_script (override) Again, the PERL_DL_NONLAZY thing. =cut sub test_via_script { my($self, $perl, $script) = @_; return $self->SUPER::test_via_script("PERL_DL_NONLAZY=1 $perl", $script); } =item tool_xsubpp (o) Determines typemaps, xsubpp version, prototype behaviour. =cut sub tool_xsubpp { my($self) = shift; return "" unless $self->needs_linking; my $xsdir; my @xsubpp_dirs = @INC; # Make sure we pick up the new xsubpp if we're building perl. unshift @xsubpp_dirs, $self->{PERL_LIB} if $self->{PERL_CORE}; my $foundxsubpp = 0; foreach my $dir (@xsubpp_dirs) { $xsdir = $self->catdir($dir, 'ExtUtils'); if( -r $self->catfile($xsdir, "xsubpp") ) { $foundxsubpp = 1; last; } } die "ExtUtils::MM_Unix::tool_xsubpp : Can't find xsubpp" if !$foundxsubpp; my $tmdir = $self->catdir($self->{PERL_LIB},"ExtUtils"); my(@tmdeps) = $self->catfile($tmdir,'typemap'); if( $self->{TYPEMAPS} ){ foreach my $typemap (@{$self->{TYPEMAPS}}){ if( ! -f $typemap ) { warn "Typemap $typemap not found.\n"; } else { $typemap = vmsify($typemap) if $Is{VMS}; push(@tmdeps, $typemap); } } } push(@tmdeps, "typemap") if -f "typemap"; # absolutised because with deep-located typemaps, eg "lib/XS/typemap", # if xsubpp is called from top level with # $(XSUBPP) ... -typemap "lib/XS/typemap" "lib/XS/Test.xs" # it says: # Can't find lib/XS/type map in (fulldir)/lib/XS # because ExtUtils::ParseXS::process_file chdir's to .xs file's # location. This is the only way to get all specified typemaps used, # wherever located. my @tmargs = map { '-typemap '.$self->quote_literal(File::Spec->rel2abs($_)) } @tmdeps; $_ = $self->quote_dep($_) for @tmdeps; if( exists $self->{XSOPT} ){ unshift( @tmargs, $self->{XSOPT} ); } if ($Is{VMS} && $Config{'ldflags'} && $Config{'ldflags'} =~ m!/Debug!i && (!exists($self->{XSOPT}) || $self->{XSOPT} !~ /linenumbers/) ) { unshift(@tmargs,'-nolinenumbers'); } $self->{XSPROTOARG} = "" unless defined $self->{XSPROTOARG}; my $xsdirdep = $self->quote_dep($xsdir); # -dep for use when dependency not command return qq{ XSUBPPDIR = $xsdir XSUBPP = "\$(XSUBPPDIR)\$(DFSEP)xsubpp" XSUBPPRUN = \$(PERLRUN) \$(XSUBPP) XSPROTOARG = $self->{XSPROTOARG} XSUBPPDEPS = @tmdeps $xsdirdep\$(DFSEP)xsubpp XSUBPPARGS = @tmargs XSUBPP_EXTRA_ARGS = }; } =item all_target Build man pages, too =cut sub all_target { my $self = shift; return <<'MAKE_EXT'; all :: pure_all manifypods $(NOECHO) $(NOOP) MAKE_EXT } =item top_targets (o) Defines the targets all, subdirs, config, and O_FILES =cut sub top_targets { # --- Target Sections --- my($self) = shift; my(@m); push @m, $self->all_target, "\n" unless $self->{SKIPHASH}{'all'}; push @m, sprintf <<'EOF'; pure_all :: config pm_to_blib subdirs linkext $(NOECHO) $(NOOP) subdirs :: $(MYEXTLIB) $(NOECHO) $(NOOP) config :: $(FIRST_MAKEFILE) blibdirs $(NOECHO) $(NOOP) EOF push @m, ' $(O_FILES) : $(H_FILES) ' if @{$self->{O_FILES} || []} && @{$self->{H} || []}; push @m, q{ help : perldoc ExtUtils::MakeMaker }; join('',@m); } =item writedoc Obsolete, deprecated method. Not used since Version 5.21. =cut sub writedoc { # --- perllocal.pod section --- my($self,$what,$name,@attribs)=@_; my $time = gmtime($ENV{SOURCE_DATE_EPOCH} || time); print "=head2 $time: $what C<$name>\n\n=over 4\n\n=item *\n\n"; print join "\n\n=item *\n\n", map("C<$_>",@attribs); print "\n\n=back\n\n"; } =item xs_c (o) Defines the suffix rules to compile XS files to C. =cut sub xs_c { my($self) = shift; return '' unless $self->needs_linking(); ' .xs.c: $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $(XSUBPP_EXTRA_ARGS) $*.xs > $*.xsc $(MV) $*.xsc $*.c '; } =item xs_cpp (o) Defines the suffix rules to compile XS files to C++. =cut sub xs_cpp { my($self) = shift; return '' unless $self->needs_linking(); ' .xs.cpp: $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $*.xs > $*.xsc $(MV) $*.xsc $*.cpp '; } =item xs_o (o) Defines suffix rules to go from XS to object files directly. This was originally only intended for broken make implementations, but is now necessary for per-XS file under C, since each XS file might have an individual C<$(VERSION)>. =cut sub xs_o { my ($self) = @_; return '' unless $self->needs_linking(); my $m_o = $self->{XSMULTI} ? $self->xs_obj_opt('$*$(OBJ_EXT)') : ''; my $dbgout = $self->dbgoutflag; $dbgout = $dbgout ? "$dbgout " : ''; my $frag = ''; # dmake makes noise about ambiguous rule $frag .= sprintf <<'EOF', $dbgout, $m_o unless $self->is_make_type('dmake'); .xs$(OBJ_EXT) : $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $*.xs > $*.xsc $(MV) $*.xsc $*.c $(CCCMD) $(CCCDLFLAGS) "-I$(PERL_INC)" $(PASTHRU_DEFINE) $(DEFINE) %s$*.c %s EOF if ($self->{XSMULTI}) { for my $ext ($self->_xs_list_basenames) { my $pmfile = "$ext.pm"; croak "$ext.xs has no matching $pmfile: $!" unless -f $pmfile; my $version = $self->parse_version($pmfile); my $cccmd = $self->{CONST_CCCMD}; $cccmd =~ s/^\s*CCCMD\s*=\s*//; $cccmd =~ s/\$\(DEFINE_VERSION\)/-DVERSION=\\"$version\\"/; $cccmd =~ s/\$\(XS_DEFINE_VERSION\)/-DXS_VERSION=\\"$version\\"/; $self->_xsbuild_replace_macro($cccmd, 'xs', $ext, 'INC'); my $define = '$(DEFINE)'; $self->_xsbuild_replace_macro($define, 'xs', $ext, 'DEFINE'); # 1 2 3 4 5 $frag .= _sprintf562 <<'EOF', $ext, $cccmd, $m_o, $define, $dbgout; %1$s$(OBJ_EXT): %1$s.xs $(XSUBPPRUN) $(XSPROTOARG) $(XSUBPPARGS) $*.xs > $*.xsc $(MV) $*.xsc $*.c %2$s $(CCCDLFLAGS) "-I$(PERL_INC)" $(PASTHRU_DEFINE) %4$s %5$s$*.c %3$s EOF } } $frag =~ s/"-I(\$\(PERL_INC\))"/-iwithsysroot "$1"/sg if $Is{ApplCor}; $frag; } # param gets modified sub _xsbuild_replace_macro { my ($self, undef, $xstype, $ext, $varname) = @_; my $value = $self->_xsbuild_value($xstype, $ext, $varname); return unless defined $value; $_[1] =~ s/\$\($varname\)/$value/; } sub _xsbuild_value { my ($self, $xstype, $ext, $varname) = @_; return $self->{XSBUILD}{$xstype}{$ext}{$varname} if $self->{XSBUILD}{$xstype}{$ext}{$varname}; return $self->{XSBUILD}{$xstype}{all}{$varname} if $self->{XSBUILD}{$xstype}{all}{$varname}; (); } 1; =back =head1 SEE ALSO L =cut __END__ PK!b?o^++perl5/ExtUtils/Mksymlists.pmnuÏÃ6Ç$package ExtUtils::Mksymlists; use 5.006; use strict qw[ subs refs ]; # no strict 'vars'; # until filehandles are exempted use warnings; use Carp; use Exporter; use Config; our @ISA = qw(Exporter); our @EXPORT = qw(&Mksymlists); our $VERSION = '7.50'; $VERSION =~ tr/_//d; sub Mksymlists { my(%spec) = @_; my($osname) = $^O; croak("Insufficient information specified to Mksymlists") unless ( $spec{NAME} or ($spec{FILE} and ($spec{DL_FUNCS} or $spec{FUNCLIST})) ); $spec{DL_VARS} = [] unless $spec{DL_VARS}; ($spec{FILE} = $spec{NAME}) =~ s/.*::// unless $spec{FILE}; $spec{FUNCLIST} = [] unless $spec{FUNCLIST}; $spec{DL_FUNCS} = { $spec{NAME} => [] } unless ( ($spec{DL_FUNCS} and keys %{$spec{DL_FUNCS}}) or @{$spec{FUNCLIST}}); if (defined $spec{DL_FUNCS}) { foreach my $package (sort keys %{$spec{DL_FUNCS}}) { my($packprefix,$bootseen); ($packprefix = $package) =~ s/\W/_/g; foreach my $sym (@{$spec{DL_FUNCS}->{$package}}) { if ($sym =~ /^boot_/) { push(@{$spec{FUNCLIST}},$sym); $bootseen++; } else { push(@{$spec{FUNCLIST}},"XS_${packprefix}_$sym"); } } push(@{$spec{FUNCLIST}},"boot_$packprefix") unless $bootseen; } } # We'll need this if we ever add any OS which uses mod2fname # not as pseudo-builtin. # require DynaLoader; if (defined &DynaLoader::mod2fname and not $spec{DLBASE}) { $spec{DLBASE} = DynaLoader::mod2fname([ split(/::/,$spec{NAME}) ]); } if ($osname eq 'aix') { _write_aix(\%spec); } elsif ($osname eq 'MacOS'){ _write_aix(\%spec) } elsif ($osname eq 'VMS') { _write_vms(\%spec) } elsif ($osname eq 'os2') { _write_os2(\%spec) } elsif ($osname eq 'MSWin32') { _write_win32(\%spec) } else { croak("Don't know how to create linker option file for $osname\n"); } } sub _write_aix { my($data) = @_; rename "$data->{FILE}.exp", "$data->{FILE}.exp_old"; open( my $exp, ">", "$data->{FILE}.exp") or croak("Can't create $data->{FILE}.exp: $!\n"); print $exp join("\n",@{$data->{DL_VARS}}, "\n") if @{$data->{DL_VARS}}; print $exp join("\n",@{$data->{FUNCLIST}}, "\n") if @{$data->{FUNCLIST}}; close $exp; } sub _write_os2 { my($data) = @_; require Config; my $threaded = ($Config::Config{archname} =~ /-thread/ ? " threaded" : ""); if (not $data->{DLBASE}) { ($data->{DLBASE} = $data->{NAME}) =~ s/.*:://; $data->{DLBASE} = substr($data->{DLBASE},0,7) . '_'; } my $distname = $data->{DISTNAME} || $data->{NAME}; $distname = "Distribution $distname"; my $patchlevel = " pl$Config{perl_patchlevel}" || ''; my $comment = sprintf "Perl (v%s%s%s) module %s", $Config::Config{version}, $threaded, $patchlevel, $data->{NAME}; chomp $comment; if ($data->{INSTALLDIRS} and $data->{INSTALLDIRS} eq 'perl') { $distname = 'perl5-porters@perl.org'; $comment = "Core $comment"; } $comment = "$comment (Perl-config: $Config{config_args})"; $comment = substr($comment, 0, 200) . "...)" if length $comment > 203; rename "$data->{FILE}.def", "$data->{FILE}_def.old"; open(my $def, ">", "$data->{FILE}.def") or croak("Can't create $data->{FILE}.def: $!\n"); print $def "LIBRARY '$data->{DLBASE}' INITINSTANCE TERMINSTANCE\n"; print $def "DESCRIPTION '\@#$distname:$data->{VERSION}#\@ $comment'\n"; print $def "CODE LOADONCALL\n"; print $def "DATA LOADONCALL NONSHARED MULTIPLE\n"; print $def "EXPORTS\n "; print $def join("\n ",@{$data->{DL_VARS}}, "\n") if @{$data->{DL_VARS}}; print $def join("\n ",@{$data->{FUNCLIST}}, "\n") if @{$data->{FUNCLIST}}; _print_imports($def, $data); close $def; } sub _print_imports { my ($def, $data)= @_; my $imports= $data->{IMPORTS} or return; if ( keys %$imports ) { print $def "IMPORTS\n"; foreach my $name (sort keys %$imports) { print $def " $name=$imports->{$name}\n"; } } } sub _write_win32 { my($data) = @_; require Config; if (not $data->{DLBASE}) { ($data->{DLBASE} = $data->{NAME}) =~ s/.*:://; $data->{DLBASE} = substr($data->{DLBASE},0,7) . '_'; } rename "$data->{FILE}.def", "$data->{FILE}_def.old"; open( my $def, ">", "$data->{FILE}.def" ) or croak("Can't create $data->{FILE}.def: $!\n"); # put library name in quotes (it could be a keyword, like 'Alias') if ($Config::Config{'cc'} !~ /\bgcc/i) { print $def "LIBRARY \"$data->{DLBASE}\"\n"; } print $def "EXPORTS\n "; my @syms; # Export public symbols both with and without underscores to # ensure compatibility between DLLs from Borland C and Visual C # NOTE: DynaLoader itself only uses the names without underscores, # so this is only to cover the case when the extension DLL may be # linked to directly from C. GSAR 97-07-10 #bcc dropped in 5.16, so dont create useless extra symbols for export table unless("$]" >= 5.016) { if ($Config::Config{'cc'} =~ /^bcc/i) { push @syms, "_$_", "$_ = _$_" for (@{$data->{DL_VARS}}, @{$data->{FUNCLIST}}); } else { push @syms, "$_", "_$_ = $_" for (@{$data->{DL_VARS}}, @{$data->{FUNCLIST}}); } } else { push @syms, "$_" for (@{$data->{DL_VARS}}, @{$data->{FUNCLIST}}); } print $def join("\n ",@syms, "\n") if @syms; _print_imports($def, $data); close $def; } sub _write_vms { my($data) = @_; require Config; # a reminder for once we do $^O require ExtUtils::XSSymSet; my($isvax) = $Config::Config{'archname'} =~ /VAX/i; my($set) = new ExtUtils::XSSymSet; rename "$data->{FILE}.opt", "$data->{FILE}.opt_old"; open(my $opt,">", "$data->{FILE}.opt") or croak("Can't create $data->{FILE}.opt: $!\n"); # Options file declaring universal symbols # Used when linking shareable image for dynamic extension, # or when linking PerlShr into which we've added this package # as a static extension # We don't do anything to preserve order, so we won't relax # the GSMATCH criteria for a dynamic extension print $opt "case_sensitive=yes\n" if $Config::Config{d_vms_case_sensitive_symbols}; foreach my $sym (@{$data->{FUNCLIST}}) { my $safe = $set->addsym($sym); if ($isvax) { print $opt "UNIVERSAL=$safe\n" } else { print $opt "SYMBOL_VECTOR=($safe=PROCEDURE)\n"; } } foreach my $sym (@{$data->{DL_VARS}}) { my $safe = $set->addsym($sym); print $opt "PSECT_ATTR=${sym},PIC,OVR,RD,NOEXE,WRT,NOSHR\n"; if ($isvax) { print $opt "UNIVERSAL=$safe\n" } else { print $opt "SYMBOL_VECTOR=($safe=DATA)\n"; } } close $opt; } 1; __END__ =head1 NAME ExtUtils::Mksymlists - write linker options files for dynamic extension =head1 SYNOPSIS use ExtUtils::Mksymlists; Mksymlists( NAME => $name , DL_VARS => [ $var1, $var2, $var3 ], DL_FUNCS => { $pkg1 => [ $func1, $func2 ], $pkg2 => [ $func3 ] ); =head1 DESCRIPTION C produces files used by the linker under some OSs during the creation of shared libraries for dynamic extensions. It is normally called from a MakeMaker-generated Makefile when the extension is built. The linker option file is generated by calling the function C, which is exported by default from C. It takes one argument, a list of key-value pairs, in which the following keys are recognized: =over 4 =item DLBASE This item specifies the name by which the linker knows the extension, which may be different from the name of the extension itself (for instance, some linkers add an '_' to the name of the extension). If it is not specified, it is derived from the NAME attribute. It is presently used only by OS2 and Win32. =item DL_FUNCS This is identical to the DL_FUNCS attribute available via MakeMaker, from which it is usually taken. Its value is a reference to an associative array, in which each key is the name of a package, and each value is an a reference to an array of function names which should be exported by the extension. For instance, one might say C { Homer::Iliad =E [ qw(trojans greeks) ], Homer::Odyssey =E [ qw(travellers family suitors) ] }>. The function names should be identical to those in the XSUB code; C will alter the names written to the linker option file to match the changes made by F. In addition, if none of the functions in a list begin with the string B, C will add a bootstrap function for that package, just as xsubpp does. (If a BpkgE> function is present in the list, it is passed through unchanged.) If DL_FUNCS is not specified, it defaults to the bootstrap function for the extension specified in NAME. =item DL_VARS This is identical to the DL_VARS attribute available via MakeMaker, and, like DL_FUNCS, it is usually specified via MakeMaker. Its value is a reference to an array of variable names which should be exported by the extension. =item FILE This key can be used to specify the name of the linker option file (minus the OS-specific extension), if for some reason you do not want to use the default value, which is the last word of the NAME attribute (I for C, FILE defaults to C). =item FUNCLIST This provides an alternate means to specify function names to be exported from the extension. Its value is a reference to an array of function names to be exported by the extension. These names are passed through unaltered to the linker options file. Specifying a value for the FUNCLIST attribute suppresses automatic generation of the bootstrap function for the package. To still create the bootstrap name you have to specify the package name in the DL_FUNCS hash: Mksymlists( NAME => $name , FUNCLIST => [ $func1, $func2 ], DL_FUNCS => { $pkg => [] } ); =item IMPORTS This attribute is used to specify names to be imported into the extension. It is currently only used by OS/2 and Win32. =item NAME This gives the name of the extension (I C) for which the linker option file will be produced. =back When calling C, one should always specify the NAME attribute. In most cases, this is all that's necessary. In the case of unusual extensions, however, the other attributes can be used to provide additional information to the linker. =head1 AUTHOR Charles Bailey Ibailey@newman.upenn.eduE> =head1 REVISION Last revised 14-Feb-1996, for Perl 5.002. PK!áðºS  perl5/ExtUtils/MM_Win95.pmnuÏÃ6Ç$package ExtUtils::MM_Win95; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Win32; our @ISA = qw(ExtUtils::MM_Win32); use ExtUtils::MakeMaker::Config; =head1 NAME ExtUtils::MM_Win95 - method to customize MakeMaker for Win9X =head1 SYNOPSIS You should not be using this module directly. =head1 DESCRIPTION This is a subclass of L containing changes necessary to get MakeMaker playing nice with command.com and other Win9Xisms. =head2 Overridden methods Most of these make up for limitations in the Win9x/nmake command shell. =over 4 =item max_exec_len Win98 chokes on things like Encode if we set the max length to nmake's max of 2K. So we go for a more conservative value of 1K. =cut sub max_exec_len { my $self = shift; return $self->{_MAX_EXEC_LEN} ||= 1024; } =item os_flavor Win95 and Win98 and WinME are collectively Win9x and Win32 =cut sub os_flavor { my $self = shift; return ($self->SUPER::os_flavor, 'Win9x'); } =back =head1 AUTHOR Code originally inside MM_Win32. Original author unknown. Currently maintained by Michael G Schwern C. Send patches and ideas to C. See https://metacpan.org/release/ExtUtils-MakeMaker. =cut 1; PK!^›sXperl5/ExtUtils/MM_Cygwin.pmnuÏÃ6Ç$package ExtUtils::MM_Cygwin; use strict; use warnings; use ExtUtils::MakeMaker::Config; use File::Spec; require ExtUtils::MM_Unix; require ExtUtils::MM_Win32; our @ISA = qw( ExtUtils::MM_Unix ); our $VERSION = '7.50'; $VERSION =~ tr/_//d; =head1 NAME ExtUtils::MM_Cygwin - methods to override UN*X behaviour in ExtUtils::MakeMaker =head1 SYNOPSIS use ExtUtils::MM_Cygwin; # Done internally by ExtUtils::MakeMaker if needed =head1 DESCRIPTION See L for a documentation of the methods provided there. =over 4 =item os_flavor We're Unix and Cygwin. =cut sub os_flavor { return('Unix', 'Cygwin'); } =item cflags if configured for dynamic loading, triggers #define EXT in EXTERN.h =cut sub cflags { my($self,$libperl)=@_; return $self->{CFLAGS} if $self->{CFLAGS}; return '' unless $self->needs_linking(); my $base = $self->SUPER::cflags($libperl); foreach (split /\n/, $base) { /^(\S*)\s*=\s*(\S*)$/ and $self->{$1} = $2; }; $self->{CCFLAGS} .= " -DUSEIMPORTLIB" if ($Config{useshrplib} eq 'true'); return $self->{CFLAGS} = qq{ CCFLAGS = $self->{CCFLAGS} OPTIMIZE = $self->{OPTIMIZE} PERLTYPE = $self->{PERLTYPE} }; } =item replace_manpage_separator replaces strings '::' with '.' in MAN*POD man page names =cut sub replace_manpage_separator { my($self, $man) = @_; $man =~ s{/+}{.}g; return $man; } =item init_linker points to libperl.a =cut sub init_linker { my $self = shift; if ($Config{useshrplib} eq 'true') { my $libperl = '$(PERL_INC)' .'/'. "$Config{libperl}"; if( "$]" >= 5.006002 ) { $libperl =~ s/(dll\.)?a$/dll.a/; } $self->{PERL_ARCHIVE} = $libperl; } else { $self->{PERL_ARCHIVE} = '$(PERL_INC)' .'/'. ("$Config{libperl}" or "libperl.a"); } $self->{PERL_ARCHIVEDEP} ||= ''; $self->{PERL_ARCHIVE_AFTER} ||= ''; $self->{EXPORT_LIST} ||= ''; } sub init_others { my $self = shift; $self->SUPER::init_others; $self->{LDLOADLIBS} ||= $Config{perllibs}; return; } =item maybe_command Determine whether a file is native to Cygwin by checking whether it resides inside the Cygwin installation (using Windows paths). If so, use L to determine if it may be a command. Otherwise use the tests from L. =cut sub maybe_command { my ($self, $file) = @_; my $cygpath = Cygwin::posix_to_win_path('/', 1); my $filepath = Cygwin::posix_to_win_path($file, 1); return (substr($filepath,0,length($cygpath)) eq $cygpath) ? $self->SUPER::maybe_command($file) # Unix : ExtUtils::MM_Win32->maybe_command($file); # Win32 } =item dynamic_lib Use the default to produce the *.dll's. But for new archdir dll's use the same rebase address if the old exists. =cut sub dynamic_lib { my($self, %attribs) = @_; my $s = ExtUtils::MM_Unix::dynamic_lib($self, %attribs); return '' unless $s; return $s unless %{$self->{XS}}; # do an ephemeral rebase so the new DLL fits to the current rebase map $s .= "\t/bin/find \$\(INST_ARCHLIB\)/auto -xdev -name \\*.$self->{DLEXT} | /bin/rebase -sOT -" if (( $Config{myarchname} eq 'i686-cygwin' ) and not ( exists $ENV{CYGPORT_PACKAGE_VERSION} )); $s; } =item install Rebase dll's with the global rebase database after installation. =cut sub install { my($self, %attribs) = @_; my $s = ExtUtils::MM_Unix::install($self, %attribs); return '' unless $s; return $s unless %{$self->{XS}}; my $INSTALLDIRS = $self->{INSTALLDIRS}; my $INSTALLLIB = $self->{"INSTALL". ($INSTALLDIRS eq 'perl' ? 'ARCHLIB' : uc($INSTALLDIRS)."ARCH")}; my $dop = "\$\(DESTDIR\)$INSTALLLIB/auto/"; my $dll = "$dop/$self->{FULLEXT}/$self->{BASEEXT}.$self->{DLEXT}"; $s =~ s|^(pure_install :: pure_\$\(INSTALLDIRS\)_install\n\t)\$\(NOECHO\) \$\(NOOP\)\n|$1\$(CHMOD) \$(PERM_RWX) $dll\n\t/bin/find $dop -xdev -name \\*.$self->{DLEXT} \| /bin/rebase -sOT -\n|m if (( $Config{myarchname} eq 'i686-cygwin') and not ( exists $ENV{CYGPORT_PACKAGE_VERSION} )); $s; } =back =cut 1; PK!8éA®®)perl5/ExtUtils/MakeMaker/version/regex.pmnuÏÃ6Ç$#--------------------------------------------------------------------------# # This is a modified copy of version.pm 0.9909, bundled exclusively for # use by ExtUtils::Makemaker and its dependencies to bootstrap when # version.pm is not available. It should not be used by ordinary modules. #--------------------------------------------------------------------------# package ExtUtils::MakeMaker::version::regex; use strict; use warnings; use vars qw($VERSION $CLASS $STRICT $LAX); $VERSION = '7.50'; $VERSION =~ tr/_//d; #--------------------------------------------------------------------------# # Version regexp components #--------------------------------------------------------------------------# # Fraction part of a decimal version number. This is a common part of # both strict and lax decimal versions my $FRACTION_PART = qr/\.[0-9]+/; # First part of either decimal or dotted-decimal strict version number. # Unsigned integer with no leading zeroes (except for zero itself) to # avoid confusion with octal. my $STRICT_INTEGER_PART = qr/0|[1-9][0-9]*/; # First part of either decimal or dotted-decimal lax version number. # Unsigned integer, but allowing leading zeros. Always interpreted # as decimal. However, some forms of the resulting syntax give odd # results if used as ordinary Perl expressions, due to how perl treats # octals. E.g. # version->new("010" ) == 10 # version->new( 010 ) == 8 # version->new( 010.2) == 82 # "8" . "2" my $LAX_INTEGER_PART = qr/[0-9]+/; # Second and subsequent part of a strict dotted-decimal version number. # Leading zeroes are permitted, and the number is always decimal. # Limited to three digits to avoid overflow when converting to decimal # form and also avoid problematic style with excessive leading zeroes. my $STRICT_DOTTED_DECIMAL_PART = qr/\.[0-9]{1,3}/; # Second and subsequent part of a lax dotted-decimal version number. # Leading zeroes are permitted, and the number is always decimal. No # limit on the numerical value or number of digits, so there is the # possibility of overflow when converting to decimal form. my $LAX_DOTTED_DECIMAL_PART = qr/\.[0-9]+/; # Alpha suffix part of lax version number syntax. Acts like a # dotted-decimal part. my $LAX_ALPHA_PART = qr/_[0-9]+/; #--------------------------------------------------------------------------# # Strict version regexp definitions #--------------------------------------------------------------------------# # Strict decimal version number. my $STRICT_DECIMAL_VERSION = qr/ $STRICT_INTEGER_PART $FRACTION_PART? /x; # Strict dotted-decimal version number. Must have both leading "v" and # at least three parts, to avoid confusion with decimal syntax. my $STRICT_DOTTED_DECIMAL_VERSION = qr/ v $STRICT_INTEGER_PART $STRICT_DOTTED_DECIMAL_PART{2,} /x; # Complete strict version number syntax -- should generally be used # anchored: qr/ \A $STRICT \z /x $STRICT = qr/ $STRICT_DECIMAL_VERSION | $STRICT_DOTTED_DECIMAL_VERSION /x; #--------------------------------------------------------------------------# # Lax version regexp definitions #--------------------------------------------------------------------------# # Lax decimal version number. Just like the strict one except for # allowing an alpha suffix or allowing a leading or trailing # decimal-point my $LAX_DECIMAL_VERSION = qr/ $LAX_INTEGER_PART (?: \. | $FRACTION_PART $LAX_ALPHA_PART? )? | $FRACTION_PART $LAX_ALPHA_PART? /x; # Lax dotted-decimal version number. Distinguished by having either # leading "v" or at least three non-alpha parts. Alpha part is only # permitted if there are at least two non-alpha parts. Strangely # enough, without the leading "v", Perl takes .1.2 to mean v0.1.2, # so when there is no "v", the leading part is optional my $LAX_DOTTED_DECIMAL_VERSION = qr/ v $LAX_INTEGER_PART (?: $LAX_DOTTED_DECIMAL_PART+ $LAX_ALPHA_PART? )? | $LAX_INTEGER_PART? $LAX_DOTTED_DECIMAL_PART{2,} $LAX_ALPHA_PART? /x; # Complete lax version number syntax -- should generally be used # anchored: qr/ \A $LAX \z /x # # The string 'undef' is a special case to make for easier handling # of return values from ExtUtils::MM->parse_version $LAX = qr/ undef | $LAX_DECIMAL_VERSION | $LAX_DOTTED_DECIMAL_VERSION /x; #--------------------------------------------------------------------------# # Preloaded methods go here. sub is_strict { defined $_[0] && $_[0] =~ qr/ \A $STRICT \z /x } sub is_lax { defined $_[0] && $_[0] =~ qr/ \A $LAX \z /x } 1; PK!d+È~ZZ'perl5/ExtUtils/MakeMaker/version/vpp.pmnuÏÃ6Ç$#--------------------------------------------------------------------------# # This is a modified copy of version.pm 0.9909, bundled exclusively for # use by ExtUtils::Makemaker and its dependencies to bootstrap when # version.pm is not available. It should not be used by ordinary modules. #--------------------------------------------------------------------------# package ExtUtils::MakeMaker::charstar; # a little helper class to emulate C char* semantics in Perl # so that prescan_version can use the same code as in C use overload ( '""' => \&thischar, '0+' => \&thischar, '++' => \&increment, '--' => \&decrement, '+' => \&plus, '-' => \&minus, '*' => \&multiply, 'cmp' => \&cmp, '<=>' => \&spaceship, 'bool' => \&thischar, '=' => \&clone, ); sub new { my ($self, $string) = @_; my $class = ref($self) || $self; my $obj = { string => [split(//,$string)], current => 0, }; return bless $obj, $class; } sub thischar { my ($self) = @_; my $last = $#{$self->{string}}; my $curr = $self->{current}; if ($curr >= 0 && $curr <= $last) { return $self->{string}->[$curr]; } else { return ''; } } sub increment { my ($self) = @_; $self->{current}++; } sub decrement { my ($self) = @_; $self->{current}--; } sub plus { my ($self, $offset) = @_; my $rself = $self->clone; $rself->{current} += $offset; return $rself; } sub minus { my ($self, $offset) = @_; my $rself = $self->clone; $rself->{current} -= $offset; return $rself; } sub multiply { my ($left, $right, $swapped) = @_; my $char = $left->thischar(); return $char * $right; } sub spaceship { my ($left, $right, $swapped) = @_; unless (ref($right)) { # not an object already $right = $left->new($right); } return $left->{current} <=> $right->{current}; } sub cmp { my ($left, $right, $swapped) = @_; unless (ref($right)) { # not an object already if (length($right) == 1) { # comparing single character only return $left->thischar cmp $right; } $right = $left->new($right); } return $left->currstr cmp $right->currstr; } sub bool { my ($self) = @_; my $char = $self->thischar; return ($char ne ''); } sub clone { my ($left, $right, $swapped) = @_; $right = { string => [@{$left->{string}}], current => $left->{current}, }; return bless $right, ref($left); } sub currstr { my ($self, $s) = @_; my $curr = $self->{current}; my $last = $#{$self->{string}}; if (defined($s) && $s->{current} < $last) { $last = $s->{current}; } my $string = join('', @{$self->{string}}[$curr..$last]); return $string; } package ExtUtils::MakeMaker::version::vpp; use 5.006001; use strict; use warnings; use Config; use vars qw($VERSION $CLASS @ISA $LAX $STRICT); $VERSION = '7.50'; $VERSION =~ tr/_//d; $CLASS = 'ExtUtils::MakeMaker::version::vpp'; require ExtUtils::MakeMaker::version::regex; *ExtUtils::MakeMaker::version::vpp::is_strict = \&ExtUtils::MakeMaker::version::regex::is_strict; *ExtUtils::MakeMaker::version::vpp::is_lax = \&ExtUtils::MakeMaker::version::regex::is_lax; *LAX = \$ExtUtils::MakeMaker::version::regex::LAX; *STRICT = \$ExtUtils::MakeMaker::version::regex::STRICT; use overload ( '""' => \&stringify, '0+' => \&numify, 'cmp' => \&vcmp, '<=>' => \&vcmp, 'bool' => \&vbool, '+' => \&vnoop, '-' => \&vnoop, '*' => \&vnoop, '/' => \&vnoop, '+=' => \&vnoop, '-=' => \&vnoop, '*=' => \&vnoop, '/=' => \&vnoop, 'abs' => \&vnoop, ); eval "use warnings"; if ($@) { eval ' package warnings; sub enabled {return $^W;} 1; '; } sub import { no strict 'refs'; my ($class) = shift; # Set up any derived class unless ($class eq $CLASS) { no warnings; *{$class.'::declare'} = \&{$CLASS.'::declare'}; *{$class.'::qv'} = \&{$CLASS.'::qv'}; } my %args; if (@_) { # any remaining terms are arguments map { $args{$_} = 1 } @_ } else { # no parameters at all on use line %args = ( qv => 1, 'UNIVERSAL::VERSION' => 1, ); } my $callpkg = caller(); if (exists($args{declare})) { *{$callpkg.'::declare'} = sub {return $class->declare(shift) } unless defined(&{$callpkg.'::declare'}); } if (exists($args{qv})) { *{$callpkg.'::qv'} = sub {return $class->qv(shift) } unless defined(&{$callpkg.'::qv'}); } if (exists($args{'UNIVERSAL::VERSION'})) { no warnings; *UNIVERSAL::VERSION = \&{$CLASS.'::_VERSION'}; } if (exists($args{'VERSION'})) { *{$callpkg.'::VERSION'} = \&{$CLASS.'::_VERSION'}; } if (exists($args{'is_strict'})) { *{$callpkg.'::is_strict'} = \&{$CLASS.'::is_strict'} unless defined(&{$callpkg.'::is_strict'}); } if (exists($args{'is_lax'})) { *{$callpkg.'::is_lax'} = \&{$CLASS.'::is_lax'} unless defined(&{$callpkg.'::is_lax'}); } } my $VERSION_MAX = 0x7FFFFFFF; # implement prescan_version as closely to the C version as possible use constant TRUE => 1; use constant FALSE => 0; sub isDIGIT { my ($char) = shift->thischar(); return ($char =~ /\d/); } sub isALPHA { my ($char) = shift->thischar(); return ($char =~ /[a-zA-Z]/); } sub isSPACE { my ($char) = shift->thischar(); return ($char =~ /\s/); } sub BADVERSION { my ($s, $errstr, $error) = @_; if ($errstr) { $$errstr = $error; } return $s; } sub prescan_version { my ($s, $strict, $errstr, $sqv, $ssaw_decimal, $swidth, $salpha) = @_; my $qv = defined $sqv ? $$sqv : FALSE; my $saw_decimal = defined $ssaw_decimal ? $$ssaw_decimal : 0; my $width = defined $swidth ? $$swidth : 3; my $alpha = defined $salpha ? $$salpha : FALSE; my $d = $s; if ($qv && isDIGIT($d)) { goto dotted_decimal_version; } if ($d eq 'v') { # explicit v-string $d++; if (isDIGIT($d)) { $qv = TRUE; } else { # degenerate v-string # requires v1.2.3 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions require at least three parts)"); } dotted_decimal_version: if ($strict && $d eq '0' && isDIGIT($d+1)) { # no leading zeros allowed return BADVERSION($s,$errstr,"Invalid version format (no leading zeros)"); } while (isDIGIT($d)) { # integer part $d++; } if ($d eq '.') { $saw_decimal++; $d++; # decimal point } else { if ($strict) { # require v1.2.3 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions require at least three parts)"); } else { goto version_prescan_finish; } } { my $i = 0; my $j = 0; while (isDIGIT($d)) { # just keep reading $i++; while (isDIGIT($d)) { $d++; $j++; # maximum 3 digits between decimal if ($strict && $j > 3) { return BADVERSION($s,$errstr,"Invalid version format (maximum 3 digits between decimals)"); } } if ($d eq '_') { if ($strict) { return BADVERSION($s,$errstr,"Invalid version format (no underscores)"); } if ( $alpha ) { return BADVERSION($s,$errstr,"Invalid version format (multiple underscores)"); } $d++; $alpha = TRUE; } elsif ($d eq '.') { if ($alpha) { return BADVERSION($s,$errstr,"Invalid version format (underscores before decimal)"); } $saw_decimal++; $d++; } elsif (!isDIGIT($d)) { last; } $j = 0; } if ($strict && $i < 2) { # requires v1.2.3 return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions require at least three parts)"); } } } # end if dotted-decimal else { # decimal versions my $j = 0; # special $strict case for leading '.' or '0' if ($strict) { if ($d eq '.') { return BADVERSION($s,$errstr,"Invalid version format (0 before decimal required)"); } if ($d eq '0' && isDIGIT($d+1)) { return BADVERSION($s,$errstr,"Invalid version format (no leading zeros)"); } } # and we never support negative version numbers if ($d eq '-') { return BADVERSION($s,$errstr,"Invalid version format (negative version number)"); } # consume all of the integer part while (isDIGIT($d)) { $d++; } # look for a fractional part if ($d eq '.') { # we found it, so consume it $saw_decimal++; $d++; } elsif (!$d || $d eq ';' || isSPACE($d) || $d eq '}') { if ( $d == $s ) { # found nothing return BADVERSION($s,$errstr,"Invalid version format (version required)"); } # found just an integer goto version_prescan_finish; } elsif ( $d == $s ) { # didn't find either integer or period return BADVERSION($s,$errstr,"Invalid version format (non-numeric data)"); } elsif ($d eq '_') { # underscore can't come after integer part if ($strict) { return BADVERSION($s,$errstr,"Invalid version format (no underscores)"); } elsif (isDIGIT($d+1)) { return BADVERSION($s,$errstr,"Invalid version format (alpha without decimal)"); } else { return BADVERSION($s,$errstr,"Invalid version format (misplaced underscore)"); } } elsif ($d) { # anything else after integer part is just invalid data return BADVERSION($s,$errstr,"Invalid version format (non-numeric data)"); } # scan the fractional part after the decimal point if ($d && !isDIGIT($d) && ($strict || ! ($d eq ';' || isSPACE($d) || $d eq '}') )) { # $strict or lax-but-not-the-end return BADVERSION($s,$errstr,"Invalid version format (fractional part required)"); } while (isDIGIT($d)) { $d++; $j++; if ($d eq '.' && isDIGIT($d-1)) { if ($alpha) { return BADVERSION($s,$errstr,"Invalid version format (underscores before decimal)"); } if ($strict) { return BADVERSION($s,$errstr,"Invalid version format (dotted-decimal versions must begin with 'v')"); } $d = $s; # start all over again $qv = TRUE; goto dotted_decimal_version; } if ($d eq '_') { if ($strict) { return BADVERSION($s,$errstr,"Invalid version format (no underscores)"); } if ( $alpha ) { return BADVERSION($s,$errstr,"Invalid version format (multiple underscores)"); } if ( ! isDIGIT($d+1) ) { return BADVERSION($s,$errstr,"Invalid version format (misplaced underscore)"); } $width = $j; $d++; $alpha = TRUE; } } } version_prescan_finish: while (isSPACE($d)) { $d++; } if ($d && !isDIGIT($d) && (! ($d eq ';' || $d eq '}') )) { # trailing non-numeric data return BADVERSION($s,$errstr,"Invalid version format (non-numeric data)"); } if (defined $sqv) { $$sqv = $qv; } if (defined $swidth) { $$swidth = $width; } if (defined $ssaw_decimal) { $$ssaw_decimal = $saw_decimal; } if (defined $salpha) { $$salpha = $alpha; } return $d; } sub scan_version { my ($s, $rv, $qv) = @_; my $start; my $pos; my $last; my $errstr; my $saw_decimal = 0; my $width = 3; my $alpha = FALSE; my $vinf = FALSE; my @av; $s = new ExtUtils::MakeMaker::charstar $s; while (isSPACE($s)) { # leading whitespace is OK $s++; } $last = prescan_version($s, FALSE, \$errstr, \$qv, \$saw_decimal, \$width, \$alpha); if ($errstr) { # 'undef' is a special case and not an error if ( $s ne 'undef') { require Carp; Carp::croak($errstr); } } $start = $s; if ($s eq 'v') { $s++; } $pos = $s; if ( $qv ) { $$rv->{qv} = $qv; } if ( $alpha ) { $$rv->{alpha} = $alpha; } if ( !$qv && $width < 3 ) { $$rv->{width} = $width; } while (isDIGIT($pos)) { $pos++; } if (!isALPHA($pos)) { my $rev; for (;;) { $rev = 0; { # this is atoi() that delimits on underscores my $end = $pos; my $mult = 1; my $orev; # the following if() will only be true after the decimal # point of a version originally created with a bare # floating point number, i.e. not quoted in any way # if ( !$qv && $s > $start && $saw_decimal == 1 ) { $mult *= 100; while ( $s < $end ) { $orev = $rev; $rev += $s * $mult; $mult /= 10; if ( (abs($orev) > abs($rev)) || (abs($rev) > $VERSION_MAX )) { warn("Integer overflow in version %d", $VERSION_MAX); $s = $end - 1; $rev = $VERSION_MAX; $vinf = 1; } $s++; if ( $s eq '_' ) { $s++; } } } else { while (--$end >= $s) { $orev = $rev; $rev += $end * $mult; $mult *= 10; if ( (abs($orev) > abs($rev)) || (abs($rev) > $VERSION_MAX )) { warn("Integer overflow in version"); $end = $s - 1; $rev = $VERSION_MAX; $vinf = 1; } } } } # Append revision push @av, $rev; if ( $vinf ) { $s = $last; last; } elsif ( $pos eq '.' ) { $s = ++$pos; } elsif ( $pos eq '_' && isDIGIT($pos+1) ) { $s = ++$pos; } elsif ( $pos eq ',' && isDIGIT($pos+1) ) { $s = ++$pos; } elsif ( isDIGIT($pos) ) { $s = $pos; } else { $s = $pos; last; } if ( $qv ) { while ( isDIGIT($pos) ) { $pos++; } } else { my $digits = 0; while ( ( isDIGIT($pos) || $pos eq '_' ) && $digits < 3 ) { if ( $pos ne '_' ) { $digits++; } $pos++; } } } } if ( $qv ) { # quoted versions always get at least three terms my $len = $#av; # This for loop appears to trigger a compiler bug on OS X, as it # loops infinitely. Yes, len is negative. No, it makes no sense. # Compiler in question is: # gcc version 3.3 20030304 (Apple Computer, Inc. build 1640) # for ( len = 2 - len; len > 0; len-- ) # av_push(MUTABLE_AV(sv), newSViv(0)); # $len = 2 - $len; while ($len-- > 0) { push @av, 0; } } # need to save off the current version string for later if ( $vinf ) { $$rv->{original} = "v.Inf"; $$rv->{vinf} = 1; } elsif ( $s > $start ) { $$rv->{original} = $start->currstr($s); if ( $qv && $saw_decimal == 1 && $start ne 'v' ) { # need to insert a v to be consistent $$rv->{original} = 'v' . $$rv->{original}; } } else { $$rv->{original} = '0'; push(@av, 0); } # And finally, store the AV in the hash $$rv->{version} = \@av; # fix RT#19517 - special case 'undef' as string if ($s eq 'undef') { $s += 5; } return $s; } sub new { my $class = shift; unless (defined $class or $#_ > 1) { require Carp; Carp::croak('Usage: version::new(class, version)'); } my $self = bless ({}, ref ($class) || $class); my $qv = FALSE; if ( $#_ == 1 ) { # must be CVS-style $qv = TRUE; } my $value = pop; # always going to be the last element if ( ref($value) && eval('$value->isa("version")') ) { # Can copy the elements directly $self->{version} = [ @{$value->{version} } ]; $self->{qv} = 1 if $value->{qv}; $self->{alpha} = 1 if $value->{alpha}; $self->{original} = ''.$value->{original}; return $self; } if ( not defined $value or $value =~ /^undef$/ ) { # RT #19517 - special case for undef comparison # or someone forgot to pass a value push @{$self->{version}}, 0; $self->{original} = "0"; return ($self); } if (ref($value) =~ m/ARRAY|HASH/) { require Carp; Carp::croak("Invalid version format (non-numeric data)"); } $value = _un_vstring($value); if ($Config{d_setlocale} && eval { require POSIX } ) { require locale; my $currlocale = POSIX::setlocale(&POSIX::LC_ALL); # if the current locale uses commas for decimal points, we # just replace commas with decimal places, rather than changing # locales if ( POSIX::localeconv()->{decimal_point} eq ',' ) { $value =~ tr/,/./; } } # exponential notation if ( $value =~ /\d+.?\d*e[-+]?\d+/ ) { $value = sprintf("%.9f",$value); $value =~ s/(0+)$//; # trim trailing zeros } my $s = scan_version($value, \$self, $qv); if ($s) { # must be something left over warn("Version string '%s' contains invalid data; " ."ignoring: '%s'", $value, $s); } return ($self); } *parse = \&new; sub numify { my ($self) = @_; unless (_verify($self)) { require Carp; Carp::croak("Invalid version object"); } my $width = $self->{width} || 3; my $alpha = $self->{alpha} || ""; my $len = $#{$self->{version}}; my $digit = $self->{version}[0]; my $string = sprintf("%d.", $digit ); for ( my $i = 1 ; $i < $len ; $i++ ) { $digit = $self->{version}[$i]; if ( $width < 3 ) { my $denom = 10**(3-$width); my $quot = int($digit/$denom); my $rem = $digit - ($quot * $denom); $string .= sprintf("%0".$width."d_%d", $quot, $rem); } else { $string .= sprintf("%03d", $digit); } } if ( $len > 0 ) { $digit = $self->{version}[$len]; if ( $alpha && $width == 3 ) { $string .= "_"; } $string .= sprintf("%0".$width."d", $digit); } else # $len = 0 { $string .= sprintf("000"); } return $string; } sub normal { my ($self) = @_; unless (_verify($self)) { require Carp; Carp::croak("Invalid version object"); } my $alpha = $self->{alpha} || ""; my $len = $#{$self->{version}}; my $digit = $self->{version}[0]; my $string = sprintf("v%d", $digit ); for ( my $i = 1 ; $i < $len ; $i++ ) { $digit = $self->{version}[$i]; $string .= sprintf(".%d", $digit); } if ( $len > 0 ) { $digit = $self->{version}[$len]; if ( $alpha ) { $string .= sprintf("_%0d", $digit); } else { $string .= sprintf(".%0d", $digit); } } if ( $len <= 2 ) { for ( $len = 2 - $len; $len != 0; $len-- ) { $string .= sprintf(".%0d", 0); } } return $string; } sub stringify { my ($self) = @_; unless (_verify($self)) { require Carp; Carp::croak("Invalid version object"); } return exists $self->{original} ? $self->{original} : exists $self->{qv} ? $self->normal : $self->numify; } sub vcmp { require UNIVERSAL; my ($left,$right,$swap) = @_; my $class = ref($left); unless ( UNIVERSAL::isa($right, $class) ) { $right = $class->new($right); } if ( $swap ) { ($left, $right) = ($right, $left); } unless (_verify($left)) { require Carp; Carp::croak("Invalid version object"); } unless (_verify($right)) { require Carp; Carp::croak("Invalid version format"); } my $l = $#{$left->{version}}; my $r = $#{$right->{version}}; my $m = $l < $r ? $l : $r; my $lalpha = $left->is_alpha; my $ralpha = $right->is_alpha; my $retval = 0; my $i = 0; while ( $i <= $m && $retval == 0 ) { $retval = $left->{version}[$i] <=> $right->{version}[$i]; $i++; } # tiebreaker for alpha with identical terms if ( $retval == 0 && $l == $r && $left->{version}[$m] == $right->{version}[$m] && ( $lalpha || $ralpha ) ) { if ( $lalpha && !$ralpha ) { $retval = -1; } elsif ( $ralpha && !$lalpha) { $retval = +1; } } # possible match except for trailing 0's if ( $retval == 0 && $l != $r ) { if ( $l < $r ) { while ( $i <= $r && $retval == 0 ) { if ( $right->{version}[$i] != 0 ) { $retval = -1; # not a match after all } $i++; } } else { while ( $i <= $l && $retval == 0 ) { if ( $left->{version}[$i] != 0 ) { $retval = +1; # not a match after all } $i++; } } } return $retval; } sub vbool { my ($self) = @_; return vcmp($self,$self->new("0"),1); } sub vnoop { require Carp; Carp::croak("operation not supported with version object"); } sub is_alpha { my ($self) = @_; return (exists $self->{alpha}); } sub qv { my $value = shift; my $class = $CLASS; if (@_) { $class = ref($value) || $value; $value = shift; } $value = _un_vstring($value); $value = 'v'.$value unless $value =~ /(^v|\d+\.\d+\.\d)/; my $obj = $CLASS->new($value); return bless $obj, $class; } *declare = \&qv; sub is_qv { my ($self) = @_; return (exists $self->{qv}); } sub _verify { my ($self) = @_; if ( ref($self) && eval { exists $self->{version} } && ref($self->{version}) eq 'ARRAY' ) { return 1; } else { return 0; } } sub _is_non_alphanumeric { my $s = shift; $s = new ExtUtils::MakeMaker::charstar $s; while ($s) { return 0 if isSPACE($s); # early out return 1 unless (isALPHA($s) || isDIGIT($s) || $s =~ /[.-]/); $s++; } return 0; } sub _un_vstring { my $value = shift; # may be a v-string if ( length($value) >= 3 && $value !~ /[._]/ && _is_non_alphanumeric($value)) { my $tvalue; if ( "$]" >= 5.008_001 ) { $tvalue = _find_magic_vstring($value); $value = $tvalue if length $tvalue; } elsif ( "$]" >= 5.006_000 ) { $tvalue = sprintf("v%vd",$value); if ( $tvalue =~ /^v\d+(\.\d+){2,}$/ ) { # must be a v-string $value = $tvalue; } } } return $value; } sub _find_magic_vstring { my $value = shift; my $tvalue = ''; require B; my $sv = B::svref_2object(\$value); my $magic = ref($sv) eq 'B::PVMG' ? $sv->MAGIC : undef; while ( $magic ) { if ( $magic->TYPE eq 'V' ) { $tvalue = $magic->PTR; $tvalue =~ s/^v?(.+)$/v$1/; last; } else { $magic = $magic->MOREMAGIC; } } return $tvalue; } sub _VERSION { my ($obj, $req) = @_; my $class = ref($obj) || $obj; no strict 'refs'; if ( exists $INC{"$class.pm"} and not %{"$class\::"} and "$]" >= 5.008) { # file but no package require Carp; Carp::croak( "$class defines neither package nor VERSION" ."--version check failed"); } my $version = eval "\$$class\::VERSION"; if ( defined $version ) { local $^W if "$]" <= 5.008; $version = ExtUtils::MakeMaker::version::vpp->new($version); } if ( defined $req ) { unless ( defined $version ) { require Carp; my $msg = "$]" < 5.006 ? "$class version $req required--this is only version " : "$class does not define \$$class\::VERSION" ."--version check failed"; if ( $ENV{VERSION_DEBUG} ) { Carp::confess($msg); } else { Carp::croak($msg); } } $req = ExtUtils::MakeMaker::version::vpp->new($req); if ( $req > $version ) { require Carp; if ( $req->is_qv ) { Carp::croak( sprintf ("%s version %s required--". "this is only version %s", $class, $req->normal, $version->normal) ); } else { Carp::croak( sprintf ("%s version %s required--". "this is only version %s", $class, $req->stringify, $version->stringify) ); } } } return defined $version ? $version->stringify : undef; } 1; #this line is important and will help the module return a true value PK!œE¤$4$4"perl5/ExtUtils/MakeMaker/Locale.pmnuÏÃ6Ç$package ExtUtils::MakeMaker::Locale; use strict; use warnings; our $VERSION = "7.50"; $VERSION =~ tr/_//d; use base 'Exporter'; our @EXPORT_OK = qw( decode_argv env $ENCODING_LOCALE $ENCODING_LOCALE_FS $ENCODING_CONSOLE_IN $ENCODING_CONSOLE_OUT ); use Encode (); use Encode::Alias (); our $ENCODING_LOCALE; our $ENCODING_LOCALE_FS; our $ENCODING_CONSOLE_IN; our $ENCODING_CONSOLE_OUT; sub DEBUG () { 0 } sub _init { if ($^O eq "MSWin32") { unless ($ENCODING_LOCALE) { # Try to obtain what the Windows ANSI code page is eval { unless (defined &GetConsoleCP) { require Win32; # manually "import" it since Win32->import refuses *GetConsoleCP = sub { &Win32::GetConsoleCP } if defined &Win32::GetConsoleCP; } unless (defined &GetConsoleCP) { require Win32::API; Win32::API->Import('kernel32', 'int GetConsoleCP()'); } if (defined &GetConsoleCP) { my $cp = GetConsoleCP(); $ENCODING_LOCALE = "cp$cp" if $cp; } }; } unless ($ENCODING_CONSOLE_IN) { # only test one since set together unless (defined &GetInputCP) { eval { require Win32; eval { local $SIG{__WARN__} = sub {} if ( "$]" < 5.014 ); # suppress deprecation warning for inherited AUTOLOAD of Win32::GetConsoleCP() Win32::GetConsoleCP(); }; # manually "import" it since Win32->import refuses *GetInputCP = sub { &Win32::GetConsoleCP } if defined &Win32::GetConsoleCP; *GetOutputCP = sub { &Win32::GetConsoleOutputCP } if defined &Win32::GetConsoleOutputCP; }; unless (defined &GetInputCP) { eval { # try Win32::Console module for codepage to use require Win32::Console; *GetInputCP = sub { &Win32::Console::InputCP } if defined &Win32::Console::InputCP; *GetOutputCP = sub { &Win32::Console::OutputCP } if defined &Win32::Console::OutputCP; }; } unless (defined &GetInputCP) { # final fallback *GetInputCP = *GetOutputCP = sub { # another fallback that could work is: # reg query HKLM\System\CurrentControlSet\Control\Nls\CodePage /v ACP ((qx(chcp) || '') =~ /^Active code page: (\d+)/) ? $1 : (); }; } } my $cp = GetInputCP(); $ENCODING_CONSOLE_IN = "cp$cp" if $cp; $cp = GetOutputCP(); $ENCODING_CONSOLE_OUT = "cp$cp" if $cp; } } unless ($ENCODING_LOCALE) { eval { require I18N::Langinfo; $ENCODING_LOCALE = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET()); # Workaround of Encode < v2.25. The "646" encoding alias was # introduced in Encode-2.25, but we don't want to require that version # quite yet. Should avoid the CPAN testers failure reported from # openbsd-4.7/perl-5.10.0 combo. $ENCODING_LOCALE = "ascii" if $ENCODING_LOCALE eq "646"; # https://rt.cpan.org/Ticket/Display.html?id=66373 $ENCODING_LOCALE = "hp-roman8" if $^O eq "hpux" && $ENCODING_LOCALE eq "roman8"; }; $ENCODING_LOCALE ||= $ENCODING_CONSOLE_IN; } # Workaround of Encode < v2.71 for "cp65000" and "cp65001" # The "cp65000" and "cp65001" aliases were added in [Encode v2.71](https://github.com/dankogai/p5-encode/commit/7874bd95aa10967a3b5dbae333d16bcd703ac6c6) # via commit . # This will avoid test failures for Win32 machines using the UTF-7 or UTF-8 code pages. $ENCODING_LOCALE = 'UTF-7' if $ENCODING_LOCALE && lc($ENCODING_LOCALE) eq "cp65000"; $ENCODING_LOCALE = 'utf-8-strict' if $ENCODING_LOCALE && lc($ENCODING_LOCALE) eq "cp65001"; if ($^O eq "darwin") { $ENCODING_LOCALE_FS ||= "UTF-8"; } # final fallback $ENCODING_LOCALE ||= $^O eq "MSWin32" ? "cp1252" : "UTF-8"; $ENCODING_LOCALE_FS ||= $ENCODING_LOCALE; $ENCODING_CONSOLE_IN ||= $ENCODING_LOCALE; $ENCODING_CONSOLE_OUT ||= $ENCODING_CONSOLE_IN; unless (Encode::find_encoding($ENCODING_LOCALE)) { my $foundit; if (lc($ENCODING_LOCALE) eq "gb18030") { eval { require Encode::HanExtra; }; if ($@) { die "Need Encode::HanExtra to be installed to support locale codeset ($ENCODING_LOCALE), stopped"; } $foundit++ if Encode::find_encoding($ENCODING_LOCALE); } die "The locale codeset ($ENCODING_LOCALE) isn't one that perl can decode, stopped" unless $foundit; } # use Data::Dump; ddx $ENCODING_LOCALE, $ENCODING_LOCALE_FS, $ENCODING_CONSOLE_IN, $ENCODING_CONSOLE_OUT; } _init(); Encode::Alias::define_alias(sub { no strict 'refs'; no warnings 'once'; return ${"ENCODING_" . uc(shift)}; }, "locale"); sub _flush_aliases { no strict 'refs'; for my $a (sort keys %Encode::Alias::Alias) { if (defined ${"ENCODING_" . uc($a)}) { delete $Encode::Alias::Alias{$a}; warn "Flushed alias cache for $a" if DEBUG; } } } sub reinit { $ENCODING_LOCALE = shift; $ENCODING_LOCALE_FS = shift; $ENCODING_CONSOLE_IN = $ENCODING_LOCALE; $ENCODING_CONSOLE_OUT = $ENCODING_LOCALE; _init(); _flush_aliases(); } sub decode_argv { die if defined wantarray; for (@ARGV) { $_ = Encode::decode(locale => $_, @_); } } sub env { my $k = Encode::encode(locale => shift); my $old = $ENV{$k}; if (@_) { my $v = shift; if (defined $v) { $ENV{$k} = Encode::encode(locale => $v); } else { delete $ENV{$k}; } } return Encode::decode(locale => $old) if defined wantarray; } 1; __END__ =head1 NAME ExtUtils::MakeMaker::Locale - bundled Encode::Locale =head1 SYNOPSIS use Encode::Locale; use Encode; $string = decode(locale => $bytes); $bytes = encode(locale => $string); if (-t) { binmode(STDIN, ":encoding(console_in)"); binmode(STDOUT, ":encoding(console_out)"); binmode(STDERR, ":encoding(console_out)"); } # Processing file names passed in as arguments my $uni_filename = decode(locale => $ARGV[0]); open(my $fh, "<", encode(locale_fs => $uni_filename)) || die "Can't open '$uni_filename': $!"; binmode($fh, ":encoding(locale)"); ... =head1 DESCRIPTION In many applications it's wise to let Perl use Unicode for the strings it processes. Most of the interfaces Perl has to the outside world are still byte based. Programs therefore need to decode byte strings that enter the program from the outside and encode them again on the way out. The POSIX locale system is used to specify both the language conventions requested by the user and the preferred character set to consume and output. The C module looks up the charset and encoding (called a CODESET in the locale jargon) and arranges for the L module to know this encoding under the name "locale". It means bytes obtained from the environment can be converted to Unicode strings by calling C<< Encode::encode(locale => $bytes) >> and converted back again with C<< Encode::decode(locale => $string) >>. Where file systems interfaces pass file names in and out of the program we also need care. The trend is for operating systems to use a fixed file encoding that don't actually depend on the locale; and this module determines the most appropriate encoding for file names. The L module will know this encoding under the name "locale_fs". For traditional Unix systems this will be an alias to the same encoding as "locale". For programs running in a terminal window (called a "Console" on some systems) the "locale" encoding is usually a good choice for what to expect as input and output. Some systems allows us to query the encoding set for the terminal and C will do that if available and make these encodings known under the C aliases "console_in" and "console_out". For systems where we can't determine the terminal encoding these will be aliased as the same encoding as "locale". The advice is to use "console_in" for input known to come from the terminal and "console_out" for output to the terminal. In addition to arranging for various Encode aliases the following functions and variables are provided: =over =item decode_argv( ) =item decode_argv( Encode::FB_CROAK ) This will decode the command line arguments to perl (the C<@ARGV> array) in-place. The function will by default replace characters that can't be decoded by "\x{FFFD}", the Unicode replacement character. Any argument provided is passed as CHECK to underlying Encode::decode() call. Pass the value C to have the decoding croak if not all the command line arguments can be decoded. See L for details on other options for CHECK. =item env( $uni_key ) =item env( $uni_key => $uni_value ) Interface to get/set environment variables. Returns the current value as a Unicode string. The $uni_key and $uni_value arguments are expected to be Unicode strings as well. Passing C as $uni_value deletes the environment variable named $uni_key. The returned value will have the characters that can't be decoded replaced by "\x{FFFD}", the Unicode replacement character. There is no interface to request alternative CHECK behavior as for decode_argv(). If you need that you need to call encode/decode yourself. For example: my $key = Encode::encode(locale => $uni_key, Encode::FB_CROAK); my $uni_value = Encode::decode(locale => $ENV{$key}, Encode::FB_CROAK); =item reinit( ) =item reinit( $encoding ) Reinitialize the encodings from the locale. You want to call this function if you changed anything in the environment that might influence the locale. This function will croak if the determined encoding isn't recognized by the Encode module. With argument force $ENCODING_... variables to set to the given value. =item $ENCODING_LOCALE The encoding name determined to be suitable for the current locale. L know this encoding as "locale". =item $ENCODING_LOCALE_FS The encoding name determined to be suitable for file system interfaces involving file names. L know this encoding as "locale_fs". =item $ENCODING_CONSOLE_IN =item $ENCODING_CONSOLE_OUT The encodings to be used for reading and writing output to the a console. L know these encodings as "console_in" and "console_out". =back =head1 NOTES This table summarizes the mapping of the encodings set up by the C module: Encode | | | Alias | Windows | Mac OS X | POSIX ------------+---------+--------------+------------ locale | ANSI | nl_langinfo | nl_langinfo locale_fs | ANSI | UTF-8 | nl_langinfo console_in | OEM | nl_langinfo | nl_langinfo console_out | OEM | nl_langinfo | nl_langinfo =head2 Windows Windows has basically 2 sets of APIs. A wide API (based on passing UTF-16 strings) and a byte based API based a character set called ANSI. The regular Perl interfaces to the OS currently only uses the ANSI APIs. Unfortunately ANSI is not a single character set. The encoding that corresponds to ANSI varies between different editions of Windows. For many western editions of Windows ANSI corresponds to CP-1252 which is a character set similar to ISO-8859-1. Conceptually the ANSI character set is a similar concept to the POSIX locale CODESET so this module figures out what the ANSI code page is and make this available as $ENCODING_LOCALE and the "locale" Encoding alias. Windows systems also operate with another byte based character set. It's called the OEM code page. This is the encoding that the Console takes as input and output. It's common for the OEM code page to differ from the ANSI code page. =head2 Mac OS X On Mac OS X the file system encoding is always UTF-8 while the locale can otherwise be set up as normal for POSIX systems. File names on Mac OS X will at the OS-level be converted to NFD-form. A file created by passing a NFC-filename will come in NFD-form from readdir(). See L for details of NFD/NFC. Actually, Apple does not follow the Unicode NFD standard since not all character ranges are decomposed. The claim is that this avoids problems with round trip conversions from old Mac text encodings. See L for details. =head2 POSIX (Linux and other Unixes) File systems might vary in what encoding is to be used for filenames. Since this module has no way to actually figure out what the is correct it goes with the best guess which is to assume filenames are encoding according to the current locale. Users are advised to always specify UTF-8 as the locale charset. =head1 SEE ALSO L, L, L =head1 AUTHOR Copyright 2010 Gisle Aas . This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!oLÄðZZ"perl5/ExtUtils/MakeMaker/Config.pmnuÏÃ6Ç$package ExtUtils::MakeMaker::Config; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use Config (); # Give us an overridable config. our %Config = %Config::Config; sub import { my $caller = caller; no strict 'refs'; ## no critic *{$caller.'::Config'} = \%Config; } 1; =head1 NAME ExtUtils::MakeMaker::Config - Wrapper around Config.pm =head1 SYNOPSIS use ExtUtils::MakeMaker::Config; print $Config{installbin}; # or whatever =head1 DESCRIPTION B A very thin wrapper around Config.pm so MakeMaker is easier to test. =cut PK!ó¨?ãJOJO perl5/ExtUtils/MakeMaker/FAQ.podnuÏÃ6Ç$package ExtUtils::MakeMaker::FAQ; our $VERSION = '7.50'; $VERSION =~ tr/_//d; 1; __END__ =head1 NAME ExtUtils::MakeMaker::FAQ - Frequently Asked Questions About MakeMaker =head1 DESCRIPTION FAQs, tricks and tips for L. =head2 Module Installation =over 4 =item How do I install a module into my home directory? If you're not the Perl administrator you probably don't have permission to install a module to its default location. Ways of handling this with a B less manual effort on your part are L and L. Otherwise, you can install it for your own use into your home directory like so: # Non-unix folks, replace ~ with /path/to/your/home/dir perl Makefile.PL INSTALL_BASE=~ This will put modules into F<~/lib/perl5>, man pages into F<~/man> and programs into F<~/bin>. To ensure your Perl programs can see these newly installed modules, set your C environment variable to F<~/lib/perl5> or tell each of your programs to look in that directory with the following: use lib "$ENV{HOME}/lib/perl5"; or if $ENV{HOME} isn't set and you don't want to set it for some reason, do it the long way. use lib "/path/to/your/home/dir/lib/perl5"; =item How do I get MakeMaker and Module::Build to install to the same place? Module::Build, as of 0.28, supports two ways to install to the same location as MakeMaker. We highly recommend the install_base method, its the simplest and most closely approximates the expected behavior of an installation prefix. 1) Use INSTALL_BASE / C<--install_base> MakeMaker (as of 6.31) and Module::Build (as of 0.28) both can install to the same locations using the "install_base" concept. See L for details. To get MM and MB to install to the same location simply set INSTALL_BASE in MM and C<--install_base> in MB to the same location. perl Makefile.PL INSTALL_BASE=/whatever perl Build.PL --install_base /whatever This works most like other language's behavior when you specify a prefix. We recommend this method. 2) Use PREFIX / C<--prefix> Module::Build 0.28 added support for C<--prefix> which works like MakeMaker's PREFIX. perl Makefile.PL PREFIX=/whatever perl Build.PL --prefix /whatever We highly discourage this method. It should only be used if you know what you're doing and specifically need the PREFIX behavior. The PREFIX algorithm is complicated and focused on matching the system installation. =item How do I keep from installing man pages? Recent versions of MakeMaker will only install man pages on Unix-like operating systems by default. To generate manpages on non-Unix operating systems, make the "manifypods" target. For an individual module: perl Makefile.PL INSTALLMAN1DIR=none INSTALLMAN3DIR=none If you want to suppress man page installation for all modules you have to reconfigure Perl and tell it 'none' when it asks where to install man pages. =item How do I use a module without installing it? Two ways. One is to build the module normally... perl Makefile.PL make make test ...and then use L to point Perl at the built but uninstalled module: perl -Mblib script.pl perl -Mblib -e '...' The other is to install the module in a temporary location. perl Makefile.PL INSTALL_BASE=~/tmp make make test make install And then set PERL5LIB to F<~/tmp/lib/perl5>. This works well when you have multiple modules to work with. It also ensures that the module goes through its full installation process which may modify it. Again, L may assist you here. =item How can I organize tests into subdirectories and have them run? Let's take the following test directory structure: t/foo/sometest.t t/bar/othertest.t t/bar/baz/anothertest.t Now, inside of the C function in your F, specify where your tests are located with the C directive: test => {TESTS => 't/*.t t/*/*.t t/*/*/*.t'} The first entry in the string will run all tests in the top-level F directory. The second will run all test files located in any subdirectory under F. The third, runs all test files within any subdirectory within any other subdirectory located under F. Note that you do not have to use wildcards. You can specify explicitly which subdirectories to run tests in: test => {TESTS => 't/*.t t/foo/*.t t/bar/baz/*.t'} =item PREFIX vs INSTALL_BASE from Module::Build::Cookbook The behavior of PREFIX is complicated and depends closely on how your Perl is configured. The resulting installation locations will vary from machine to machine and even different installations of Perl on the same machine. Because of this, its difficult to document where prefix will place your modules. In contrast, INSTALL_BASE has predictable, easy to explain installation locations. Now that Module::Build and MakeMaker both have INSTALL_BASE there is little reason to use PREFIX other than to preserve your existing installation locations. If you are starting a fresh Perl installation we encourage you to use INSTALL_BASE. If you have an existing installation installed via PREFIX, consider moving it to an installation structure matching INSTALL_BASE and using that instead. =item Generating *.pm files with substitutions eg of $VERSION If you want to configure your module files for local conditions, or to automatically insert a version number, you can use EUMM's C capability, where it will automatically run each F<*.PL> it finds to generate its basename. For instance: # Makefile.PL: require 'common.pl'; my $version = get_version(); my @pms = qw(Foo.pm); WriteMakefile( NAME => 'Foo', VERSION => $version, PM => { map { ($_ => "\$(INST_LIB)/$_") } @pms }, clean => { FILES => join ' ', @pms }, ); # common.pl: sub get_version { '0.04' } sub process { my $v = get_version(); s/__VERSION__/$v/g; } 1; # Foo.pm.PL: require 'common.pl'; $_ = join '', ; process(); my $file = shift; open my $fh, '>', $file or die "$file: $!"; print $fh $_; __DATA__ package Foo; our $VERSION = '__VERSION__'; 1; You may notice that C is not specified above, since the default of mapping each .PL file to its basename works well. If the generated module were architecture-specific, you could replace C<$(INST_LIB)> above with C<$(INST_ARCHLIB)>, although if you locate modules under F, that would involve ensuring any C in front of the module location were removed. =back =head2 Common errors and problems =over 4 =item "No rule to make target `/usr/lib/perl5/CORE/config.h', needed by `Makefile'" Just what it says, you're missing that file. MakeMaker uses it to determine if perl has been rebuilt since the Makefile was made. It's a bit of a bug that it halts installation. Some operating systems don't ship the CORE directory with their base perl install. To solve the problem, you likely need to install a perl development package such as perl-devel (CentOS, Fedora and other Redhat systems) or perl (Ubuntu and other Debian systems). =back =head2 Philosophy and History =over 4 =item Why not just use ? Why did MakeMaker reinvent the build configuration wheel? Why not just use autoconf or automake or ppm or Ant or ... There are many reasons, but the major one is cross-platform compatibility. Perl is one of the most ported pieces of software ever. It works on operating systems I've never even heard of (see perlport for details). It needs a build tool that can work on all those platforms and with any wacky C compilers and linkers they might have. No such build tool exists. Even make itself has wildly different dialects. So we have to build our own. =item What is Module::Build and how does it relate to MakeMaker? Module::Build is a project by Ken Williams to supplant MakeMaker. Its primary advantages are: =over 8 =item * pure perl. no make, no shell commands =item * easier to customize =item * cleaner internals =item * less cruft =back Module::Build was long the official heir apparent to MakeMaker. The rate of both its development and adoption has slowed in recent years, though, and it is unclear what the future holds for it. That said, Module::Build set the stage for I to become the heir to MakeMaker. MakeMaker's maintainers have long said that it is a dead end and should be kept functioning, while being cautious about extending with new features. =back =head2 Module Writing =over 4 =item How do I keep my $VERSION up to date without resetting it manually? Often you want to manually set the $VERSION in the main module distribution because this is the version that everybody sees on CPAN and maybe you want to customize it a bit. But for all the other modules in your dist, $VERSION is really just bookkeeping and all that's important is it goes up every time the module is changed. Doing this by hand is a pain and you often forget. Probably the easiest way to do this is using F in L: perl-reversion -bump If your version control system supports revision numbers (git doesn't easily), the simplest way to do it automatically is to use its revision number (you are using version control, right?). In CVS, RCS and SVN you use $Revision$ (see the documentation of your version control system for details). Every time the file is checked in the $Revision$ will be updated, updating your $VERSION. SVN uses a simple integer for $Revision$ so you can adapt it for your $VERSION like so: ($VERSION) = q$Revision$ =~ /(\d+)/; In CVS and RCS version 1.9 is followed by 1.10. Since CPAN compares version numbers numerically we use a sprintf() to convert 1.9 to 1.009 and 1.10 to 1.010 which compare properly. $VERSION = sprintf "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/g; If branches are involved (ie. $Revision: 1.5.3.4$) it's a little more complicated. # must be all on one line or MakeMaker will get confused. $VERSION = do { my @r = (q$Revision$ =~ /\d+/g); sprintf "%d."."%03d" x $#r, @r }; In SVN, $Revision$ should be the same for every file in the project so they would all have the same $VERSION. CVS and RCS have a different $Revision$ per file so each file will have a different $VERSION. Distributed version control systems, such as SVK, may have a different $Revision$ based on who checks out the file, leading to a different $VERSION on each machine! Finally, some distributed version control systems, such as darcs, have no concept of revision number at all. =item What's this F thing and how did it get in my F?! F is a module meta-data file pioneered by Module::Build and automatically generated as part of the 'distdir' target (and thus 'dist'). See L. To shut off its generation, pass the C flag to C. =item How do I delete everything not in my F? Some folks are surprised that C does not delete everything not listed in their MANIFEST (thus making a clean distribution) but only tells them what they need to delete. This is done because it is considered too dangerous. While developing your module you might write a new file, not add it to the MANIFEST, then run a C and be sad because your new work was deleted. If you really want to do this, you can use C to read the MANIFEST and File::Find to delete the files. But you have to be careful. Here's a script to do that. Use at your own risk. Have fun blowing holes in your foot. #!/usr/bin/perl -w use strict; use File::Spec; use File::Find; use ExtUtils::Manifest qw(maniread); my %manifest = map {( $_ => 1 )} grep { File::Spec->canonpath($_) } keys %{ maniread() }; if( !keys %manifest ) { print "No files found in MANIFEST. Stopping.\n"; exit; } find({ wanted => sub { my $path = File::Spec->canonpath($_); return unless -f $path; return if exists $manifest{ $path }; print "unlink $path\n"; unlink $path; }, no_chdir => 1 }, "." ); =item Which tar should I use on Windows? We recommend ptar from Archive::Tar not older than 1.66 with '-C' option. =item Which zip should I use on Windows for '[ndg]make zipdist'? We recommend InfoZIP: L =back =head2 XS =over 4 =item How do I prevent "object version X.XX does not match bootstrap parameter Y.YY" errors? XS code is very sensitive to the module version number and will complain if the version number in your Perl module doesn't match. If you change your module's version # without rerunning Makefile.PL the old version number will remain in the Makefile, causing the XS code to be built with the wrong number. To avoid this, you can force the Makefile to be rebuilt whenever you change the module containing the version number by adding this to your WriteMakefile() arguments. depend => { '$(FIRST_MAKEFILE)' => '$(VERSION_FROM)' } =item How do I make two or more XS files coexist in the same directory? Sometimes you need to have two and more XS files in the same package. There are three ways: C, separate directories, and bootstrapping one XS from another. =over 8 =item XSMULTI Structure your modules so they are all located under F, such that C is in F and F, etc. Have your top-level C set the variable C to a true value. Er, that's it. =item Separate directories Put each XS files into separate directories, each with their own F. Make sure each of those Fs has the correct C, C, C etc. You will need to make sure the top-level F refers to each of these using C. =item Bootstrapping Let's assume that we have a package C, which includes C and C modules each having a separate XS file. First we use the following I: use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Cool::Foo', VERSION_FROM => 'Foo.pm', OBJECT => q/$(O_FILES)/, # ... other attrs ... ); Notice the C attribute. MakeMaker generates the following variables in I: # Handy lists of source code files: XS_FILES= Bar.xs \ Foo.xs C_FILES = Bar.c \ Foo.c O_FILES = Bar.o \ Foo.o Therefore we can use the C variable to tell MakeMaker to use these objects into the shared library. That's pretty much it. Now write I and I, I and I, where I bootstraps the shared library and I simply loading I. The only issue left is to how to bootstrap I. This is done from I: MODULE = Cool::Foo PACKAGE = Cool::Foo BOOT: # boot the second XS file boot_Cool__Bar(aTHX_ cv); If you have more than two files, this is the place where you should boot extra XS files from. The following four files sum up all the details discussed so far. Foo.pm: ------- package Cool::Foo; require DynaLoader; our @ISA = qw(DynaLoader); our $VERSION = '0.01'; bootstrap Cool::Foo $VERSION; 1; Bar.pm: ------- package Cool::Bar; use Cool::Foo; # bootstraps Bar.xs 1; Foo.xs: ------- #include "EXTERN.h" #include "perl.h" #include "XSUB.h" MODULE = Cool::Foo PACKAGE = Cool::Foo BOOT: # boot the second XS file boot_Cool__Bar(aTHX_ cv); MODULE = Cool::Foo PACKAGE = Cool::Foo PREFIX = cool_foo_ void cool_foo_perl_rules() CODE: fprintf(stderr, "Cool::Foo says: Perl Rules\n"); Bar.xs: ------- #include "EXTERN.h" #include "perl.h" #include "XSUB.h" MODULE = Cool::Bar PACKAGE = Cool::Bar PREFIX = cool_bar_ void cool_bar_perl_rules() CODE: fprintf(stderr, "Cool::Bar says: Perl Rules\n"); And of course a very basic test: t/cool.t: -------- use Test; BEGIN { plan tests => 1 }; use Cool::Foo; use Cool::Bar; Cool::Foo::perl_rules(); Cool::Bar::perl_rules(); ok 1; This tip has been brought to you by Nick Ing-Simmons and Stas Bekman. An alternative way to achieve this can be seen in L and L. =back =back =head1 DESIGN =head2 MakeMaker object hierarchy (simplified) What most people need to know (superclasses on top.) ExtUtils::MM_Any | ExtUtils::MM_Unix | ExtUtils::MM_{Current OS} | ExtUtils::MakeMaker | MY The object actually used is of the class L which allows you to override bits of MakeMaker inside your Makefile.PL by declaring MY::foo() methods. =head2 MakeMaker object hierarchy (real) Here's how it really works: ExtUtils::MM_Any | ExtUtils::MM_Unix | ExtUtils::Liblist::Kid ExtUtils::MM_{Current OS} (if necessary) | | ExtUtils::Liblist ExtUtils::MakeMaker | | | | | | |----------------------- ExtUtils::MM | | ExtUtils::MY MM (created by ExtUtils::MM) | | MY (created by ExtUtils::MY) | . | (mixin) | . | PACK### (created each call to ExtUtils::MakeMaker->new) NOTE: Yes, this is a mess. See L for some history. NOTE: When L is loaded it chooses a superclass for MM from amongst the ExtUtils::MM_* modules based on the current operating system. NOTE: ExtUtils::MM_{Current OS} represents one of the ExtUtils::MM_* modules except L chosen based on your operating system. NOTE: The main object used by MakeMaker is a PACK### object, *not* L. It is, effectively, a subclass of L, L, L and ExtUtils::MM_{Current OS} NOTE: The methods in L are simply copied into PACK### rather than MY being a superclass of PACK###. I don't remember the rationale. NOTE: L should be removed from the inheritance hiearchy and simply be called as functions. NOTE: Modules like L and L have been omitted for clarity. =head2 The MM_* hierarchy MM_Win95 MM_NW5 \ / MM_BeOS MM_Cygwin MM_OS2 MM_VMS MM_Win32 MM_DOS MM_UWIN \ | | | / / / ------------------------------------------------ | | MM_Unix | | | MM_Any NOTE: Each direct L subclass is also an L subclass. This is a temporary hack because MM_Unix overrides some MM_Any methods with Unix specific code. It allows the non-Unix modules to see the original MM_Any implementations. NOTE: Modules like L and L have been omitted for clarity. =head1 PATCHING If you have a question you'd like to see added to the FAQ (whether or not you have the answer) please either: =over 2 =item * make a pull request on the MakeMaker github repository =item * raise a issue on the MakeMaker github repository =item * file an RT ticket =item * email makemaker@perl.org =back =head1 AUTHOR The denizens of makemaker@perl.org. =head1 SEE ALSO L =cut PK!&œÆ›U U #perl5/ExtUtils/MakeMaker/version.pmnuÏÃ6Ç$#--------------------------------------------------------------------------# # This is a modified copy of version.pm 0.9909, bundled exclusively for # use by ExtUtils::Makemaker and its dependencies to bootstrap when # version.pm is not available. It should not be used by ordinary modules. # # When loaded, it will try to load version.pm. If that fails, it will load # ExtUtils::MakeMaker::version::vpp and alias various *version functions # to functions in that module. It will also override UNIVERSAL::VERSION. #--------------------------------------------------------------------------# package ExtUtils::MakeMaker::version; use 5.006001; use strict; use warnings; use vars qw(@ISA $VERSION $CLASS $STRICT $LAX *declare *qv); $VERSION = '7.50'; $VERSION =~ tr/_//d; $CLASS = 'version'; { local $SIG{'__DIE__'}; eval "use version"; if ( $@ ) { # don't have any version.pm installed eval "use ExtUtils::MakeMaker::version::vpp"; die "$@" if ( $@ ); no warnings; delete $INC{'version.pm'}; $INC{'version.pm'} = $INC{'ExtUtils/MakeMaker/version.pm'}; push @version::ISA, "ExtUtils::MakeMaker::version::vpp"; $version::VERSION = $VERSION; *version::qv = \&ExtUtils::MakeMaker::version::vpp::qv; *version::declare = \&ExtUtils::MakeMaker::version::vpp::declare; *version::_VERSION = \&ExtUtils::MakeMaker::version::vpp::_VERSION; *version::vcmp = \&ExtUtils::MakeMaker::version::vpp::vcmp; *version::new = \&ExtUtils::MakeMaker::version::vpp::new; if ("$]" >= 5.009000) { no strict 'refs'; *version::stringify = \&ExtUtils::MakeMaker::version::vpp::stringify; *{'version::(""'} = \&ExtUtils::MakeMaker::version::vpp::stringify; *{'version::(<=>'} = \&ExtUtils::MakeMaker::version::vpp::vcmp; *version::parse = \&ExtUtils::MakeMaker::version::vpp::parse; } require ExtUtils::MakeMaker::version::regex; *version::is_lax = \&ExtUtils::MakeMaker::version::regex::is_lax; *version::is_strict = \&ExtUtils::MakeMaker::version::regex::is_strict; *LAX = \$ExtUtils::MakeMaker::version::regex::LAX; *STRICT = \$ExtUtils::MakeMaker::version::regex::STRICT; } elsif ( ! version->can('is_qv') ) { *version::is_qv = sub { exists $_[0]->{qv} }; } } 1; PK!ƒ~˜«ss%perl5/ExtUtils/MakeMaker/Tutorial.podnuÏÃ6Ç$package ExtUtils::MakeMaker::Tutorial; our $VERSION = '7.50'; $VERSION =~ tr/_//d; =head1 NAME ExtUtils::MakeMaker::Tutorial - Writing a module with MakeMaker =head1 SYNOPSIS use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Your::Module', VERSION_FROM => 'lib/Your/Module.pm' ); =head1 DESCRIPTION This is a short tutorial on writing a simple module with MakeMaker. It's really not that hard. =head2 The Mantra MakeMaker modules are installed using this simple mantra perl Makefile.PL make make test make install There are lots more commands and options, but the above will do it. =head2 The Layout The basic files in a module look something like this. Makefile.PL MANIFEST lib/Your/Module.pm That's all that's strictly necessary. There's additional files you might want: lib/Your/Other/Module.pm t/some_test.t t/some_other_test.t Changes README INSTALL MANIFEST.SKIP bin/some_program =over 4 =item Makefile.PL When you run Makefile.PL, it makes a Makefile. That's the whole point of MakeMaker. The Makefile.PL is a simple program which loads ExtUtils::MakeMaker and runs the WriteMakefile() function to generate a Makefile. Here's an example of what you need for a simple module: use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Your::Module', VERSION_FROM => 'lib/Your/Module.pm' ); NAME is the top-level namespace of your module. VERSION_FROM is the file which contains the $VERSION variable for the entire distribution. Typically this is the same as your top-level module. =item MANIFEST A simple listing of all the files in your distribution. Makefile.PL MANIFEST lib/Your/Module.pm File paths in a MANIFEST always use Unix conventions (ie. /) even if you're not on Unix. You can write this by hand or generate it with 'make manifest'. See L for more details. =item lib/ This is the directory where the .pm and .pod files you wish to have installed go. They are laid out according to namespace. So Foo::Bar is F. =item t/ Tests for your modules go here. Each test filename ends with a .t. So F 'make test' will run these tests. Typically, the F test directory is flat, with all test files located directly within it. However, you can nest tests within subdirectories, for example: t/foo/subdir_test.t To do this, you need to inform C in your I file in the following fashion: test => {TESTS => 't/*.t t/*/*.t'} That will run all tests in F, as well as all tests in all subdirectories that reside under F. You can nest as deeply as makes sense for your project. Simply add another entry in the test location string. For example, to test: t/foo/bar/subdir_test.t You would use the following C directive: test => {TESTS => 't/*.t t/*/*/*.t'} Note that in the above example, tests in the first subdirectory will not be run. To run all tests in the intermediary subdirectory preceding the one the test files are in, you need to explicitly note it: test => {TESTS => 't/*.t t/*/*.t t/*/*/*.t'} You don't need to specify wildcards if you only want to test within specific subdirectories. The following example will only run tests in F: test => {TESTS => 't/foo/*.t'} Tests are run from the top level of your distribution. So inside a test you would refer to ./lib to enter the lib directory, for example. =item Changes A log of changes you've made to this module. The layout is free-form. Here's an example: 1.01 Fri Apr 11 00:21:25 PDT 2003 - thing() does some stuff now - fixed the wiggy bug in withit() 1.00 Mon Apr 7 00:57:15 PDT 2003 - "Rain of Frogs" now supported =item README A short description of your module, what it does, why someone would use it and its limitations. CPAN automatically pulls your README file out of the archive and makes it available to CPAN users, it is the first thing they will read to decide if your module is right for them. =item INSTALL Instructions on how to install your module along with any dependencies. Suggested information to include here: any extra modules required for use the minimum version of Perl required if only works on certain operating systems =item MANIFEST.SKIP A file full of regular expressions to exclude when using 'make manifest' to generate the MANIFEST. These regular expressions are checked against each file path found in the distribution (so you're matching against "t/foo.t" not "foo.t"). Here's a sample: ~$ # ignore emacs and vim backup files .bak$ # ignore manual backups \# # ignore CVS old revision files and emacs temp files Since # can be used for comments, # must be escaped. MakeMaker comes with a default MANIFEST.SKIP to avoid things like version control directories and backup files. Specifying your own will override this default. =item bin/ =back =head1 SEE ALSO L gives stylistic help writing a module. L gives more information about how to write a module. There are modules to help you through the process of writing a module: L, L, L, L, L =cut 1; PK!¾6™&b&bperl5/ExtUtils/Liblist/Kid.pmnuÏÃ6Ç$package ExtUtils::Liblist::Kid; # XXX Splitting this out into its own .pm is a temporary solution. # This kid package is to be used by MakeMaker. It will not work if # $self is not a Makemaker. use 5.006; # Broken out of MakeMaker from version 4.11 use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use ExtUtils::MakeMaker::Config; use Cwd 'cwd'; use File::Basename; use File::Spec; sub ext { if ( $^O eq 'VMS' ) { return &_vms_ext; } elsif ( $^O eq 'MSWin32' ) { return &_win32_ext; } else { return &_unix_os2_ext; } } sub _unix_os2_ext { my ( $self, $potential_libs, $verbose, $give_libs ) = @_; $verbose ||= 0; if ( $^O =~ /os2|android/ and $Config{perllibs} ) { # Dynamic libraries are not transitive, so we may need including # the libraries linked against perl.dll/libperl.so again. $potential_libs .= " " if $potential_libs; $potential_libs .= $Config{perllibs}; } return ( "", "", "", "", ( $give_libs ? [] : () ) ) unless $potential_libs; warn "Potential libraries are '$potential_libs':\n" if $verbose; my ( $so ) = $Config{so}; my ( $libs ) = defined $Config{perllibs} ? $Config{perllibs} : $Config{libs}; my $Config_libext = $Config{lib_ext} || ".a"; my $Config_dlext = $Config{dlext}; # compute $extralibs, $bsloadlibs and $ldloadlibs from # $potential_libs # this is a rewrite of Andy Dougherty's extliblist in perl require Text::ParseWords; my ( @searchpath ); # from "-L/path" entries in $potential_libs my ( @libpath ) = Text::ParseWords::quotewords( '\s+', 0, $Config{'libpth'} || '' ); my ( @ldloadlibs, @bsloadlibs, @extralibs, @ld_run_path, %ld_run_path_seen ); my ( @libs, %libs_seen ); my ( $fullname, @fullname ); my ( $pwd ) = cwd(); # from Cwd.pm my ( $found ) = 0; if ( $^O eq 'darwin' or $^O eq 'next' ) { # 'escape' Mach-O ld -framework and -F flags, so they aren't dropped later on $potential_libs =~ s/(^|\s)(-(?:weak_|reexport_|lazy_)?framework)\s+(\S+)/$1-Wl,$2 -Wl,$3/g; $potential_libs =~ s/(^|\s)(-F)\s*(\S+)/$1-Wl,$2 -Wl,$3/g; } foreach my $thislib ( Text::ParseWords::quotewords( '\s+', 0, $potential_libs) ) { my ( $custom_name ) = ''; # Handle possible linker path arguments. if ( $thislib =~ s/^(-[LR]|-Wl,-R|-Wl,-rpath,)// ) { # save path flag type my ( $ptype ) = $1; unless ( -d $thislib ) { warn "$ptype$thislib ignored, directory does not exist\n" if $verbose; next; } my ( $rtype ) = $ptype; if ( ( $ptype eq '-R' ) or ( $ptype =~ m!^-Wl,-[Rr]! ) ) { if ( $Config{'lddlflags'} =~ /-Wl,-[Rr]/ ) { $rtype = '-Wl,-R'; } elsif ( $Config{'lddlflags'} =~ /-R/ ) { $rtype = '-R'; } } unless ( File::Spec->file_name_is_absolute( $thislib ) ) { warn "Warning: $ptype$thislib changed to $ptype$pwd/$thislib\n"; $thislib = $self->catdir( $pwd, $thislib ); } push( @searchpath, $thislib ); $thislib = qq{"$thislib"} if $thislib =~ / /; # protect spaces if there push( @extralibs, "$ptype$thislib" ); push( @ldloadlibs, "$rtype$thislib" ); next; } if ( $thislib =~ m!^-Wl,! ) { push( @extralibs, $thislib ); push( @ldloadlibs, $thislib ); next; } # Handle possible library arguments. if ( $thislib =~ s/^-l(:)?// ) { # Handle -l:foo.so, which means that the library will # actually be called foo.so, not libfoo.so. This # is used in Android by ExtUtils::Depends to allow one XS # module to link to another. $custom_name = $1 || ''; } else { warn "Unrecognized argument in LIBS ignored: '$thislib'\n"; next; } my ( $found_lib ) = 0; foreach my $thispth ( @searchpath, @libpath ) { # Try to find the full name of the library. We need this to # determine whether it's a dynamically-loadable library or not. # This tends to be subject to various os-specific quirks. # For gcc-2.6.2 on linux (March 1995), DLD can not load # .sa libraries, with the exception of libm.sa, so we # deliberately skip them. if ((@fullname = $self->lsdir($thispth, "^\Qlib$thislib.$so.\E[0-9]+")) || (@fullname = $self->lsdir($thispth, "^\Qlib$thislib.\E[0-9]+\Q\.$so"))) { # Take care that libfoo.so.10 wins against libfoo.so.9. # Compare two libraries to find the most recent version # number. E.g. if you have libfoo.so.9.0.7 and # libfoo.so.10.1, first convert all digits into two # decimal places. Then we'll add ".00" to the shorter # strings so that we're comparing strings of equal length # Thus we'll compare libfoo.so.09.07.00 with # libfoo.so.10.01.00. Some libraries might have letters # in the version. We don't know what they mean, but will # try to skip them gracefully -- we'll set any letter to # '0'. Finally, sort in reverse so we can take the # first element. #TODO: iterate through the directory instead of sorting $fullname = "$thispth/" . ( sort { my ( $ma ) = $a; my ( $mb ) = $b; $ma =~ tr/A-Za-z/0/s; $ma =~ s/\b(\d)\b/0$1/g; $mb =~ tr/A-Za-z/0/s; $mb =~ s/\b(\d)\b/0$1/g; while ( length( $ma ) < length( $mb ) ) { $ma .= ".00"; } while ( length( $mb ) < length( $ma ) ) { $mb .= ".00"; } # Comparison deliberately backwards $mb cmp $ma; } @fullname )[0]; } elsif ( -f ( $fullname = "$thispth/lib$thislib.$so" ) && ( ( $Config{'dlsrc'} ne "dl_dld.xs" ) || ( $thislib eq "m" ) ) ) { } elsif (-f ( $fullname = "$thispth/lib${thislib}_s$Config_libext" ) && ( $Config{'archname'} !~ /RM\d\d\d-svr4/ ) && ( $thislib .= "_s" ) ) { # we must explicitly use _s version } elsif ( -f ( $fullname = "$thispth/lib$thislib$Config_libext" ) ) { } elsif ( defined( $Config_dlext ) && -f ( $fullname = "$thispth/lib$thislib.$Config_dlext" ) ) { } elsif ( -f ( $fullname = "$thispth/$thislib$Config_libext" ) ) { } elsif ( -f ( $fullname = "$thispth/lib$thislib.dll$Config_libext" ) ) { } elsif ( $^O eq 'cygwin' && -f ( $fullname = "$thispth/$thislib.dll" ) ) { } elsif ( -f ( $fullname = "$thispth/Slib$thislib$Config_libext" ) ) { } elsif ($^O eq 'dgux' && -l ( $fullname = "$thispth/lib$thislib$Config_libext" ) && readlink( $fullname ) =~ /^elink:/s ) { # Some of DG's libraries look like misconnected symbolic # links, but development tools can follow them. (They # look like this: # # libm.a -> elink:${SDE_PATH:-/usr}/sde/\ # ${TARGET_BINARY_INTERFACE:-m88kdgux}/usr/lib/libm.a # # , the compilation tools expand the environment variables.) } elsif ( $custom_name && -f ( $fullname = "$thispth/$thislib" ) ) { } else { warn "$thislib not found in $thispth\n" if $verbose; next; } warn "'-l$thislib' found at $fullname\n" if $verbose; push @libs, $fullname unless $libs_seen{$fullname}++; $found++; $found_lib++; # Now update library lists # what do we know about this library... # "Sounds like we should always assume it's a dynamic library on AIX." my $is_dyna = $^O eq 'aix' ? 1 : ( $fullname !~ /\Q$Config_libext\E\z/ ); my $in_perl = ( $libs =~ /\B-l:?\Q${thislib}\E\b/s ); # include the path to the lib once in the dynamic linker path # but only if it is a dynamic lib and not in Perl itself my ( $fullnamedir ) = dirname( $fullname ); push @ld_run_path, $fullnamedir if $is_dyna && !$in_perl && !$ld_run_path_seen{$fullnamedir}++; # Do not add it into the list if it is already linked in # with the main perl executable. # We have to special-case the NeXT, because math and ndbm # are both in libsys_s unless ( $in_perl || ( $Config{'osname'} eq 'next' && ( $thislib eq 'm' || $thislib eq 'ndbm' ) ) ) { push( @extralibs, "-l$custom_name$thislib" ); } # We might be able to load this archive file dynamically if ( ( $Config{'dlsrc'} =~ /dl_next/ && $Config{'osvers'} lt '4_0' ) || ( $Config{'dlsrc'} =~ /dl_dld/ ) ) { # We push -l$thislib instead of $fullname because # it avoids hardwiring a fixed path into the .bs file. # Mkbootstrap will automatically add dl_findfile() to # the .bs file if it sees a name in the -l format. # USE THIS, when dl_findfile() is fixed: # push(@bsloadlibs, "-l$thislib"); # OLD USE WAS while checking results against old_extliblist push( @bsloadlibs, "$fullname" ); } else { if ( $is_dyna ) { # For SunOS4, do not add in this shared library if # it is already linked in the main perl executable push( @ldloadlibs, "-l$custom_name$thislib" ) unless ( $in_perl and $^O eq 'sunos' ); } else { push( @ldloadlibs, "-l$custom_name$thislib" ); } } last; # found one here so don't bother looking further } warn "Warning (mostly harmless): " . "No library found for -l$thislib\n" unless $found_lib > 0; } unless ( $found ) { return ( '', '', '', '', ( $give_libs ? \@libs : () ) ); } else { return ( "@extralibs", "@bsloadlibs", "@ldloadlibs", join( ":", @ld_run_path ), ( $give_libs ? \@libs : () ) ); } } sub _win32_ext { require Text::ParseWords; my ( $self, $potential_libs, $verbose, $give_libs ) = @_; $verbose ||= 0; # If user did not supply a list, we punt. # (caller should probably use the list in $Config{libs}) return ( "", "", "", "", ( $give_libs ? [] : () ) ) unless $potential_libs; # TODO: make this use MM_Win32.pm's compiler detection my %libs_seen; my @extralibs; my $cc = $Config{cc} || ''; my $VC = $cc =~ /\bcl\b/i; my $GC = $cc =~ /\bgcc\b/i; my $libext = _win32_lib_extensions(); my @searchpath = ( '' ); # from "-L/path" entries in $potential_libs my @libpath = _win32_default_search_paths( $VC, $GC ); my $pwd = cwd(); # from Cwd.pm my $search = 1; # compute @extralibs from $potential_libs my @lib_search_list = _win32_make_lib_search_list( $potential_libs, $verbose ); for ( @lib_search_list ) { my $thislib = $_; # see if entry is a flag if ( /^:\w+$/ ) { $search = 0 if lc eq ':nosearch'; $search = 1 if lc eq ':search'; _debug( "Ignoring unknown flag '$thislib'\n", $verbose ) if !/^:(no)?(search|default)$/i; next; } # if searching is disabled, do compiler-specific translations unless ( $search ) { s/^-l(.+)$/$1.lib/ unless $GC; s/^-L/-libpath:/ if $VC; push( @extralibs, $_ ); next; } # handle possible linker path arguments if ( s/^-L// and not -d ) { _debug( "$thislib ignored, directory does not exist\n", $verbose ); next; } elsif ( -d ) { unless ( File::Spec->file_name_is_absolute( $_ ) ) { warn "Warning: '$thislib' changed to '-L$pwd/$_'\n"; $_ = $self->catdir( $pwd, $_ ); } push( @searchpath, $_ ); next; } my @paths = ( @searchpath, @libpath ); my ( $fullname, $path ) = _win32_search_file( $thislib, $libext, \@paths, $verbose, $GC ); if ( !$fullname ) { warn "Warning (mostly harmless): No library found for $thislib\n"; next; } _debug( "'$thislib' found as '$fullname'\n", $verbose ); push( @extralibs, $fullname ); $libs_seen{$fullname} = 1 if $path; # why is this a special case? } my @libs = sort keys %libs_seen; return ( '', '', '', '', ( $give_libs ? \@libs : () ) ) unless @extralibs; # make sure paths with spaces are properly quoted @extralibs = map { qq["$_"] } @extralibs; @libs = map { qq["$_"] } @libs; my $lib = join( ' ', @extralibs ); # normalize back to backward slashes (to help braindead tools) # XXX this may break equally braindead GNU tools that don't understand # backslashes, either. Seems like one can't win here. Cursed be CP/M. $lib =~ s,/,\\,g; _debug( "Result: $lib\n", $verbose ); wantarray ? ( $lib, '', $lib, '', ( $give_libs ? \@libs : () ) ) : $lib; } sub _win32_make_lib_search_list { my ( $potential_libs, $verbose ) = @_; # If Config.pm defines a set of default libs, we always # tack them on to the user-supplied list, unless the user # specified :nodefault my $libs = $Config{'perllibs'}; $potential_libs = join( ' ', $potential_libs, $libs ) if $libs and $potential_libs !~ /:nodefault/i; _debug( "Potential libraries are '$potential_libs':\n", $verbose ); $potential_libs =~ s,\\,/,g; # normalize to forward slashes my @list = Text::ParseWords::quotewords( '\s+', 0, $potential_libs ); return @list; } sub _win32_default_search_paths { my ( $VC, $GC ) = @_; my $libpth = $Config{'libpth'} || ''; $libpth =~ s,\\,/,g; # normalize to forward slashes my @libpath = Text::ParseWords::quotewords( '\s+', 0, $libpth ); push @libpath, "$Config{installarchlib}/CORE"; # add "$Config{installarchlib}/CORE" to default search path push @libpath, split /;/, $ENV{LIB} if $VC and $ENV{LIB}; push @libpath, split /;/, $ENV{LIBRARY_PATH} if $GC and $ENV{LIBRARY_PATH}; return @libpath; } sub _win32_search_file { my ( $thislib, $libext, $paths, $verbose, $GC ) = @_; my @file_list = _win32_build_file_list( $thislib, $GC, $libext ); for my $lib_file ( @file_list ) { for my $path ( @{$paths} ) { my $fullname = $lib_file; $fullname = "$path\\$fullname" if $path; return ( $fullname, $path ) if -f $fullname; _debug( "'$thislib' not found as '$fullname'\n", $verbose ); } } return; } sub _win32_build_file_list { my ( $lib, $GC, $extensions ) = @_; my @pre_fixed = _win32_build_prefixed_list( $lib, $GC ); return map _win32_attach_extensions( $_, $extensions ), @pre_fixed; } sub _win32_build_prefixed_list { my ( $lib, $GC ) = @_; return $lib if $lib !~ s/^-l//; return $lib if $lib =~ /^lib/ and !$GC; ( my $no_prefix = $lib ) =~ s/^lib//i; $lib = "lib$lib" if $no_prefix eq $lib; return ( $lib, $no_prefix ) if $GC; return ( $no_prefix, $lib ); } sub _win32_attach_extensions { my ( $lib, $extensions ) = @_; return map _win32_try_attach_extension( $lib, $_ ), @{$extensions}; } sub _win32_try_attach_extension { my ( $lib, $extension ) = @_; return $lib if $lib =~ /\Q$extension\E$/i; return "$lib$extension"; } sub _win32_lib_extensions { my @extensions; push @extensions, $Config{'lib_ext'} if $Config{'lib_ext'}; push @extensions, '.dll.a' if grep { m!^\.a$! } @extensions; push @extensions, '.lib' unless grep { m!^\.lib$! } @extensions; return \@extensions; } sub _debug { my ( $message, $verbose ) = @_; return if !$verbose; warn $message; return; } sub _vms_ext { my ( $self, $potential_libs, $verbose, $give_libs ) = @_; $verbose ||= 0; my ( @crtls, $crtlstr ); @crtls = ( ( $Config{'ldflags'} =~ m-/Debug-i ? $Config{'dbgprefix'} : '' ) . 'PerlShr/Share' ); push( @crtls, grep { not /\(/ } split /\s+/, $Config{'perllibs'} ); push( @crtls, grep { not /\(/ } split /\s+/, $Config{'libc'} ); # In general, we pass through the basic libraries from %Config unchanged. # The one exception is that if we're building in the Perl source tree, and # a library spec could be resolved via a logical name, we go to some trouble # to insure that the copy in the local tree is used, rather than one to # which a system-wide logical may point. if ( $self->{PERL_SRC} ) { my ( $locspec, $type ); foreach my $lib ( @crtls ) { if ( ( $locspec, $type ) = $lib =~ m{^([\w\$-]+)(/\w+)?} and $locspec =~ /perl/i ) { if ( lc $type eq '/share' ) { $locspec .= $Config{'exe_ext'}; } elsif ( lc $type eq '/library' ) { $locspec .= $Config{'lib_ext'}; } else { $locspec .= $Config{'obj_ext'}; } $locspec = $self->catfile( $self->{PERL_SRC}, $locspec ); $lib = "$locspec$type" if -e $locspec; } } } $crtlstr = @crtls ? join( ' ', @crtls ) : ''; unless ( $potential_libs ) { warn "Result:\n\tEXTRALIBS: \n\tLDLOADLIBS: $crtlstr\n" if $verbose; return ( '', '', $crtlstr, '', ( $give_libs ? [] : () ) ); } my ( %found, @fndlibs, $ldlib ); my $cwd = cwd(); my ( $so, $lib_ext, $obj_ext ) = @Config{ 'so', 'lib_ext', 'obj_ext' }; # List of common Unix library names and their VMS equivalents # (VMS equivalent of '' indicates that the library is automatically # searched by the linker, and should be skipped here.) my ( @flibs, %libs_seen ); my %libmap = ( 'm' => '', 'f77' => '', 'F77' => '', 'V77' => '', 'c' => '', 'malloc' => '', 'crypt' => '', 'resolv' => '', 'c_s' => '', 'socket' => '', 'X11' => 'DECW$XLIBSHR', 'Xt' => 'DECW$XTSHR', 'Xm' => 'DECW$XMLIBSHR', 'Xmu' => 'DECW$XMULIBSHR' ); warn "Potential libraries are '$potential_libs'\n" if $verbose; # First, sort out directories and library names in the input my ( @dirs, @libs ); foreach my $lib ( split ' ', $potential_libs ) { push( @dirs, $1 ), next if $lib =~ /^-L(.*)/; push( @dirs, $lib ), next if $lib =~ /[:>\]]$/; push( @dirs, $lib ), next if -d $lib; push( @libs, $1 ), next if $lib =~ /^-l(.*)/; push( @libs, $lib ); } push( @dirs, split( ' ', $Config{'libpth'} ) ); # Now make sure we've got VMS-syntax absolute directory specs # (We don't, however, check whether someone's hidden a relative # path in a logical name.) foreach my $dir ( @dirs ) { unless ( -d $dir ) { warn "Skipping nonexistent Directory $dir\n" if $verbose > 1; $dir = ''; next; } warn "Resolving directory $dir\n" if $verbose; if ( File::Spec->file_name_is_absolute( $dir ) ) { $dir = VMS::Filespec::vmspath( $dir ); } else { $dir = $self->catdir( $cwd, $dir ); } } @dirs = grep { length( $_ ) } @dirs; unshift( @dirs, '' ); # Check each $lib without additions first LIB: foreach my $lib ( @libs ) { if ( exists $libmap{$lib} ) { next unless length $libmap{$lib}; $lib = $libmap{$lib}; } my ( @variants, $cand ); my ( $ctype ) = ''; # If we don't have a file type, consider it a possibly abbreviated name and # check for common variants. We try these first to grab libraries before # a like-named executable image (e.g. -lperl resolves to perlshr.exe # before perl.exe). if ( $lib !~ /\.[^:>\]]*$/ ) { push( @variants, "${lib}shr", "${lib}rtl", "${lib}lib" ); push( @variants, "lib$lib" ) if $lib !~ /[:>\]]/; } push( @variants, $lib ); warn "Looking for $lib\n" if $verbose; foreach my $variant ( @variants ) { my ( $fullname, $name ); foreach my $dir ( @dirs ) { my ( $type ); $name = "$dir$variant"; warn "\tChecking $name\n" if $verbose > 2; $fullname = VMS::Filespec::rmsexpand( $name ); if ( defined $fullname and -f $fullname ) { # It's got its own suffix, so we'll have to figure out the type if ( $fullname =~ /(?:$so|exe)$/i ) { $type = 'SHR'; } elsif ( $fullname =~ /(?:$lib_ext|olb)$/i ) { $type = 'OLB'; } elsif ( $fullname =~ /(?:$obj_ext|obj)$/i ) { warn "Warning (mostly harmless): " . "Plain object file $fullname found in library list\n"; $type = 'OBJ'; } else { warn "Warning (mostly harmless): " . "Unknown library type for $fullname; assuming shared\n"; $type = 'SHR'; } } elsif (-f ( $fullname = VMS::Filespec::rmsexpand( $name, $so ) ) or -f ( $fullname = VMS::Filespec::rmsexpand( $name, '.exe' ) ) ) { $type = 'SHR'; $name = $fullname unless $fullname =~ /exe;?\d*$/i; } elsif ( not length( $ctype ) and # If we've got a lib already, # don't bother ( -f ( $fullname = VMS::Filespec::rmsexpand( $name, $lib_ext ) ) or -f ( $fullname = VMS::Filespec::rmsexpand( $name, '.olb' ) ) ) ) { $type = 'OLB'; $name = $fullname unless $fullname =~ /olb;?\d*$/i; } elsif ( not length( $ctype ) and # If we've got a lib already, # don't bother ( -f ( $fullname = VMS::Filespec::rmsexpand( $name, $obj_ext ) ) or -f ( $fullname = VMS::Filespec::rmsexpand( $name, '.obj' ) ) ) ) { warn "Warning (mostly harmless): " . "Plain object file $fullname found in library list\n"; $type = 'OBJ'; $name = $fullname unless $fullname =~ /obj;?\d*$/i; } if ( defined $type ) { $ctype = $type; $cand = $name; last if $ctype eq 'SHR'; } } if ( $ctype ) { push @{ $found{$ctype} }, $cand; warn "\tFound as $cand (really $fullname), type $ctype\n" if $verbose > 1; push @flibs, $name unless $libs_seen{$fullname}++; next LIB; } } warn "Warning (mostly harmless): " . "No library found for $lib\n"; } push @fndlibs, @{ $found{OBJ} } if exists $found{OBJ}; push @fndlibs, map { "$_/Library" } @{ $found{OLB} } if exists $found{OLB}; push @fndlibs, map { "$_/Share" } @{ $found{SHR} } if exists $found{SHR}; my $lib = join( ' ', @fndlibs ); $ldlib = $crtlstr ? "$lib $crtlstr" : $lib; $ldlib =~ s/^\s+|\s+$//g; warn "Result:\n\tEXTRALIBS: $lib\n\tLDLOADLIBS: $ldlib\n" if $verbose; wantarray ? ( $lib, '', $ldlib, '', ( $give_libs ? \@flibs : () ) ) : $lib; } 1; PK!š:÷‰ž‰žperl5/ExtUtils/Install.pmnuÏÃ6Ç$package ExtUtils::Install; use strict; use vars qw(@ISA @EXPORT $VERSION $MUST_REBOOT %Config); use AutoSplit; use Carp (); use Config qw(%Config); use Cwd qw(cwd); use Exporter; use ExtUtils::Packlist; use File::Basename qw(dirname); use File::Compare qw(compare); use File::Copy; use File::Find qw(find); use File::Path; use File::Spec; @ISA = ('Exporter'); @EXPORT = ('install','uninstall','pm_to_blib', 'install_default'); =pod =head1 NAME ExtUtils::Install - install files from here to there =head1 SYNOPSIS use ExtUtils::Install; install({ 'blib/lib' => 'some/install/dir' } ); uninstall($packlist); pm_to_blib({ 'lib/Foo/Bar.pm' => 'blib/lib/Foo/Bar.pm' }); =head1 VERSION 2.06 =cut $VERSION = '2.06'; # <-- do not forget to update the POD section just above this line! $VERSION = eval $VERSION; =pod =head1 DESCRIPTION Handles the installing and uninstalling of perl modules, scripts, man pages, etc... Both install() and uninstall() are specific to the way ExtUtils::MakeMaker handles the installation and deinstallation of perl modules. They are not designed as general purpose tools. On some operating systems such as Win32 installation may not be possible until after a reboot has occurred. This can have varying consequences: removing an old DLL does not impact programs using the new one, but if a new DLL cannot be installed properly until reboot then anything depending on it must wait. The package variable $ExtUtils::Install::MUST_REBOOT is used to store this status. If this variable is true then such an operation has occurred and anything depending on this module cannot proceed until a reboot has occurred. If this value is defined but false then such an operation has ocurred, but should not impact later operations. =over =begin _private =item _chmod($$;$) Wrapper to chmod() for debugging and error trapping. =item _warnonce(@) Warns about something only once. =item _choke(@) Dies with a special message. =back =end _private =cut my $Is_VMS = $^O eq 'VMS'; my $Is_MacPerl = $^O eq 'MacOS'; my $Is_Win32 = $^O eq 'MSWin32'; my $Is_cygwin = $^O eq 'cygwin'; my $CanMoveAtBoot = ($Is_Win32 || $Is_cygwin); my $Inc_uninstall_warn_handler; # install relative to here my $INSTALL_ROOT = $ENV{PERL_INSTALL_ROOT}; my $INSTALL_QUIET = $ENV{PERL_INSTALL_QUIET}; my $Curdir = File::Spec->curdir; my $Updir = File::Spec->updir; sub _estr(@) { return join "\n",'!' x 72,@_,'!' x 72,''; } {my %warned; sub _warnonce(@) { my $first=shift; my $msg=_estr "WARNING: $first",@_; warn $msg unless $warned{$msg}++; }} sub _choke(@) { my $first=shift; my $msg=_estr "ERROR: $first",@_; Carp::croak($msg); } sub _chmod($$;$) { my ( $mode, $item, $verbose )=@_; $verbose ||= 0; if (chmod $mode, $item) { printf "chmod(0%o, %s)\n",$mode, $item if $verbose > 1; } else { my $err="$!"; _warnonce sprintf "WARNING: Failed chmod(0%o, %s): %s\n", $mode, $item, $err if -e $item; } } =begin _private =over =item _move_file_at_boot( $file, $target, $moan ) OS-Specific, Win32/Cygwin Schedules a file to be moved/renamed/deleted at next boot. $file should be a filespec of an existing file $target should be a ref to an array if the file is to be deleted otherwise it should be a filespec for a rename. If the file is existing it will be replaced. Sets $MUST_REBOOT to 0 to indicate a deletion operation has occurred and sets it to 1 to indicate that a move operation has been requested. returns 1 on success, on failure if $moan is false errors are fatal. If $moan is true then returns 0 on error and warns instead of dies. =end _private =cut { my $Has_Win32API_File; sub _move_file_at_boot { #XXX OS-SPECIFIC my ( $file, $target, $moan )= @_; Carp::confess("Panic: Can't _move_file_at_boot on this platform!") unless $CanMoveAtBoot; my $descr= ref $target ? "'$file' for deletion" : "'$file' for installation as '$target'"; # *note* CanMoveAtBoot is only incidentally the same condition as below # this needs not hold true in the future. $Has_Win32API_File = ($Is_Win32 || $Is_cygwin) ? (eval {require Win32API::File; 1} || 0) : 0 unless defined $Has_Win32API_File; if ( ! $Has_Win32API_File ) { my @msg=( "Cannot schedule $descr at reboot.", "Try installing Win32API::File to allow operations on locked files", "to be scheduled during reboot. Or try to perform the operation by", "hand yourself. (You may need to close other perl processes first)" ); if ( $moan ) { _warnonce(@msg) } else { _choke(@msg) } return 0; } my $opts= Win32API::File::MOVEFILE_DELAY_UNTIL_REBOOT(); $opts= $opts | Win32API::File::MOVEFILE_REPLACE_EXISTING() unless ref $target; _chmod( 0666, $file ); _chmod( 0666, $target ) unless ref $target; if (Win32API::File::MoveFileEx( $file, $target, $opts )) { $MUST_REBOOT ||= ref $target ? 0 : 1; return 1; } else { my @msg=( "MoveFileEx $descr at reboot failed: $^E", "You may try to perform the operation by hand yourself. ", "(You may need to close other perl processes first).", ); if ( $moan ) { _warnonce(@msg) } else { _choke(@msg) } } return 0; } } =begin _private =item _unlink_or_rename( $file, $tryhard, $installing ) OS-Specific, Win32/Cygwin Tries to get a file out of the way by unlinking it or renaming it. On some OS'es (Win32 based) DLL files can end up locked such that they can be renamed but not deleted. Likewise sometimes a file can be locked such that it cant even be renamed or changed except at reboot. To handle these cases this routine finds a tempfile name that it can either rename the file out of the way or use as a proxy for the install so that the rename can happen later (at reboot). $file : the file to remove. $tryhard : should advanced tricks be used for deletion $installing : we are not merely deleting but we want to overwrite When $tryhard is not true if the unlink fails its fatal. When $tryhard is true then the file is attempted to be renamed. The renamed file is then scheduled for deletion. If the rename fails then $installing governs what happens. If it is false the failure is fatal. If it is true then an attempt is made to schedule installation at boot using a temporary file to hold the new file. If this fails then a fatal error is thrown, if it succeeds it returns the temporary file name (which will be a derivative of the original in the same directory) so that the caller can use it to install under. In all other cases of success returns $file. On failure throws a fatal error. =end _private =cut sub _unlink_or_rename { #XXX OS-SPECIFIC my ( $file, $tryhard, $installing )= @_; # this chmod was originally unconditional. However, its not needed on # POSIXy systems since permission to unlink a file is specified by the # directory rather than the file; and in fact it screwed up hard- and # symlinked files. Keep it for other platforms in case its still # needed there. if ($^O =~ /^(dos|os2|MSWin32|VMS)$/) { _chmod( 0666, $file ); } my $unlink_count = 0; while (unlink $file) { $unlink_count++; } return $file if $unlink_count > 0; my $error="$!"; _choke("Cannot unlink '$file': $!") unless $CanMoveAtBoot && $tryhard; my $tmp= "AAA"; ++$tmp while -e "$file.$tmp"; $tmp= "$file.$tmp"; warn "WARNING: Unable to unlink '$file': $error\n", "Going to try to rename it to '$tmp'.\n"; if ( rename $file, $tmp ) { warn "Rename successful. Scheduling '$tmp'\nfor deletion at reboot.\n"; # when $installing we can set $moan to true. # IOW, if we cant delete the renamed file at reboot its # not the end of the world. The other cases are more serious # and need to be fatal. _move_file_at_boot( $tmp, [], $installing ); return $file; } elsif ( $installing ) { _warnonce("Rename failed: $!. Scheduling '$tmp'\nfor". " installation as '$file' at reboot.\n"); _move_file_at_boot( $tmp, $file ); return $tmp; } else { _choke("Rename failed:$!", "Cannot proceed."); } } =pod =back =head2 Functions =begin _private =over =item _get_install_skip Handles loading the INSTALL.SKIP file. Returns an array of patterns to use. =cut sub _get_install_skip { my ( $skip, $verbose )= @_; if ($ENV{EU_INSTALL_IGNORE_SKIP}) { print "EU_INSTALL_IGNORE_SKIP is set, ignore skipfile settings\n" if $verbose>2; return []; } if ( ! defined $skip ) { print "Looking for install skip list\n" if $verbose>2; for my $file ( 'INSTALL.SKIP', $ENV{EU_INSTALL_SITE_SKIPFILE} ) { next unless $file; print "\tChecking for $file\n" if $verbose>2; if (-e $file) { $skip= $file; last; } } } if ($skip && !ref $skip) { print "Reading skip patterns from '$skip'.\n" if $verbose; if (open my $fh,$skip ) { my @patterns; while (<$fh>) { chomp; next if /^\s*(?:#|$)/; print "\tSkip pattern: $_\n" if $verbose>3; push @patterns, $_; } $skip= \@patterns; } else { warn "Can't read skip file:'$skip':$!\n"; $skip=[]; } } elsif ( UNIVERSAL::isa($skip,'ARRAY') ) { print "Using array for skip list\n" if $verbose>2; } elsif ($verbose) { print "No skip list found.\n" if $verbose>1; $skip= []; } warn "Got @{[0+@$skip]} skip patterns.\n" if $verbose>3; return $skip } =pod =item _have_write_access Abstract a -w check that tries to use POSIX::access() if possible. =cut { my $has_posix; sub _have_write_access { my $dir=shift; unless (defined $has_posix) { $has_posix= (!$Is_cygwin && !$Is_Win32 && eval 'local $^W; require POSIX; 1') || 0; } if ($has_posix) { return POSIX::access($dir, POSIX::W_OK()); } else { return -w $dir; } } } =pod =item _can_write_dir(C<$dir>) Checks whether a given directory is writable, taking account the possibility that the directory might not exist and would have to be created first. Returns a list, containing: C<($writable, $determined_by, @create)> C<$writable> says whether the directory is (hypothetically) writable C<$determined_by> is the directory the status was determined from. It will be either the C<$dir>, or one of its parents. C<@create> is a list of directories that would probably have to be created to make the requested directory. It may not actually be correct on relative paths with C<..> in them. But for our purposes it should work ok =cut sub _can_write_dir { my $dir=shift; return unless defined $dir and length $dir; my ($vol, $dirs, $file) = File::Spec->splitpath($dir,1); my @dirs = File::Spec->splitdir($dirs); unshift @dirs, File::Spec->curdir unless File::Spec->file_name_is_absolute($dir); my $path=''; my @make; while (@dirs) { if ($Is_VMS) { $dir = File::Spec->catdir($vol,@dirs); } else { $dir = File::Spec->catdir(@dirs); $dir = File::Spec->catpath($vol,$dir,'') if defined $vol and length $vol; } next if ( $dir eq $path ); if ( ! -e $dir ) { unshift @make,$dir; next; } if ( _have_write_access($dir) ) { return 1,$dir,@make } else { return 0,$dir,@make } } continue { pop @dirs; } return 0; } =pod =item _mkpath($dir,$show,$mode,$verbose,$dry_run) Wrapper around File::Path::mkpath() to handle errors. If $verbose is true and >1 then additional diagnostics will be produced, also this will force $show to true. If $dry_run is true then the directory will not be created but a check will be made to see whether it would be possible to write to the directory, or that it would be possible to create the directory. If $dry_run is not true dies if the directory can not be created or is not writable. =cut sub _mkpath { my ($dir,$show,$mode,$verbose,$dry_run)=@_; if ( $verbose && $verbose > 1 && ! -d $dir) { $show= 1; printf "mkpath(%s,%d,%#o)\n", $dir, $show, $mode; } if (!$dry_run) { if ( ! eval { File::Path::mkpath($dir,$show,$mode); 1 } ) { _choke("Can't create '$dir'","$@"); } } my ($can,$root,@make)=_can_write_dir($dir); if (!$can) { my @msg=( "Can't create '$dir'", $root ? "Do not have write permissions on '$root'" : "Unknown Error" ); if ($dry_run) { _warnonce @msg; } else { _choke @msg; } } elsif ($show and $dry_run) { print "$_\n" for @make; } } =pod =item _copy($from,$to,$verbose,$dry_run) Wrapper around File::Copy::copy to handle errors. If $verbose is true and >1 then additional diagnostics will be emitted. If $dry_run is true then the copy will not actually occur. Dies if the copy fails. =cut sub _copy { my ( $from, $to, $verbose, $dry_run)=@_; if ($verbose && $verbose>1) { printf "copy(%s,%s)\n", $from, $to; } if (!$dry_run) { File::Copy::copy($from,$to) or Carp::croak( _estr "ERROR: Cannot copy '$from' to '$to': $!" ); } } =pod =item _chdir($from) Wrapper around chdir to catch errors. If not called in void context returns the cwd from before the chdir. dies on error. =cut sub _chdir { my ($dir)= @_; my $ret; if (defined wantarray) { $ret= cwd; } chdir $dir or _choke("Couldn't chdir to '$dir': $!"); return $ret; } =pod =back =end _private =over =item B # deprecated forms install(\%from_to); install(\%from_to, $verbose, $dry_run, $uninstall_shadows, $skip, $always_copy, \%result); # recommended form as of 1.47 install([ from_to => \%from_to, verbose => 1, dry_run => 0, uninstall_shadows => 1, skip => undef, always_copy => 1, result => \%install_results, ]); Copies each directory tree of %from_to to its corresponding value preserving timestamps and permissions. There are two keys with a special meaning in the hash: "read" and "write". These contain packlist files. After the copying is done, install() will write the list of target files to $from_to{write}. If $from_to{read} is given the contents of this file will be merged into the written file. The read and the written file may be identical, but on AFS it is quite likely that people are installing to a different directory than the one where the files later appear. If $verbose is true, will print out each file removed. Default is false. This is "make install VERBINST=1". $verbose values going up to 5 show increasingly more diagnostics output. If $dry_run is true it will only print what it was going to do without actually doing it. Default is false. If $uninstall_shadows is true any differing versions throughout @INC will be uninstalled. This is "make install UNINST=1" As of 1.37_02 install() supports the use of a list of patterns to filter out files that shouldn't be installed. If $skip is omitted or undefined then install will try to read the list from INSTALL.SKIP in the CWD. This file is a list of regular expressions and is just like the MANIFEST.SKIP file used by L. A default site INSTALL.SKIP may be provided by setting then environment variable EU_INSTALL_SITE_SKIPFILE, this will only be used when there isn't a distribution specific INSTALL.SKIP. If the environment variable EU_INSTALL_IGNORE_SKIP is true then no install file filtering will be performed. If $skip is undefined then the skip file will be autodetected and used if it is found. If $skip is a reference to an array then it is assumed the array contains the list of patterns, if $skip is a true non reference it is assumed to be the filename holding the list of patterns, any other value of $skip is taken to mean that no install filtering should occur. B As of version 1.47 the following additions were made to the install interface. Note that the new argument style and use of the %result hash is recommended. The $always_copy parameter which when true causes files to be updated regardless as to whether they have changed, if it is defined but false then copies are made only if the files have changed, if it is undefined then the value of the environment variable EU_INSTALL_ALWAYS_COPY is used as default. The %result hash will be populated with the various keys/subhashes reflecting the install. Currently these keys and their structure are: install => { $target => $source }, install_fail => { $target => $source }, install_unchanged => { $target => $source }, install_filtered => { $source => $pattern }, uninstall => { $uninstalled => $source }, uninstall_fail => { $uninstalled => $source }, where C<$source> is the filespec of the file being installed. C<$target> is where it is being installed to, and C<$uninstalled> is any shadow file that is in C<@INC> or C<$ENV{PERL5LIB}> or other standard locations, and C<$pattern> is the pattern that caused a source file to be skipped. In future more keys will be added, such as to show created directories, however this requires changes in other modules and must therefore wait. These keys will be populated before any exceptions are thrown should there be an error. Note that all updates of the %result are additive, the hash will not be cleared before use, thus allowing status results of many installs to be easily aggregated. B If there is only one argument and it is a reference to an array then the array is assumed to contain a list of key-value pairs specifying the options. In this case the option "from_to" is mandatory. This style means that you do not have to supply a cryptic list of arguments and can use a self documenting argument list that is easier to understand. This is now the recommended interface to install(). B If all actions were successful install will return a hashref of the results as described above for the $result parameter. If any action is a failure then install will die, therefore it is recommended to pass in the $result parameter instead of using the return value. If the result parameter is provided then the returned hashref will be the passed in hashref. =cut sub install { #XXX OS-SPECIFIC my($from_to,$verbose,$dry_run,$uninstall_shadows,$skip,$always_copy,$result) = @_; if (@_==1 and eval { 1+@$from_to }) { my %opts = @$from_to; $from_to = $opts{from_to} or Carp::confess("from_to is a mandatory parameter"); $verbose = $opts{verbose}; $dry_run = $opts{dry_run}; $uninstall_shadows = $opts{uninstall_shadows}; $skip = $opts{skip}; $always_copy = $opts{always_copy}; $result = $opts{result}; } $result ||= {}; $verbose ||= 0; $dry_run ||= 0; $skip= _get_install_skip($skip,$verbose); $always_copy = $ENV{EU_INSTALL_ALWAYS_COPY} || $ENV{EU_ALWAYS_COPY} || 0 unless defined $always_copy; my(%from_to) = %$from_to; my(%pack, $dir, %warned); my($packlist) = ExtUtils::Packlist->new(); local(*DIR); for (qw/read write/) { $pack{$_}=$from_to{$_}; delete $from_to{$_}; } my $tmpfile = install_rooted_file($pack{"read"}); $packlist->read($tmpfile) if (-f $tmpfile); my $cwd = cwd(); my @found_files; my %check_dirs; MOD_INSTALL: foreach my $source (sort keys %from_to) { #copy the tree to the target directory without altering #timestamp and permission and remember for the .packlist #file. The packlist file contains the absolute paths of the #install locations. AFS users may call this a bug. We'll have #to reconsider how to add the means to satisfy AFS users also. #October 1997: we want to install .pm files into archlib if #there are any files in arch. So we depend on having ./blib/arch #hardcoded here. my $targetroot = install_rooted_dir($from_to{$source}); my $blib_lib = File::Spec->catdir('blib', 'lib'); my $blib_arch = File::Spec->catdir('blib', 'arch'); if ($source eq $blib_lib and exists $from_to{$blib_arch} and directory_not_empty($blib_arch) ){ $targetroot = install_rooted_dir($from_to{$blib_arch}); print "Files found in $blib_arch: installing files in $blib_lib into architecture dependent library tree\n"; } next unless -d $source; _chdir($source); # 5.5.3's File::Find missing no_chdir option # XXX OS-SPECIFIC # File::Find seems to always be Unixy except on MacPerl :( my $current_directory= $Is_MacPerl ? $Curdir : '.'; find(sub { my ($mode,$size,$atime,$mtime) = (stat)[2,7,8,9]; return if !-f _; my $origfile = $_; return if $origfile eq ".exists"; my $targetdir = File::Spec->catdir($targetroot, $File::Find::dir); my $targetfile = File::Spec->catfile($targetdir, $origfile); my $sourcedir = File::Spec->catdir($source, $File::Find::dir); my $sourcefile = File::Spec->catfile($sourcedir, $origfile); for my $pat (@$skip) { if ( $sourcefile=~/$pat/ ) { print "Skipping $targetfile (filtered)\n" if $verbose>1; $result->{install_filtered}{$sourcefile} = $pat; return; } } # we have to do this for back compat with old File::Finds # and because the target is relative my $save_cwd = _chdir($cwd); my $diff = 0; # XXX: I wonder how useful this logic is actually -- demerphq if ( $always_copy or !-f $targetfile or -s $targetfile != $size) { $diff++; } else { # we might not need to copy this file $diff = compare($sourcefile, $targetfile); } $check_dirs{$targetdir}++ unless -w $targetfile; push @found_files, [ $diff, $File::Find::dir, $origfile, $mode, $size, $atime, $mtime, $targetdir, $targetfile, $sourcedir, $sourcefile, ]; #restore the original directory we were in when File::Find #called us so that it doesn't get horribly confused. _chdir($save_cwd); }, $current_directory ); _chdir($cwd); } foreach my $targetdir (sort keys %check_dirs) { _mkpath( $targetdir, 0, 0755, $verbose, $dry_run ); } foreach my $found (@found_files) { my ($diff, $ffd, $origfile, $mode, $size, $atime, $mtime, $targetdir, $targetfile, $sourcedir, $sourcefile)= @$found; my $realtarget= $targetfile; if ($diff) { eval { if (-f $targetfile) { print "_unlink_or_rename($targetfile)\n" if $verbose>1; $targetfile= _unlink_or_rename( $targetfile, 'tryhard', 'install' ) unless $dry_run; } elsif ( ! -d $targetdir ) { _mkpath( $targetdir, 0, 0755, $verbose, $dry_run ); } print "Installing $targetfile\n"; _copy( $sourcefile, $targetfile, $verbose, $dry_run, ); #XXX OS-SPECIFIC print "utime($atime,$mtime,$targetfile)\n" if $verbose>1; utime($atime,$mtime + $Is_VMS,$targetfile) unless $dry_run>1; $mode = 0444 | ( $mode & 0111 ? 0111 : 0 ); $mode = $mode | 0222 if $realtarget ne $targetfile; _chmod( $mode, $targetfile, $verbose ); $result->{install}{$targetfile} = $sourcefile; 1 } or do { $result->{install_fail}{$targetfile} = $sourcefile; die $@; }; } else { $result->{install_unchanged}{$targetfile} = $sourcefile; print "Skipping $targetfile (unchanged)\n" if $verbose; } if ( $uninstall_shadows ) { inc_uninstall($sourcefile,$ffd, $verbose, $dry_run, $realtarget ne $targetfile ? $realtarget : "", $result); } # Record the full pathname. $packlist->{$targetfile}++; } if ($pack{'write'}) { $dir = install_rooted_dir(dirname($pack{'write'})); _mkpath( $dir, 0, 0755, $verbose, $dry_run ); print "Writing $pack{'write'}\n" if $verbose; $packlist->write(install_rooted_file($pack{'write'})) unless $dry_run; } _do_cleanup($verbose); return $result; } =begin _private =item _do_cleanup Standardize finish event for after another instruction has occurred. Handles converting $MUST_REBOOT to a die for instance. =end _private =cut sub _do_cleanup { my ($verbose) = @_; if ($MUST_REBOOT) { die _estr "Operation not completed! ", "You must reboot to complete the installation.", "Sorry."; } elsif (defined $MUST_REBOOT & $verbose) { warn _estr "Installation will be completed at the next reboot.\n", "However it is not necessary to reboot immediately.\n"; } } =begin _undocumented =item install_rooted_file( $file ) Returns $file, or catfile($INSTALL_ROOT,$file) if $INSTALL_ROOT is defined. =item install_rooted_dir( $dir ) Returns $dir, or catdir($INSTALL_ROOT,$dir) if $INSTALL_ROOT is defined. =end _undocumented =cut sub install_rooted_file { if (defined $INSTALL_ROOT) { File::Spec->catfile($INSTALL_ROOT, $_[0]); } else { $_[0]; } } sub install_rooted_dir { if (defined $INSTALL_ROOT) { File::Spec->catdir($INSTALL_ROOT, $_[0]); } else { $_[0]; } } =begin _undocumented =item forceunlink( $file, $tryhard ) Tries to delete a file. If $tryhard is true then we will use whatever devious tricks we can to delete the file. Currently this only applies to Win32 in that it will try to use Win32API::File to schedule a delete at reboot. A wrapper for _unlink_or_rename(). =end _undocumented =cut sub forceunlink { my ( $file, $tryhard )= @_; #XXX OS-SPECIFIC _unlink_or_rename( $file, $tryhard, not("installing") ); } =begin _undocumented =item directory_not_empty( $dir ) Returns 1 if there is an .exists file somewhere in a directory tree. Returns 0 if there is not. =end _undocumented =cut sub directory_not_empty ($) { my($dir) = @_; my $files = 0; find(sub { return if $_ eq ".exists"; if (-f) { $File::Find::prune++; $files = 1; } }, $dir); return $files; } =pod =item B I install_default(); install_default($fullext); Calls install() with arguments to copy a module from blib/ to the default site installation location. $fullext is the name of the module converted to a directory (ie. Foo::Bar would be Foo/Bar). If $fullext is not specified, it will attempt to read it from @ARGV. This is primarily useful for install scripts. B This function is not really useful because of the hard-coded install location with no way to control site vs core vs vendor directories and the strange way in which the module name is given. Consider its use discouraged. =cut sub install_default { @_ < 2 or Carp::croak("install_default should be called with 0 or 1 argument"); my $FULLEXT = @_ ? shift : $ARGV[0]; defined $FULLEXT or die "Do not know to where to write install log"; my $INST_LIB = File::Spec->catdir($Curdir,"blib","lib"); my $INST_ARCHLIB = File::Spec->catdir($Curdir,"blib","arch"); my $INST_BIN = File::Spec->catdir($Curdir,'blib','bin'); my $INST_SCRIPT = File::Spec->catdir($Curdir,'blib','script'); my $INST_MAN1DIR = File::Spec->catdir($Curdir,'blib','man1'); my $INST_MAN3DIR = File::Spec->catdir($Curdir,'blib','man3'); my @INST_HTML; if($Config{installhtmldir}) { my $INST_HTMLDIR = File::Spec->catdir($Curdir,'blib','html'); @INST_HTML = ($INST_HTMLDIR => $Config{installhtmldir}); } install({ read => "$Config{sitearchexp}/auto/$FULLEXT/.packlist", write => "$Config{installsitearch}/auto/$FULLEXT/.packlist", $INST_LIB => (directory_not_empty($INST_ARCHLIB)) ? $Config{installsitearch} : $Config{installsitelib}, $INST_ARCHLIB => $Config{installsitearch}, $INST_BIN => $Config{installbin} , $INST_SCRIPT => $Config{installscript}, $INST_MAN1DIR => $Config{installman1dir}, $INST_MAN3DIR => $Config{installman3dir}, @INST_HTML, },1,0,0); } =item B uninstall($packlist_file); uninstall($packlist_file, $verbose, $dont_execute); Removes the files listed in a $packlist_file. If $verbose is true, will print out each file removed. Default is false. If $dont_execute is true it will only print what it was going to do without actually doing it. Default is false. =cut sub uninstall { my($fil,$verbose,$dry_run) = @_; $verbose ||= 0; $dry_run ||= 0; die _estr "ERROR: no packlist file found: '$fil'" unless -f $fil; # my $my_req = $self->catfile(qw(auto ExtUtils Install forceunlink.al)); # require $my_req; # Hairy, but for the first my ($packlist) = ExtUtils::Packlist->new($fil); foreach (sort(keys(%$packlist))) { chomp; print "unlink $_\n" if $verbose; forceunlink($_,'tryhard') unless $dry_run; } print "unlink $fil\n" if $verbose; forceunlink($fil, 'tryhard') unless $dry_run; _do_cleanup($verbose); } =begin _undocumented =item inc_uninstall($filepath,$libdir,$verbose,$dry_run,$ignore,$results) Remove shadowed files. If $ignore is true then it is assumed to hold a filename to ignore. This is used to prevent spurious warnings from occurring when doing an install at reboot. We now only die when failing to remove a file that has precedence over our own, when our install has precedence we only warn. $results is assumed to contain a hashref which will have the keys 'uninstall' and 'uninstall_fail' populated with keys for the files removed and values of the source files they would shadow. =end _undocumented =cut sub inc_uninstall { my($filepath,$libdir,$verbose,$dry_run,$ignore,$results) = @_; my($dir); $ignore||=""; my $file = (File::Spec->splitpath($filepath))[2]; my %seen_dir = (); my @PERL_ENV_LIB = split $Config{path_sep}, defined $ENV{'PERL5LIB'} ? $ENV{'PERL5LIB'} : $ENV{'PERLLIB'} || ''; my @dirs=( @PERL_ENV_LIB, @INC, @Config{qw(archlibexp privlibexp sitearchexp sitelibexp)}); #warn join "\n","---",@dirs,"---"; my $seen_ours; foreach $dir ( @dirs ) { my $canonpath = $Is_VMS ? $dir : File::Spec->canonpath($dir); next if $canonpath eq $Curdir; next if $seen_dir{$canonpath}++; my $targetfile = File::Spec->catfile($canonpath,$libdir,$file); next unless -f $targetfile; # The reason why we compare file's contents is, that we cannot # know, which is the file we just installed (AFS). So we leave # an identical file in place my $diff = 0; if ( -f $targetfile && -s _ == -s $filepath) { # We have a good chance, we can skip this one $diff = compare($filepath,$targetfile); } else { $diff++; } print "#$file and $targetfile differ\n" if $diff && $verbose > 1; if (!$diff or $targetfile eq $ignore) { $seen_ours = 1; next; } if ($dry_run) { $results->{uninstall}{$targetfile} = $filepath; if ($verbose) { $Inc_uninstall_warn_handler ||= ExtUtils::Install::Warn->new(); $libdir =~ s|^\./||s ; # That's just cosmetics, no need to port. It looks prettier. $Inc_uninstall_warn_handler->add( File::Spec->catfile($libdir, $file), $targetfile ); } # if not verbose, we just say nothing } else { print "Unlinking $targetfile (shadowing?)\n" if $verbose; eval { die "Fake die for testing" if $ExtUtils::Install::Testing and ucase(File::Spec->canonpath($ExtUtils::Install::Testing)) eq ucase($targetfile); forceunlink($targetfile,'tryhard'); $results->{uninstall}{$targetfile} = $filepath; 1; } or do { $results->{fail_uninstall}{$targetfile} = $filepath; if ($seen_ours) { warn "Failed to remove probably harmless shadow file '$targetfile'\n"; } else { die "$@\n"; } }; } } } =begin _undocumented =item run_filter($cmd,$src,$dest) Filter $src using $cmd into $dest. =end _undocumented =cut sub run_filter { my ($cmd, $src, $dest) = @_; local(*CMD, *SRC); open(CMD, "|$cmd >$dest") || die "Cannot fork: $!"; open(SRC, $src) || die "Cannot open $src: $!"; my $buf; my $sz = 1024; while (my $len = sysread(SRC, $buf, $sz)) { syswrite(CMD, $buf, $len); } close SRC; close CMD or die "Filter command '$cmd' failed for $src"; } =pod =item B pm_to_blib(\%from_to); pm_to_blib(\%from_to, $autosplit_dir); pm_to_blib(\%from_to, $autosplit_dir, $filter_cmd); Copies each key of %from_to to its corresponding value efficiently. If an $autosplit_dir is provided, all .pm files will be autosplit into it. Any destination directories are created. $filter_cmd is an optional shell command to run each .pm file through prior to splitting and copying. Input is the contents of the module, output the new module contents. You can have an environment variable PERL_INSTALL_ROOT set which will be prepended as a directory to each installed file (and directory). By default verbose output is generated, setting the PERL_INSTALL_QUIET environment variable will silence this output. =cut sub pm_to_blib { my($fromto,$autodir,$pm_filter) = @_; _mkpath($autodir,0,0755) if defined $autodir; while(my($from, $to) = each %$fromto) { if( -f $to && -s $from == -s $to && -M $to < -M $from ) { print "Skip $to (unchanged)\n" unless $INSTALL_QUIET; next; } # When a pm_filter is defined, we need to pre-process the source first # to determine whether it has changed or not. Therefore, only perform # the comparison check when there's no filter to be ran. # -- RAM, 03/01/2001 my $need_filtering = defined $pm_filter && length $pm_filter && $from =~ /\.pm$/; if (!$need_filtering && 0 == compare($from,$to)) { print "Skip $to (unchanged)\n" unless $INSTALL_QUIET; next; } if (-f $to){ # we wont try hard here. its too likely to mess things up. forceunlink($to); } else { _mkpath(dirname($to),0,0755); } if ($need_filtering) { run_filter($pm_filter, $from, $to); print "$pm_filter <$from >$to\n"; } else { _copy( $from, $to ); print "cp $from $to\n" unless $INSTALL_QUIET; } my($mode,$atime,$mtime) = (stat $from)[2,8,9]; utime($atime,$mtime+$Is_VMS,$to); _chmod(0444 | ( $mode & 0111 ? 0111 : 0 ),$to); next unless $from =~ /\.pm$/; _autosplit($to,$autodir) if defined $autodir; } } =begin _private =item _autosplit From 1.0307 back, AutoSplit will sometimes leave an open filehandle to the file being split. This causes problems on systems with mandatory locking (ie. Windows). So we wrap it and close the filehandle. =end _private =cut sub _autosplit { #XXX OS-SPECIFIC my $retval = autosplit(@_); close *AutoSplit::IN if defined *AutoSplit::IN{IO}; return $retval; } package ExtUtils::Install::Warn; sub new { bless {}, shift } sub add { my($self,$file,$targetfile) = @_; push @{$self->{$file}}, $targetfile; } sub DESTROY { unless(defined $INSTALL_ROOT) { my $self = shift; my($file,$i,$plural); foreach $file (sort keys %$self) { $plural = @{$self->{$file}} > 1 ? "s" : ""; print "## Differing version$plural of $file found. You might like to\n"; for (0..$#{$self->{$file}}) { print "rm ", $self->{$file}[$_], "\n"; $i++; } } $plural = $i>1 ? "all those files" : "this file"; my $inst = (_invokant() eq 'ExtUtils::MakeMaker') ? ( $Config::Config{make} || 'make' ).' install' . ( $Is_VMS ? '/MACRO="UNINST"=1' : ' UNINST=1' ) : './Build install uninst=1'; print "## Running '$inst' will unlink $plural for you.\n"; } } =begin _private =item _invokant Does a heuristic on the stack to see who called us for more intelligent error messages. Currently assumes we will be called only by Module::Build or by ExtUtils::MakeMaker. =end _private =cut sub _invokant { my @stack; my $frame = 0; while (my $file = (caller($frame++))[1]) { push @stack, (File::Spec->splitpath($file))[2]; } my $builder; my $top = pop @stack; if ($top =~ /^Build/i || exists($INC{'Module/Build.pm'})) { $builder = 'Module::Build'; } else { $builder = 'ExtUtils::MakeMaker'; } return $builder; } =pod =back =head1 ENVIRONMENT =over 4 =item B Will be prepended to each install path. =item B Will prevent the automatic use of INSTALL.SKIP as the install skip file. =item B If there is no INSTALL.SKIP file in the make directory then this value can be used to provide a default. =item B If this environment variable is true then normal install processes will always overwrite older identical files during the install process. Note that the alias EU_ALWAYS_COPY will be supported if EU_INSTALL_ALWAYS_COPY is not defined until at least the 1.50 release. Please ensure you use the correct EU_INSTALL_ALWAYS_COPY. =back =head1 AUTHOR Original author lost in the mists of time. Probably the same as Makemaker. Production release currently maintained by demerphq C, extensive changes by Michael G. Schwern. Send bug reports via http://rt.cpan.org/. Please send your generated Makefile along with your report. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L =cut 1; PK! p^î��perl5/ExtUtils/MM_Darwin.pmnuÏÃ6Ç$package ExtUtils::MM_Darwin; use strict; use warnings; BEGIN { require ExtUtils::MM_Unix; our @ISA = qw( ExtUtils::MM_Unix ); } our $VERSION = '7.50'; $VERSION =~ tr/_//d; =head1 NAME ExtUtils::MM_Darwin - special behaviors for OS X =head1 SYNOPSIS For internal MakeMaker use only =head1 DESCRIPTION See L or L for documentation on the methods overridden here. =head2 Overridden Methods =head3 init_dist Turn off Apple tar's tendency to copy resource forks as "._foo" files. =cut sub init_dist { my $self = shift; # Thank you, Apple, for breaking tar and then breaking the work around. # 10.4 wants COPY_EXTENDED_ATTRIBUTES_DISABLE while 10.5 wants # COPYFILE_DISABLE. I'm not going to push my luck and instead just # set both. $self->{TAR} ||= 'COPY_EXTENDED_ATTRIBUTES_DISABLE=1 COPYFILE_DISABLE=1 tar'; $self->SUPER::init_dist(@_); } =head3 cflags Over-ride Apple's automatic setting of -Werror =cut sub cflags { my $self = shift; $self->{CCFLAGS} .= ($self->{CCFLAGS} ? ' ' : '').'-Wno-error=implicit-function-declaration'; $self->SUPER::cflags(@_); } 1; PK!œrWhhperl5/ExtUtils/MM_NW5.pmnuÏÃ6Ç$package ExtUtils::MM_NW5; =head1 NAME ExtUtils::MM_NW5 - methods to override UN*X behaviour in ExtUtils::MakeMaker =head1 SYNOPSIS use ExtUtils::MM_NW5; # Done internally by ExtUtils::MakeMaker if needed =head1 DESCRIPTION See L for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. =over =cut use strict; use warnings; use ExtUtils::MakeMaker::Config; use File::Basename; our $VERSION = '7.50'; $VERSION =~ tr/_//d; require ExtUtils::MM_Win32; our @ISA = qw(ExtUtils::MM_Win32); use ExtUtils::MakeMaker qw(&neatvalue &_sprintf562); $ENV{EMXSHELL} = 'sh'; # to run `commands` my $BORLAND = $Config{'cc'} =~ /\bbcc/i; my $GCC = $Config{'cc'} =~ /\bgcc/i; =item os_flavor We're Netware in addition to being Windows. =cut sub os_flavor { my $self = shift; return ($self->SUPER::os_flavor, 'Netware'); } =item init_platform Add Netware macros. LIBPTH, BASE_IMPORT, NLM_VERSION, MPKTOOL, TOOLPATH, BOOT_SYMBOL, NLM_SHORT_NAME, INCLUDE, PATH, MM_NW5_REVISION =item platform_constants Add Netware macros initialized above to the Makefile. =cut sub init_platform { my($self) = shift; # To get Win32's setup. $self->SUPER::init_platform; # incpath is copied to makefile var INCLUDE in constants sub, here just # make it empty my $libpth = $Config{'libpth'}; $libpth =~ s( )(;); $self->{'LIBPTH'} = $libpth; $self->{'BASE_IMPORT'} = $Config{'base_import'}; # Additional import file specified from Makefile.pl if($self->{'base_import'}) { $self->{'BASE_IMPORT'} .= ', ' . $self->{'base_import'}; } $self->{'NLM_VERSION'} = $Config{'nlm_version'}; $self->{'MPKTOOL'} = $Config{'mpktool'}; $self->{'TOOLPATH'} = $Config{'toolpath'}; (my $boot = $self->{'NAME'}) =~ s/:/_/g; $self->{'BOOT_SYMBOL'}=$boot; # If the final binary name is greater than 8 chars, # truncate it here. if(length($self->{'BASEEXT'}) > 8) { $self->{'NLM_SHORT_NAME'} = substr($self->{'BASEEXT'},0,8); } # Get the include path and replace the spaces with ; # Copy this to makefile as INCLUDE = d:\...;d:\; ($self->{INCLUDE} = $Config{'incpath'}) =~ s/([ ]*)-I/;/g; # Set the path to CodeWarrior binaries which might not have been set in # any other place $self->{PATH} = '$(PATH);$(TOOLPATH)'; $self->{MM_NW5_VERSION} = $VERSION; } sub platform_constants { my($self) = shift; my $make_frag = ''; # Setup Win32's constants. $make_frag .= $self->SUPER::platform_constants; foreach my $macro (qw(LIBPTH BASE_IMPORT NLM_VERSION MPKTOOL TOOLPATH BOOT_SYMBOL NLM_SHORT_NAME INCLUDE PATH MM_NW5_VERSION )) { next unless defined $self->{$macro}; $make_frag .= "$macro = $self->{$macro}\n"; } return $make_frag; } =item static_lib_pure_cmd Defines how to run the archive utility =cut sub static_lib_pure_cmd { my ($self, $src) = @_; $src =~ s/(\$\(\w+)(\))/$1:^"+"$2/g if $BORLAND; sprintf qq{\t\$(AR) %s\n}, ($BORLAND ? '$@ ' . $src : ($GCC ? '-ru $@ ' . $src : '-type library -o $@ ' . $src)); } =item xs_static_lib_is_xs =cut sub xs_static_lib_is_xs { return 1; } =item dynamic_lib Override of utility methods for OS-specific work. =cut sub xs_make_dynamic_lib { my ($self, $attribs, $from, $to, $todir, $ldfrom, $exportlist) = @_; my @m; # Taking care of long names like FileHandle, ByteLoader, SDBM_File etc if ($to =~ /^\$/) { if ($self->{NLM_SHORT_NAME}) { # deal with shortnames my $newto = q{$(INST_AUTODIR)\\$(NLM_SHORT_NAME).$(DLEXT)}; push @m, "$to: $newto\n\n"; $to = $newto; } } else { my ($v, $d, $f) = File::Spec->splitpath($to); # relies on $f having a literal "." in it, unlike for $(OBJ_EXT) if ($f =~ /[^\.]{9}\./) { # 9+ chars before '.', need to shorten $f = substr $f, 0, 8; } my $newto = File::Spec->catpath($v, $d, $f); push @m, "$to: $newto\n\n"; $to = $newto; } # bits below should be in dlsyms, not here # 1 2 3 4 push @m, _sprintf562 <<'MAKE_FRAG', $to, $from, $todir, $exportlist; # Create xdc data for an MT safe NLM in case of mpk build %1$s: %2$s $(MYEXTLIB) $(BOOTSTRAP) %3$s$(DFSEP).exists $(NOECHO) $(ECHO) Export boot_$(BOOT_SYMBOL) > %4$s $(NOECHO) $(ECHO) $(BASE_IMPORT) >> %4$s $(NOECHO) $(ECHO) Import @$(PERL_INC)\perl.imp >> %4$s MAKE_FRAG if ( $self->{CCFLAGS} =~ m/ -DMPK_ON /) { (my $xdc = $exportlist) =~ s#def\z#xdc#; $xdc = '$(BASEEXT).xdc'; push @m, sprintf <<'MAKE_FRAG', $xdc, $exportlist; $(MPKTOOL) $(XDCFLAGS) %s $(NOECHO) $(ECHO) xdcdata $(BASEEXT).xdc >> %s MAKE_FRAG } # Reconstruct the X.Y.Z version. my $version = join '.', map { sprintf "%d", $_ } "$]" =~ /(\d)\.(\d{3})(\d{2})/; push @m, sprintf <<'EOF', $from, $version, $to, $exportlist; $(LD) $(LDFLAGS) %s -desc "Perl %s Extension ($(BASEEXT)) XS_VERSION: $(XS_VERSION)" -nlmversion $(NLM_VERSION) -o %s $(MYEXTLIB) $(PERL_INC)\Main.lib -commandfile %s $(CHMOD) 755 $@ EOF join '', @m; } 1; __END__ =back =cut PK!†–ÕÖ:Ö:perl5/ExtUtils/MM_Win32.pmnuÏÃ6Ç$package ExtUtils::MM_Win32; use strict; use warnings; =head1 NAME ExtUtils::MM_Win32 - methods to override UN*X behaviour in ExtUtils::MakeMaker =head1 SYNOPSIS use ExtUtils::MM_Win32; # Done internally by ExtUtils::MakeMaker if needed =head1 DESCRIPTION See L for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. =cut use ExtUtils::MakeMaker::Config; use File::Basename; use File::Spec; use ExtUtils::MakeMaker qw(neatvalue _sprintf562); require ExtUtils::MM_Any; require ExtUtils::MM_Unix; our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix ); our $VERSION = '7.50'; $VERSION =~ tr/_//d; $ENV{EMXSHELL} = 'sh'; # to run `commands` my ( $BORLAND, $GCC, $MSVC ) = _identify_compiler_environment( \%Config ); sub _identify_compiler_environment { my ( $config ) = @_; my $BORLAND = $config->{cc} =~ /\bbcc/i ? 1 : 0; my $GCC = $config->{cc} =~ /\bgcc\b/i ? 1 : 0; my $MSVC = $config->{cc} =~ /\b(?:cl|icl)/i ? 1 : 0; # MSVC can come as clarm.exe, icl=Intel C return ( $BORLAND, $GCC, $MSVC ); } =head2 Overridden methods =over 4 =item B =cut sub dlsyms { my($self,%attribs) = @_; return '' if $self->{SKIPHASH}{'dynamic'}; $self->xs_dlsyms_iterator(\%attribs); } =item xs_dlsyms_ext On Win32, is C<.def>. =cut sub xs_dlsyms_ext { '.def'; } =item replace_manpage_separator Changes the path separator with . =cut sub replace_manpage_separator { my($self,$man) = @_; $man =~ s,[/\\]+,.,g; $man; } =item B Since Windows has nothing as simple as an executable bit, we check the file extension. The PATHEXT env variable will be used to get a list of extensions that might indicate a command, otherwise .com, .exe, .bat and .cmd will be used by default. =cut sub maybe_command { my($self,$file) = @_; my @e = exists($ENV{'PATHEXT'}) ? split(/;/, $ENV{PATHEXT}) : qw(.com .exe .bat .cmd); my $e = ''; for (@e) { $e .= "\Q$_\E|" } chop $e; # see if file ends in one of the known extensions if ($file =~ /($e)$/i) { return $file if -e $file; } else { for (@e) { return "$file$_" if -e "$file$_"; } } return; } =item B Using \ for Windows, except for "gmake" where it is /. =cut sub init_DIRFILESEP { my($self) = shift; # The ^ makes sure its not interpreted as an escape in nmake $self->{DIRFILESEP} = $self->is_make_type('nmake') ? '^\\' : $self->is_make_type('dmake') ? '\\\\' : $self->is_make_type('gmake') ? '/' : '\\'; } =item init_tools Override some of the slower, portable commands with Windows specific ones. =cut sub init_tools { my ($self) = @_; $self->{NOOP} ||= 'rem'; $self->{DEV_NULL} ||= '> NUL'; $self->{FIXIN} ||= $self->{PERL_CORE} ? "\$(PERLRUN) -I$self->{PERL_SRC}\\cpan\\ExtUtils-PL2Bat\\lib $self->{PERL_SRC}\\win32\\bin\\pl2bat.pl" : 'pl2bat.bat'; $self->SUPER::init_tools; # Setting SHELL from $Config{sh} can break dmake. Its ok without it. delete $self->{SHELL}; return; } =item init_others Override the default link and compile tools. LDLOADLIBS's default is changed to $Config{libs}. Adjustments are made for Borland's quirks needing -L to come first. =cut sub init_others { my $self = shift; $self->{LD} ||= 'link'; $self->{AR} ||= 'lib'; $self->SUPER::init_others; $self->{LDLOADLIBS} ||= $Config{libs}; # -Lfoo must come first for Borland, so we put it in LDDLFLAGS if ($BORLAND) { my $libs = $self->{LDLOADLIBS}; my $libpath = ''; while ($libs =~ s/(?:^|\s)(("?)-L.+?\2)(?:\s|$)/ /) { $libpath .= ' ' if length $libpath; $libpath .= $1; } $self->{LDLOADLIBS} = $libs; $self->{LDDLFLAGS} ||= $Config{lddlflags}; $self->{LDDLFLAGS} .= " $libpath"; } return; } =item init_platform Add MM_Win32_VERSION. =item platform_constants =cut sub init_platform { my($self) = shift; $self->{MM_Win32_VERSION} = $VERSION; return; } sub platform_constants { my($self) = shift; my $make_frag = ''; foreach my $macro (qw(MM_Win32_VERSION)) { next unless defined $self->{$macro}; $make_frag .= "$macro = $self->{$macro}\n"; } return $make_frag; } =item specify_shell Set SHELL to $ENV{COMSPEC} only if make is type 'gmake'. =cut sub specify_shell { my $self = shift; return '' unless $self->is_make_type('gmake'); "\nSHELL = $ENV{COMSPEC}\n"; } =item constants Add MAXLINELENGTH for dmake before all the constants are output. =cut sub constants { my $self = shift; my $make_text = $self->SUPER::constants; return $make_text unless $self->is_make_type('dmake'); # dmake won't read any single "line" (even those with escaped newlines) # larger than a certain size which can be as small as 8k. PM_TO_BLIB # on large modules like DateTime::TimeZone can create lines over 32k. # So we'll crank it up to a WHOPPING 64k. # # This has to come here before all the constants and not in # platform_constants which is after constants. my $size = $self->{MAXLINELENGTH} || 800000; my $prefix = qq{ # Get dmake to read long commands like PM_TO_BLIB MAXLINELENGTH = $size }; return $prefix . $make_text; } =item special_targets Add .USESHELL target for dmake. =cut sub special_targets { my($self) = @_; my $make_frag = $self->SUPER::special_targets; $make_frag .= <<'MAKE_FRAG' if $self->is_make_type('dmake'); .USESHELL : MAKE_FRAG return $make_frag; } =item static_lib_pure_cmd Defines how to run the archive utility =cut sub static_lib_pure_cmd { my ($self, $from) = @_; $from =~ s/(\$\(\w+)(\))/$1:^"+"$2/g if $BORLAND; sprintf qq{\t\$(AR) %s\n}, ($BORLAND ? '$@ ' . $from : ($GCC ? '-ru $@ ' . $from : '-out:$@ ' . $from)); } =item dynamic_lib Methods are overridden here: not dynamic_lib itself, but the utility ones that do the OS-specific work. =cut sub xs_make_dynamic_lib { my ($self, $attribs, $from, $to, $todir, $ldfrom, $exportlist) = @_; my @m = sprintf '%s : %s $(MYEXTLIB) %s$(DFSEP).exists %s $(PERL_ARCHIVEDEP) $(INST_DYNAMIC_DEP)'."\n", $to, $from, $todir, $exportlist; if ($GCC) { # per https://rt.cpan.org/Ticket/Display.html?id=78395 no longer # uses dlltool - relies on post 2002 MinGW # 1 2 push @m, _sprintf562 <<'EOF', $exportlist, $ldfrom; $(LD) %1$s -o $@ $(LDDLFLAGS) %2$s $(OTHERLDFLAGS) $(MYEXTLIB) "$(PERL_ARCHIVE)" $(LDLOADLIBS) -Wl,--enable-auto-image-base EOF } elsif ($BORLAND) { my $ldargs = $self->is_make_type('dmake') ? q{"$(PERL_ARCHIVE:s,/,\,)" $(LDLOADLIBS:s,/,\,) $(MYEXTLIB:s,/,\,),} : q{"$(subst /,\,$(PERL_ARCHIVE))" $(subst /,\,$(LDLOADLIBS)) $(subst /,\,$(MYEXTLIB)),}; my $subbed; if ($exportlist eq '$(EXPORT_LIST)') { $subbed = $self->is_make_type('dmake') ? q{$(EXPORT_LIST:s,/,\,)} : q{$(subst /,\,$(EXPORT_LIST))}; } else { # in XSMULTI, exportlist is per-XS, so have to sub in perl not make ($subbed = $exportlist) =~ s#/#\\#g; } push @m, sprintf <<'EOF', $ldfrom, $ldargs . $subbed; $(LD) $(LDDLFLAGS) $(OTHERLDFLAGS) %s,$@,,%s,$(RESFILES) EOF } else { # VC push @m, sprintf <<'EOF', $ldfrom, $exportlist; $(LD) -out:$@ $(LDDLFLAGS) %s $(OTHERLDFLAGS) $(MYEXTLIB) "$(PERL_ARCHIVE)" $(LDLOADLIBS) -def:%s EOF # Embed the manifest file if it exists push(@m, q{ if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2 if exist $@.manifest del $@.manifest}); } push @m, "\n\t\$(CHMOD) \$(PERM_RWX) \$\@\n"; join '', @m; } sub xs_dynamic_lib_macros { my ($self, $attribs) = @_; my $otherldflags = $attribs->{OTHERLDFLAGS} || ($BORLAND ? 'c0d32.obj': ''); my $inst_dynamic_dep = $attribs->{INST_DYNAMIC_DEP} || ""; sprintf <<'EOF', $otherldflags, $inst_dynamic_dep; # This section creates the dynamically loadable objects from relevant # objects and possibly $(MYEXTLIB). OTHERLDFLAGS = %s INST_DYNAMIC_DEP = %s EOF } =item extra_clean_files Clean out some extra dll.{base,exp} files which might be generated by gcc. Otherwise, take out all *.pdb files. =cut sub extra_clean_files { my $self = shift; return $GCC ? (qw(dll.base dll.exp)) : ('*.pdb'); } =item init_linker =cut sub init_linker { my $self = shift; $self->{PERL_ARCHIVE} = "\$(PERL_INC)\\$Config{libperl}"; $self->{PERL_ARCHIVEDEP} = "\$(PERL_INCDEP)\\$Config{libperl}"; $self->{PERL_ARCHIVE_AFTER} = ''; $self->{EXPORT_LIST} = '$(BASEEXT).def'; } =item perl_script Checks for the perl program under several common perl extensions. =cut sub perl_script { my($self,$file) = @_; return $file if -r $file && -f _; return "$file.pl" if -r "$file.pl" && -f _; return "$file.plx" if -r "$file.plx" && -f _; return "$file.bat" if -r "$file.bat" && -f _; return; } sub can_dep_space { my ($self) = @_; return 0 unless $self->can_load_xs; require Win32; require File::Spec; my ($vol, $dir) = File::Spec->splitpath($INC{'ExtUtils/MakeMaker.pm'}); # can_dep_space via GetShortPathName, if short paths are supported my $canary = Win32::GetShortPathName(File::Spec->catpath($vol, $dir, 'MakeMaker.pm')); (undef, undef, my $file) = File::Spec->splitpath($canary); return (length $file > 11) ? 0 : 1; } =item quote_dep =cut sub quote_dep { my ($self, $arg) = @_; if ($arg =~ / / and not $self->is_make_type('gmake')) { require Win32; $arg = Win32::GetShortPathName($arg); die <SUPER::quote_dep($arg); } =item xs_obj_opt Override to fixup -o flags for MSVC. =cut sub xs_obj_opt { my ($self, $output_file) = @_; ($MSVC ? "/Fo" : "-o ") . $output_file; } =item pasthru All we send is -nologo to nmake to prevent it from printing its damned banner. =cut sub pasthru { my($self) = shift; my $old = $self->SUPER::pasthru; return $old unless $self->is_make_type('nmake'); $old =~ s/(PASTHRU\s*=\s*)/$1 -nologo /; $old; } =item arch_check (override) Normalize all arguments for consistency of comparison. =cut sub arch_check { my $self = shift; # Win32 is an XS module, minperl won't have it. # arch_check() is not critical, so just fake it. return 1 unless $self->can_load_xs; return $self->SUPER::arch_check( map { $self->_normalize_path_name($_) } @_); } sub _normalize_path_name { my $self = shift; my $file = shift; require Win32; my $short = Win32::GetShortPathName($file); return defined $short ? lc $short : lc $file; } =item oneliner These are based on what command.com does on Win98. They may be wrong for other Windows shells, I don't know. =cut sub oneliner { my($self, $cmd, $switches) = @_; $switches = [] unless defined $switches; # Strip leading and trailing newlines $cmd =~ s{^\n+}{}; $cmd =~ s{\n+$}{}; $cmd = $self->quote_literal($cmd); $cmd = $self->escape_newlines($cmd); $switches = join ' ', @$switches; return qq{\$(ABSPERLRUN) $switches -e $cmd --}; } sub quote_literal { my($self, $text, $opts) = @_; $opts->{allow_variables} = 1 unless defined $opts->{allow_variables}; # See: http://www.autohotkey.net/~deleyd/parameters/parameters.htm#CPP # Apply the Microsoft C/C++ parsing rules $text =~ s{\\\\"}{\\\\\\\\\\"}g; # \\" -> \\\\\" $text =~ s{(? \\\" $text =~ s{(? \" $text = qq{"$text"} if $text =~ /[ \t#]/; # hash because gmake 4.2.1 # Apply the Command Prompt parsing rules (cmd.exe) my @text = split /("[^"]*")/, $text; # We should also escape parentheses, but it breaks one-liners containing # $(MACRO)s in makefiles. s{([<>|&^@!])}{^$1}g foreach grep { !/^"[^"]*"$/ } @text; $text = join('', @text); # dmake expands {{ to { and }} to }. if( $self->is_make_type('dmake') ) { $text =~ s/{/{{/g; $text =~ s/}/}}/g; } $text = $opts->{allow_variables} ? $self->escape_dollarsigns($text) : $self->escape_all_dollarsigns($text); return $text; } sub escape_newlines { my($self, $text) = @_; # Escape newlines $text =~ s{\n}{\\\n}g; return $text; } =item cd dmake can handle Unix style cd'ing but nmake (at least 1.5) cannot. It wants: cd dir1\dir2 command another_command cd ..\.. =cut sub cd { my($self, $dir, @cmds) = @_; return $self->SUPER::cd($dir, @cmds) unless $self->is_make_type('nmake'); my $cmd = join "\n\t", map "$_", @cmds; my $updirs = $self->catdir(map { $self->updir } $self->splitdir($dir)); # No leading tab and no trailing newline makes for easier embedding. my $make_frag = sprintf <<'MAKE_FRAG', $dir, $cmd, $updirs; cd %s %s cd %s MAKE_FRAG chomp $make_frag; return $make_frag; } =item max_exec_len nmake 1.50 limits command length to 2048 characters. =cut sub max_exec_len { my $self = shift; return $self->{_MAX_EXEC_LEN} ||= 2 * 1024; } =item os_flavor Windows is Win32. =cut sub os_flavor { return('Win32'); } =item dbgoutflag Returns a CC flag that tells the CC to emit a separate debugging symbol file when compiling an object file. =cut sub dbgoutflag { $MSVC ? '-Fd$(*).pdb' : ''; } =item cflags Defines the PERLDLL symbol if we are configured for static building since all code destined for the perl5xx.dll must be compiled with the PERLDLL symbol defined. =cut sub cflags { my($self,$libperl)=@_; return $self->{CFLAGS} if $self->{CFLAGS}; return '' unless $self->needs_linking(); my $base = $self->SUPER::cflags($libperl); foreach (split /\n/, $base) { /^(\S*)\s*=\s*(\S*)$/ and $self->{$1} = $2; }; $self->{CCFLAGS} .= " -DPERLDLL" if ($self->{LINKTYPE} eq 'static'); return $self->{CFLAGS} = qq{ CCFLAGS = $self->{CCFLAGS} OPTIMIZE = $self->{OPTIMIZE} PERLTYPE = $self->{PERLTYPE} }; } =item make_type Returns a suitable string describing the type of makefile being written. =cut sub make_type { my ($self) = @_; my $make = $self->make; $make = +( File::Spec->splitpath( $make ) )[-1]; $make =~ s!\.exe$!!i; if ( $make =~ m![^A-Z0-9]!i ) { ($make) = grep { m!make!i } split m![^A-Z0-9]!i, $make; } return "$make-style"; } 1; __END__ =back PK! ‹ØÔ  perl5/ExtUtils/ParseXS.pmnuÏÃ6Ç$package ExtUtils::ParseXS; use strict; use 5.006001; use Cwd; use Config; use Exporter 'import'; use File::Basename; use File::Spec; use Symbol; our $VERSION; BEGIN { $VERSION = '3.35'; } use ExtUtils::ParseXS::Constants $VERSION; use ExtUtils::ParseXS::CountLines $VERSION; use ExtUtils::ParseXS::Utilities $VERSION; use ExtUtils::ParseXS::Eval $VERSION; $VERSION = eval $VERSION if $VERSION =~ /_/; use ExtUtils::ParseXS::Utilities qw( standard_typemap_locations trim_whitespace C_string valid_proto_string process_typemaps map_type standard_XS_defs assign_func_args analyze_preprocessor_statements set_cond Warn current_line_number blurt death check_conditional_preprocessor_statements escape_file_for_line_directive report_typemap_failure ); our @EXPORT_OK = qw( process_file report_error_count ); ############################## # A number of "constants" our ($C_group_rex, $C_arg); # Group in C (no support for comments or literals) $C_group_rex = qr/ [({\[] (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )* [)}\]] /x; # Chunk in C without comma at toplevel (no comments): $C_arg = qr/ (?: (?> [^()\[\]{},"']+ ) | (??{ $C_group_rex }) | " (?: (?> [^\\"]+ ) | \\. )* " # String literal | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal )* /xs; # "impossible" keyword (multiple newline) my $END = "!End!\n\n"; # Match an XS Keyword my $BLOCK_regexp = '\s*(' . $ExtUtils::ParseXS::Constants::XSKeywordsAlternation . "|$END)\\s*:"; sub new { return bless {} => shift; } our $Singleton = __PACKAGE__->new; sub process_file { my $self; # Allow for $package->process_file(%hash), $obj->process_file, and process_file() if (@_ % 2) { my $invocant = shift; $self = ref($invocant) ? $invocant : $invocant->new; } else { $self = $Singleton; } my %options = @_; $self->{ProtoUsed} = exists $options{prototypes}; # Set defaults. my %args = ( argtypes => 1, csuffix => '.c', except => 0, hiertype => 0, inout => 1, linenumbers => 1, optimize => 1, output => \*STDOUT, prototypes => 0, typemap => [], versioncheck => 1, FH => Symbol::gensym(), %options, ); $args{except} = $args{except} ? ' TRY' : ''; # Global Constants my ($Is_VMS, $SymSet); if ($^O eq 'VMS') { $Is_VMS = 1; # Establish set of global symbols with max length 28, since xsubpp # will later add the 'XS_' prefix. require ExtUtils::XSSymSet; $SymSet = ExtUtils::XSSymSet->new(28); } @{ $self->{XSStack} } = ({type => 'none'}); $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ]; $self->{Overload} = 0; # bool $self->{errors} = 0; # count $self->{Fallback} = '&PL_sv_undef'; # Most of the 1500 lines below uses these globals. We'll have to # clean this up sometime, probably. For now, we just pull them out # of %args. -Ken $self->{RetainCplusplusHierarchicalTypes} = $args{hiertype}; $self->{WantPrototypes} = $args{prototypes}; $self->{WantVersionChk} = $args{versioncheck}; $self->{WantLineNumbers} = $args{linenumbers}; $self->{IncludedFiles} = {}; die "Missing required parameter 'filename'" unless $args{filename}; $self->{filepathname} = $args{filename}; ($self->{dir}, $self->{filename}) = (dirname($args{filename}), basename($args{filename})); $self->{filepathname} =~ s/\\/\\\\/g; $self->{IncludedFiles}->{$args{filename}}++; # Open the output file if given as a string. If they provide some # other kind of reference, trust them that we can print to it. if (not ref $args{output}) { open my($fh), "> $args{output}" or die "Can't create $args{output}: $!"; $args{outfile} = $args{output}; $args{output} = $fh; } # Really, we shouldn't have to chdir() or select() in the first # place. For now, just save and restore. my $orig_cwd = cwd(); my $orig_fh = select(); chdir($self->{dir}); my $pwd = cwd(); my $csuffix = $args{csuffix}; if ($self->{WantLineNumbers}) { my $cfile; if ( $args{outfile} ) { $cfile = $args{outfile}; } else { $cfile = $args{filename}; $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix; } tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output}); select PSEUDO_STDOUT; } else { select $args{output}; } $self->{typemap} = process_typemaps( $args{typemap}, $pwd ); # Move more settings from parameters to object foreach my $datum ( qw| argtypes except inout optimize | ) { $self->{$datum} = $args{$datum}; } $self->{strip_c_func_prefix} = $args{s}; # Identify the version of xsubpp used print <{filename}. Do not edit this file, edit $self->{filename} instead. * * ANY CHANGES MADE HERE WILL BE LOST! * */ EOM print("#line 1 \"" . escape_file_for_line_directive($self->{filepathname}) . "\"\n") if $self->{WantLineNumbers}; # Open the input file (using $self->{filename} which # is a basename'd $args{filename} due to chdir above) open($self->{FH}, '<', $self->{filename}) or die "cannot open $self->{filename}: $!\n"; FIRSTMODULE: while (readline($self->{FH})) { if (/^=/) { my $podstartline = $.; do { if (/^=cut\s*$/) { # We can't just write out a /* */ comment, as our embedded # POD might itself be in a comment. We can't put a /**/ # comment inside #if 0, as the C standard says that the source # file is decomposed into preprocessing characters in the stage # before preprocessing commands are executed. # I don't want to leave the text as barewords, because the spec # isn't clear whether macros are expanded before or after # preprocessing commands are executed, and someone pathological # may just have defined one of the 3 words as a macro that does # something strange. Multiline strings are illegal in C, so # the "" we write must be a string literal. And they aren't # concatenated until 2 steps later, so we are safe. # - Nicholas Clark print("#if 0\n \"Skipped embedded POD.\"\n#endif\n"); printf("#line %d \"%s\"\n", $. + 1, escape_file_for_line_directive($self->{filepathname})) if $self->{WantLineNumbers}; next FIRSTMODULE; } } while (readline($self->{FH})); # At this point $. is at end of file so die won't state the start # of the problem, and as we haven't yet read any lines &death won't # show the correct line in the message either. die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n") unless $self->{lastline}; } last if ($self->{Package}, $self->{Prefix}) = /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/; print $_; } unless (defined $_) { warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n"; exit 0; # Not a fatal error for the caller process } print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers}; standard_XS_defs(); print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers}; $self->{lastline} = $_; $self->{lastline_no} = $.; my $BootCode_ref = []; my $XSS_work_idx = 0; my $cpp_next_tmp = 'XSubPPtmpAAAA'; PARAGRAPH: while ($self->fetch_para()) { my $outlist_ref = []; # Print initial preprocessor statements and blank lines while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) { my $ln = shift(@{ $self->{line} }); print $ln, "\n"; next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/; my $statement = $+; ( $self, $XSS_work_idx, $BootCode_ref ) = analyze_preprocessor_statements( $self, $statement, $XSS_work_idx, $BootCode_ref ); } next PARAGRAPH unless @{ $self->{line} }; if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) { # We are inside an #if, but have not yet #defined its xsubpp variable. print "#define $cpp_next_tmp 1\n\n"; push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n"); push(@{ $BootCode_ref }, "#if $cpp_next_tmp"); $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++; } $self->death( "Code is not inside a function" ." (maybe last function was ended by a blank line " ." followed by a statement on column one?)") if $self->{line}->[0] =~ /^\s/; # initialize info arrays foreach my $member (qw(args_match var_types defaults arg_list argtype_seen in_out lengthof)) { $self->{$member} = {}; } $self->{proto_arg} = []; $self->{processing_arg_with_types} = 0; # bool $self->{proto_in_this_xsub} = 0; # counter & bool $self->{scope_in_this_xsub} = 0; # counter & bool $self->{interface} = 0; # bool $self->{interface_macro} = 'XSINTERFACE_FUNC'; $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET'; $self->{ProtoThisXSUB} = $self->{WantPrototypes}; # states 0 (none), 1 (yes), 2 (empty prototype) $self->{ScopeThisXSUB} = 0; # bool my $xsreturn = 0; $_ = shift(@{ $self->{line} }); while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|EXPORT_XSUB_SYMBOLS|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) { my $method = $kwd . "_handler"; $self->$method($_); next PARAGRAPH unless @{ $self->{line} }; $_ = shift(@{ $self->{line} }); } if ($self->check_keyword("BOOT")) { check_conditional_preprocessor_statements($self); push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \"" . escape_file_for_line_directive($self->{filepathname}) . "\"") if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/; push (@{ $BootCode_ref }, @{ $self->{line} }, ""); next PARAGRAPH; } # extract return type, function name and arguments ($self->{ret_type}) = ExtUtils::Typemaps::tidy_type($_); my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//; # Allow one-line ANSI-like declaration unshift @{ $self->{line} }, $2 if $self->{argtypes} and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s; # a function definition needs at least 2 lines $self->blurt("Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH unless @{ $self->{line} }; my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//; my $static = 1 if $self->{ret_type} =~ s/^static\s+//; my $func_header = shift(@{ $self->{line} }); $self->blurt("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s; my ($class, $orig_args); ($class, $self->{func_name}, $orig_args) = ($1, $2, $3); $class = "$4 $class" if $4; ($self->{pname} = $self->{func_name}) =~ s/^($self->{Prefix})?/$self->{Packprefix}/; my $clean_func_name; ($clean_func_name = $self->{func_name}) =~ s/^$self->{Prefix}//; $self->{Full_func_name} = "$self->{Packid}_$clean_func_name"; if ($Is_VMS) { $self->{Full_func_name} = $SymSet->addsym( $self->{Full_func_name} ); } # Check for duplicate function definition for my $tmp (@{ $self->{XSStack} }) { next unless defined $tmp->{functions}{ $self->{Full_func_name} }; Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected"); last; } $self->{XSStack}->[$XSS_work_idx]{functions}{ $self->{Full_func_name} }++; delete $self->{XsubAliases}; delete $self->{XsubAliasValues}; %{ $self->{Interfaces} } = (); @{ $self->{Attributes} } = (); $self->{DoSetMagic} = 1; $orig_args =~ s/\\\s*/ /g; # process line continuations my @args; my (@fake_INPUT_pre); # For length(s) generated variables my (@fake_INPUT); my $only_C_inlist_ref = {}; # Not in the signature of Perl function if ($self->{argtypes} and $orig_args =~ /\S/) { my $args = "$orig_args ,"; use re 'eval'; if ($args =~ /^( (??{ $C_arg }) , )* $ /x) { @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg); no re 'eval'; for ( @args ) { s/^\s+//; s/\s+$//; my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x); my ($pre, $len_name) = ($arg =~ /(.*?) \s* \b ( \w+ | length\( \s*\w+\s* \) ) \s* $ /x); next unless defined($pre) && length($pre); my $out_type = ''; my $inout_var; if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) { my $type = $1; $out_type = $type if $type ne 'IN'; $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//; $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//; } my $islength; if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) { $len_name = "XSauto_length_of_$1"; $islength = 1; die "Default value on length() argument: '$_'" if length $default; } if (length $pre or $islength) { # Has a type if ($islength) { push @fake_INPUT_pre, $arg; } else { push @fake_INPUT, $arg; } # warn "pushing '$arg'\n"; $self->{argtype_seen}->{$len_name}++; $_ = "$len_name$default"; # Assigns to @args } $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength; push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/; $self->{in_out}->{$len_name} = $out_type if $out_type; } } else { no re 'eval'; @args = split(/\s*,\s*/, $orig_args); Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split"); } } else { @args = split(/\s*,\s*/, $orig_args); for (@args) { if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) { my $out_type = $1; next if $out_type eq 'IN'; $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST"; if ($out_type =~ /OUTLIST$/) { push @{ $outlist_ref }, undef; } $self->{in_out}->{$_} = $out_type; } } } if (defined($class)) { my $arg0 = ((defined($static) or $self->{func_name} eq 'new') ? "CLASS" : "THIS"); unshift(@args, $arg0); } my $extra_args = 0; my @args_num = (); my $num_args = 0; my $report_args = ''; my $ellipsis; foreach my $i (0 .. $#args) { if ($args[$i] =~ s/\.\.\.//) { $ellipsis = 1; if ($args[$i] eq '' && $i == $#args) { $report_args .= ", ..."; pop(@args); last; } } if ($only_C_inlist_ref->{$args[$i]}) { push @args_num, undef; } else { push @args_num, ++$num_args; $report_args .= ", $args[$i]"; } if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) { $extra_args++; $args[$i] = $1; $self->{defaults}->{$args[$i]} = $2; $self->{defaults}->{$args[$i]} =~ s/"/\\"/g; } $self->{proto_arg}->[$i+1] = '$'; } my $min_args = $num_args - $extra_args; $report_args =~ s/"/\\"/g; $report_args =~ s/^,\s+//; $self->{func_args} = assign_func_args($self, \@args, $class); @{ $self->{args_match} }{@args} = @args_num; my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} }); my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} }); # Detect CODE: blocks which use ST(n)= or XST_m*(n,v) # to set explicit return values. my $EXPLICIT_RETURN = ($CODE && ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x )); $self->{ALIAS} = grep(/^\s*ALIAS\s*:/, @{ $self->{line} }); my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} }); $xsreturn = 1 if $EXPLICIT_RETURN; $externC = $externC ? qq[extern "C"] : ""; # print function header print Q(<<"EOF"); #$externC #XS_EUPXS(XS_$self->{Full_func_name}); /* prototype to pass -Wmissing-prototypes */ #XS_EUPXS(XS_$self->{Full_func_name}) #[[ # dVAR; dXSARGS; EOF print Q(<<"EOF") if $self->{ALIAS}; # dXSI32; EOF print Q(<<"EOF") if $INTERFACE; # dXSFUNCTION($self->{ret_type}); EOF $self->{cond} = set_cond($ellipsis, $min_args, $num_args); print Q(<<"EOF") if $self->{except}; # char errbuf[1024]; # *errbuf = '\\0'; EOF if($self->{cond}) { print Q(<<"EOF"); # if ($self->{cond}) # croak_xs_usage(cv, "$report_args"); EOF } else { # cv likely to be unused print Q(<<"EOF"); # PERL_UNUSED_VAR(cv); /* -W */ EOF } #gcc -Wall: if an xsub has PPCODE is used #it is possible none of ST, XSRETURN or XSprePUSH macros are used #hence 'ax' (setup by dXSARGS) is unused #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS #but such a move could break third-party extensions print Q(<<"EOF") if $PPCODE; # PERL_UNUSED_VAR(ax); /* -Wall */ EOF print Q(<<"EOF") if $PPCODE; # SP -= items; EOF # Now do a block of some sort. $self->{condnum} = 0; $self->{cond} = ''; # last CASE: conditional push(@{ $self->{line} }, "$END:"); push(@{ $self->{line_no} }, $self->{line_no}->[-1]); $_ = ''; check_conditional_preprocessor_statements(); while (@{ $self->{line} }) { $self->CASE_handler($_) if $self->check_keyword("CASE"); print Q(<<"EOF"); # $self->{except} [[ EOF # do initialization of input variables $self->{thisdone} = 0; $self->{retvaldone} = 0; $self->{deferred} = ""; %{ $self->{arg_list} } = (); $self->{gotRETVAL} = 0; $self->INPUT_handler($_); $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD"); print Q(<<"EOF") if $self->{ScopeThisXSUB}; # ENTER; # [[ EOF if (!$self->{thisdone} && defined($class)) { if (defined($static) or $self->{func_name} eq 'new') { print "\tchar *"; $self->{var_types}->{"CLASS"} = "char *"; $self->generate_init( { type => "char *", num => 1, var => "CLASS", printed_name => undef, } ); } else { print "\t" . map_type($self, "$class *"); $self->{var_types}->{"THIS"} = "$class *"; $self->generate_init( { type => "$class *", num => 1, var => "THIS", printed_name => undef, } ); } } # These are set if OUTPUT is found and/or CODE using RETVAL $self->{have_OUTPUT} = $self->{have_CODE_with_RETVAL} = 0; my ($wantRETVAL); # do code if (/^\s*NOT_IMPLEMENTED_YET/) { print "\n\tPerl_croak(aTHX_ \"$self->{pname}: not implemented yet\");\n"; $_ = ''; } else { if ($self->{ret_type} ne "void") { print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n" if !$self->{retvaldone}; $self->{args_match}->{"RETVAL"} = 0; $self->{var_types}->{"RETVAL"} = $self->{ret_type}; my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} ); print "\tdXSTARG;\n" if $self->{optimize} and $outputmap and $outputmap->targetable; } if (@fake_INPUT or @fake_INPUT_pre) { unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_; $_ = ""; $self->{processing_arg_with_types} = 1; $self->INPUT_handler($_); } print $self->{deferred}; $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD"); if ($self->check_keyword("PPCODE")) { $self->print_section(); $self->death("PPCODE must be last thing") if @{ $self->{line} }; print "\tLEAVE;\n" if $self->{ScopeThisXSUB}; print "\tPUTBACK;\n\treturn;\n"; } elsif ($self->check_keyword("CODE")) { my $consumed_code = $self->print_section(); if ($consumed_code =~ /\bRETVAL\b/) { $self->{have_CODE_with_RETVAL} = 1; } } elsif (defined($class) and $self->{func_name} eq "DESTROY") { print "\n\t"; print "delete THIS;\n"; } else { print "\n\t"; if ($self->{ret_type} ne "void") { print "RETVAL = "; $wantRETVAL = 1; } if (defined($static)) { if ($self->{func_name} eq 'new') { $self->{func_name} = "$class"; } else { print "${class}::"; } } elsif (defined($class)) { if ($self->{func_name} eq 'new') { $self->{func_name} .= " $class"; } else { print "THIS->"; } } my $strip = $self->{strip_c_func_prefix}; $self->{func_name} =~ s/^\Q$strip// if defined $strip; $self->{func_name} = 'XSFUNCTION' if $self->{interface}; print "$self->{func_name}($self->{func_args});\n"; } } # do output variables $self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section; undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section); # $wantRETVAL set if 'RETVAL =' autogenerated ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return; undef %{ $self->{outargs} }; $self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD"); # A CODE section with RETVAL, but no OUTPUT? FAIL! if ($self->{have_CODE_with_RETVAL} and not $self->{have_OUTPUT} and $self->{ret_type} ne 'void') { $self->Warn("Warning: Found a 'CODE' section which seems to be using 'RETVAL' but no 'OUTPUT' section."); } $self->generate_output( { type => $self->{var_types}->{$_}, num => $self->{args_match}->{$_}, var => $_, do_setmagic => $self->{DoSetMagic}, do_push => undef, } ) for grep $self->{in_out}->{$_} =~ /OUT$/, sort keys %{ $self->{in_out} }; my $prepush_done; # all OUTPUT done, so now push the return value on the stack if ($self->{gotRETVAL} && $self->{RETVAL_code}) { print "\t$self->{RETVAL_code}\n"; } elsif ($self->{gotRETVAL} || $wantRETVAL) { my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} ); my $trgt = $self->{optimize} && $outputmap && $outputmap->targetable; my $var = 'RETVAL'; my $type = $self->{ret_type}; if ($trgt) { my $what = $self->eval_output_typemap_code( qq("$trgt->{what}"), {var => $var, type => $self->{ret_type}} ); if (not $trgt->{with_size} and $trgt->{type} eq 'p') { # sv_setpv # PUSHp corresponds to sv_setpvn. Treat sv_setpv directly print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n"; $prepush_done = 1; } else { my $tsize = $trgt->{what_size}; $tsize = '' unless defined $tsize; $tsize = $self->eval_output_typemap_code( qq("$tsize"), {var => $var, type => $self->{ret_type}} ); print "\tXSprePUSH; PUSH$trgt->{type}($what$tsize);\n"; $prepush_done = 1; } } else { # RETVAL almost never needs SvSETMAGIC() $self->generate_output( { type => $self->{ret_type}, num => 0, var => 'RETVAL', do_setmagic => 0, do_push => undef, } ); } } $xsreturn = 1 if $self->{ret_type} ne "void"; my $num = $xsreturn; my $c = @{ $outlist_ref }; print "\tXSprePUSH;" if $c and not $prepush_done; print "\tEXTEND(SP,$c);\n" if $c; $xsreturn += $c; $self->generate_output( { type => $self->{var_types}->{$_}, num => $num++, var => $_, do_setmagic => 0, do_push => 1, } ) for @{ $outlist_ref }; # do cleanup $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD"); print Q(<<"EOF") if $self->{ScopeThisXSUB}; # ]] EOF print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE; # LEAVE; EOF # print function trailer print Q(<<"EOF"); # ]] EOF print Q(<<"EOF") if $self->{except}; # BEGHANDLERS # CATCHALL # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason); # ENDHANDLERS EOF if ($self->check_keyword("CASE")) { $self->blurt("Error: No 'CASE:' at top of function") unless $self->{condnum}; $_ = "CASE: $_"; # Restore CASE: label next; } last if $_ eq "$END:"; $self->death(/^$BLOCK_regexp/o ? "Misplaced '$1:'" : "Junk at end of function ($_)"); } print Q(<<"EOF") if $self->{except}; # if (errbuf[0]) # Perl_croak(aTHX_ errbuf); EOF if ($xsreturn) { print Q(<<"EOF") unless $PPCODE; # XSRETURN($xsreturn); EOF } else { print Q(<<"EOF") unless $PPCODE; # XSRETURN_EMPTY; EOF } print Q(<<"EOF"); #]] # EOF $self->{proto} = ""; unless($self->{ProtoThisXSUB}) { $self->{newXS} = "newXS_deffile"; $self->{file} = ""; } else { # Build the prototype string for the xsub $self->{newXS} = "newXSproto_portable"; $self->{file} = ", file"; if ($self->{ProtoThisXSUB} eq 2) { # User has specified empty prototype } elsif ($self->{ProtoThisXSUB} eq 1) { my $s = ';'; if ($min_args < $num_args) { $s = ''; $self->{proto_arg}->[$min_args] .= ";"; } push @{ $self->{proto_arg} }, "$s\@" if $ellipsis; $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } ); } else { # User has specified a prototype $self->{proto} = $self->{ProtoThisXSUB}; } $self->{proto} = qq{, "$self->{proto}"}; } if ($self->{XsubAliases} and keys %{ $self->{XsubAliases} }) { $self->{XsubAliases}->{ $self->{pname} } = 0 unless defined $self->{XsubAliases}->{ $self->{pname} }; foreach my $xname (sort keys %{ $self->{XsubAliases} }) { my $value = $self->{XsubAliases}{$xname}; push(@{ $self->{InitFileCode} }, Q(<<"EOF")); # cv = $self->{newXS}(\"$xname\", XS_$self->{Full_func_name}$self->{file}$self->{proto}); # XSANY.any_i32 = $value; EOF } } elsif (@{ $self->{Attributes} }) { push(@{ $self->{InitFileCode} }, Q(<<"EOF")); # cv = $self->{newXS}(\"$self->{pname}\", XS_$self->{Full_func_name}$self->{file}$self->{proto}); # apply_attrs_string("$self->{Package}", cv, "@{ $self->{Attributes} }", 0); EOF } elsif ($self->{interface}) { foreach my $yname (sort keys %{ $self->{Interfaces} }) { my $value = $self->{Interfaces}{$yname}; $yname = "$self->{Package}\::$yname" unless $yname =~ /::/; push(@{ $self->{InitFileCode} }, Q(<<"EOF")); # cv = $self->{newXS}(\"$yname\", XS_$self->{Full_func_name}$self->{file}$self->{proto}); # $self->{interface_macro_set}(cv,$value); EOF } } elsif($self->{newXS} eq 'newXS_deffile'){ # work around P5NCI's empty newXS macro push(@{ $self->{InitFileCode} }, " $self->{newXS}(\"$self->{pname}\", XS_$self->{Full_func_name}$self->{file}$self->{proto});\n"); } else { push(@{ $self->{InitFileCode} }, " (void)$self->{newXS}(\"$self->{pname}\", XS_$self->{Full_func_name}$self->{file}$self->{proto});\n"); } } # END 'PARAGRAPH' 'while' loop if ($self->{Overload}) { # make it findable with fetchmethod print Q(<<"EOF"); #XS_EUPXS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */ #XS_EUPXS(XS_$self->{Packid}_nil) #{ # dXSARGS; # XSRETURN_EMPTY; #} # EOF unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK"); /* Making a sub named "$self->{Package}::()" allows the package */ /* to be findable via fetchmethod(), and causes */ /* overload::Overloaded("$self->{Package}") to return true. */ (void)$self->{newXS}("$self->{Package}::()", XS_$self->{Packid}_nil$self->{file}$self->{proto}); MAKE_FETCHMETHOD_WORK } # print initialization routine print Q(<<"EOF"); ##ifdef __cplusplus #extern "C" ##endif EOF print Q(<<"EOF"); #XS_EXTERNAL(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */ #XS_EXTERNAL(boot_$self->{Module_cname}) #[[ ##if PERL_VERSION_LE(5, 21, 5) # dVAR; dXSARGS; ##else # dVAR; ${\($self->{WantVersionChk} ? 'dXSBOOTARGSXSAPIVERCHK;' : 'dXSBOOTARGSAPIVERCHK;')} ##endif EOF #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const #file name argument. If the wrong qualifier is used, it causes breakage with #C++ compilers and warnings with recent gcc. #-Wall: if there is no $self->{Full_func_name} there are no xsubs in this .xs #so 'file' is unused print Q(<<"EOF") if $self->{Full_func_name}; ##if (PERL_REVISION == 5 && PERL_VERSION < 9) # char* file = __FILE__; ##else # const char* file = __FILE__; ##endif # # PERL_UNUSED_VAR(file); EOF print Q("#\n"); print Q(<<"EOF"); # PERL_UNUSED_VAR(cv); /* -W */ # PERL_UNUSED_VAR(items); /* -W */ EOF if( $self->{WantVersionChk}){ print Q(<<"EOF") ; ##if PERL_VERSION_LE(5, 21, 5) # XS_VERSION_BOOTCHECK; ## ifdef XS_APIVERSION_BOOTCHECK # XS_APIVERSION_BOOTCHECK; ## endif ##endif EOF } else { print Q(<<"EOF") ; ##if PERL_VERSION_LE(5, 21, 5) && defined(XS_APIVERSION_BOOTCHECK) # XS_APIVERSION_BOOTCHECK; ##endif EOF } print Q(<<"EOF") if defined $self->{XsubAliases} or defined $self->{interfaces}; # { # CV * cv; # EOF print Q(<<"EOF") if ($self->{Overload}); # /* register the overloading (type 'A') magic */ ##if (PERL_REVISION == 5 && PERL_VERSION < 9) # PL_amagic_generation++; ##endif # /* The magic for overload gets a GV* via gv_fetchmeth as */ # /* mentioned above, and looks in the SV* slot of it for */ # /* the "fallback" status. */ # sv_setsv( # get_sv( "$self->{Package}::()", TRUE ), # $self->{Fallback} # ); EOF print @{ $self->{InitFileCode} }; print Q(<<"EOF") if defined $self->{XsubAliases} or defined $self->{interfaces}; # } EOF if (@{ $BootCode_ref }) { print "\n /* Initialisation Section */\n\n"; @{ $self->{line} } = @{ $BootCode_ref }; $self->print_section(); print "\n /* End of Initialisation Section */\n\n"; } print Q(<<'EOF'); ##if PERL_VERSION_LE(5, 21, 5) ## if PERL_VERSION_GE(5, 9, 0) # if (PL_unitcheckav) # call_list(PL_scopestack_ix, PL_unitcheckav); ## endif # XSRETURN_YES; ##else # Perl_xs_boot_epilog(aTHX_ ax); ##endif #]] # EOF warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n") unless $self->{ProtoUsed}; chdir($orig_cwd); select($orig_fh); untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT; close $self->{FH}; return 1; } sub report_error_count { if (@_) { return $_[0]->{errors}||0; } else { return $Singleton->{errors}||0; } } # Input: ($self, $_, @{ $self->{line} }) == unparsed input. # Output: ($_, @{ $self->{line} }) == (rest of line, following lines). # Return: the matched keyword if found, otherwise 0 sub check_keyword { my $self = shift; $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} }; s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2; } sub print_section { my $self = shift; # the "do" is required for right semantics do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} }; my $consumed_code = ''; print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"", escape_file_for_line_directive($self->{filepathname}), "\"\n") if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/; for (; defined($_) && !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { print "$_\n"; $consumed_code .= "$_\n"; } print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers}; return $consumed_code; } sub merge_section { my $self = shift; my $in = ''; while (!/\S/ && @{ $self->{line} }) { $_ = shift(@{ $self->{line} }); } for (; defined($_) && !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { $in .= "$_\n"; } chomp $in; return $in; } sub process_keyword { my($self, $pattern) = @_; while (my $kwd = $self->check_keyword($pattern)) { my $method = $kwd . "_handler"; $self->$method($_); } } sub CASE_handler { my $self = shift; $_ = shift; $self->blurt("Error: 'CASE:' after unconditional 'CASE:'") if $self->{condnum} && $self->{cond} eq ''; $self->{cond} = $_; trim_whitespace($self->{cond}); print " ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n"); $_ = ''; } sub INPUT_handler { my $self = shift; $_ = shift; for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { last if /^\s*NOT_IMPLEMENTED_YET/; next unless /\S/; # skip blank lines trim_whitespace($_); my $ln = $_; # remove trailing semicolon if no initialisation s/\s*;$//g unless /[=;+].*\S/; # Process the length(foo) declarations if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) { print "\tSTRLEN\tSTRLEN_length_of_$2;\n"; $self->{lengthof}->{$2} = undef; $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n"; } # check for optional initialisation code my $var_init = ''; $var_init = $1 if s/\s*([=;+].*)$//s; $var_init =~ s/"/\\"/g; # *sigh* It's valid to supply explicit input typemaps in the argument list... my $is_overridden_typemap = $var_init =~ /ST\s*\(|\$arg\b/; s/\s+/ /g; my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s or $self->blurt("Error: invalid argument declaration '$ln'"), next; # Check for duplicate definitions $self->blurt("Error: duplicate definition of argument '$var_name' ignored"), next if $self->{arg_list}->{$var_name}++ or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types}; $self->{thisdone} |= $var_name eq "THIS"; $self->{retvaldone} |= $var_name eq "RETVAL"; $self->{var_types}->{$var_name} = $var_type; # XXXX This check is a safeguard against the unfinished conversion of # generate_init(). When generate_init() is fixed, # one can use 2-args map_type() unconditionally. my $printed_name; if ($var_type =~ / \( \s* \* \s* \) /x) { # Function pointers are not yet supported with output_init()! print "\t" . map_type($self, $var_type, $var_name); $printed_name = 1; } else { print "\t" . map_type($self, $var_type, undef); $printed_name = 0; } $self->{var_num} = $self->{args_match}->{$var_name}; if ($self->{var_num}) { my $typemap = $self->{typemap}->get_typemap(ctype => $var_type); $self->report_typemap_failure($self->{typemap}, $var_type, "death") if not $typemap and not $is_overridden_typemap; $self->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$"; } $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr; if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/ or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/ and $var_init !~ /\S/) { if ($printed_name) { print ";\n"; } else { print "\t$var_name;\n"; } } elsif ($var_init =~ /\S/) { $self->output_init( { type => $var_type, num => $self->{var_num}, var => $var_name, init => $var_init, printed_name => $printed_name, } ); } elsif ($self->{var_num}) { $self->generate_init( { type => $var_type, num => $self->{var_num}, var => $var_name, printed_name => $printed_name, } ); } else { print ";\n"; } } } sub OUTPUT_handler { my $self = shift; $self->{have_OUTPUT} = 1; $_ = shift; for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { next unless /\S/; if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) { $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0); next; } my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s; $self->blurt("Error: duplicate OUTPUT argument '$outarg' ignored"), next if $self->{outargs}->{$outarg}++; if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') { # deal with RETVAL last $self->{RETVAL_code} = $outcode; $self->{gotRETVAL} = 1; next; } $self->blurt("Error: OUTPUT $outarg not an argument"), next unless defined($self->{args_match}->{$outarg}); $self->blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next unless defined $self->{var_types}->{$outarg}; $self->{var_num} = $self->{args_match}->{$outarg}; if ($outcode) { print "\t$outcode\n"; print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic}; } else { $self->generate_output( { type => $self->{var_types}->{$outarg}, num => $self->{var_num}, var => $outarg, do_setmagic => $self->{DoSetMagic}, do_push => undef, } ); } delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/; } } sub C_ARGS_handler { my $self = shift; $_ = shift; my $in = $self->merge_section(); trim_whitespace($in); $self->{func_args} = $in; } sub INTERFACE_MACRO_handler { my $self = shift; $_ = shift; my $in = $self->merge_section(); trim_whitespace($in); if ($in =~ /\s/) { # two ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in; } else { $self->{interface_macro} = $in; $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later } $self->{interface} = 1; # local $self->{interfaces} = 1; # global } sub INTERFACE_handler { my $self = shift; $_ = shift; my $in = $self->merge_section(); trim_whitespace($in); foreach (split /[\s,]+/, $in) { my $iface_name = $_; $iface_name =~ s/^$self->{Prefix}//; $self->{Interfaces}->{$iface_name} = $_; } print Q(<<"EOF"); # XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr); EOF $self->{interface} = 1; # local $self->{interfaces} = 1; # global } sub CLEANUP_handler { my $self = shift; $self->print_section(); } sub PREINIT_handler { my $self = shift; $self->print_section(); } sub POSTCALL_handler { my $self = shift; $self->print_section(); } sub INIT_handler { my $self = shift; $self->print_section(); } sub get_aliases { my $self = shift; my ($line) = @_; my ($orig) = $line; # Parse alias definitions # format is # alias = value alias = value ... while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) { my ($alias, $value) = ($1, $2); my $orig_alias = $alias; # check for optional package definition in the alias $alias = $self->{Packprefix} . $alias if $alias !~ /::/; # check for duplicate alias name & duplicate value Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'") if defined $self->{XsubAliases}->{$alias}; Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values") if $self->{XsubAliasValues}->{$value}; $self->{XsubAliases}->{$alias} = $value; $self->{XsubAliasValues}->{$value} = $orig_alias; } blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'") if $line; } sub ATTRS_handler { my $self = shift; $_ = shift; for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { next unless /\S/; trim_whitespace($_); push @{ $self->{Attributes} }, $_; } } sub ALIAS_handler { my $self = shift; $_ = shift; for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { next unless /\S/; trim_whitespace($_); $self->get_aliases($_) if $_; } } sub OVERLOAD_handler { my $self = shift; $_ = shift; for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { next unless /\S/; trim_whitespace($_); while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) { $self->{Overload} = 1 unless $self->{Overload}; my $overload = "$self->{Package}\::(".$1; push(@{ $self->{InitFileCode} }, " (void)$self->{newXS}(\"$overload\", XS_$self->{Full_func_name}$self->{file}$self->{proto});\n"); } } } sub FALLBACK_handler { my ($self, $setting) = @_; # the rest of the current line should contain either TRUE, # FALSE or UNDEF trim_whitespace($setting); $setting = uc($setting); my %map = ( TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes", FALSE => "&PL_sv_no", 0 => "&PL_sv_no", UNDEF => "&PL_sv_undef", ); # check for valid FALLBACK value $self->death("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{$setting}; $self->{Fallback} = $map{$setting}; } sub REQUIRE_handler { # the rest of the current line should contain a version number my ($self, $ver) = @_; trim_whitespace($ver); $self->death("Error: REQUIRE expects a version number") unless $ver; # check that the version number is of the form n.n $self->death("Error: REQUIRE: expected a number, got '$ver'") unless $ver =~ /^\d+(\.\d*)?/; $self->death("Error: xsubpp $ver (or better) required--this is only $VERSION.") unless $VERSION >= $ver; } sub VERSIONCHECK_handler { # the rest of the current line should contain either ENABLE or # DISABLE my ($self, $setting) = @_; trim_whitespace($setting); # check for ENABLE/DISABLE $self->death("Error: VERSIONCHECK: ENABLE/DISABLE") unless $setting =~ /^(ENABLE|DISABLE)/i; $self->{WantVersionChk} = 1 if $1 eq 'ENABLE'; $self->{WantVersionChk} = 0 if $1 eq 'DISABLE'; } sub PROTOTYPE_handler { my $self = shift; $_ = shift; my $specified; $self->death("Error: Only 1 PROTOTYPE definition allowed per xsub") if $self->{proto_in_this_xsub}++; for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) { next unless /\S/; $specified = 1; trim_whitespace($_); if ($_ eq 'DISABLE') { $self->{ProtoThisXSUB} = 0; } elsif ($_ eq 'ENABLE') { $self->{ProtoThisXSUB} = 1; } else { # remove any whitespace s/\s+//g; $self->death("Error: Invalid prototype '$_'") unless valid_proto_string($_); $self->{ProtoThisXSUB} = C_string($_); } } # If no prototype specified, then assume empty prototype "" $self->{ProtoThisXSUB} = 2 unless $specified; $self->{ProtoUsed} = 1; } sub SCOPE_handler { # Rest of line should be either ENABLE or DISABLE my ($self, $setting) = @_; $self->death("Error: Only 1 SCOPE declaration allowed per xsub") if $self->{scope_in_this_xsub}++; trim_whitespace($setting); $self->death("Error: SCOPE: ENABLE/DISABLE") unless $setting =~ /^(ENABLE|DISABLE)\b/i; $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' ); } sub PROTOTYPES_handler { # the rest of the current line should contain either ENABLE or # DISABLE my ($self, $setting) = @_; trim_whitespace($setting); # check for ENABLE/DISABLE $self->death("Error: PROTOTYPES: ENABLE/DISABLE") unless $setting =~ /^(ENABLE|DISABLE)/i; $self->{WantPrototypes} = 1 if $1 eq 'ENABLE'; $self->{WantPrototypes} = 0 if $1 eq 'DISABLE'; $self->{ProtoUsed} = 1; } sub EXPORT_XSUB_SYMBOLS_handler { # the rest of the current line should contain either ENABLE or # DISABLE my ($self, $setting) = @_; trim_whitespace($setting); # check for ENABLE/DISABLE $self->death("Error: EXPORT_XSUB_SYMBOLS: ENABLE/DISABLE") unless $setting =~ /^(ENABLE|DISABLE)/i; my $xs_impl = $1 eq 'ENABLE' ? 'XS_EXTERNAL' : 'XS_INTERNAL'; print Q(<<"EOF"); ##undef XS_EUPXS ##if defined(PERL_EUPXS_ALWAYS_EXPORT) ## define XS_EUPXS(name) XS_EXTERNAL(name) ##elif defined(PERL_EUPXS_NEVER_EXPORT) ## define XS_EUPXS(name) XS_INTERNAL(name) ##else ## define XS_EUPXS(name) $xs_impl(name) ##endif EOF } sub PushXSStack { my $self = shift; my %args = @_; # Save the current file context. push(@{ $self->{XSStack} }, { type => 'file', LastLine => $self->{lastline}, LastLineNo => $self->{lastline_no}, Line => $self->{line}, LineNo => $self->{line_no}, Filename => $self->{filename}, Filepathname => $self->{filepathname}, Handle => $self->{FH}, IsPipe => scalar($self->{filename} =~ /\|\s*$/), %args, }); } sub INCLUDE_handler { my $self = shift; $_ = shift; # the rest of the current line should contain a valid filename trim_whitespace($_); $self->death("INCLUDE: filename missing") unless $_; $self->death("INCLUDE: output pipe is illegal") if /^\s*\|/; # simple minded recursion detector $self->death("INCLUDE loop detected") if $self->{IncludedFiles}->{$_}; ++$self->{IncludedFiles}->{$_} unless /\|\s*$/; if (/\|\s*$/ && /^\s*perl\s/) { Warn( $self, "The INCLUDE directive with a command is discouraged." . " Use INCLUDE_COMMAND instead! In particular using 'perl'" . " in an 'INCLUDE: ... |' directive is not guaranteed to pick" . " up the correct perl. The INCLUDE_COMMAND directive allows" . " the use of \$^X as the currently running perl, see" . " 'perldoc perlxs' for details."); } $self->PushXSStack(); $self->{FH} = Symbol::gensym(); # open the new file open($self->{FH}, $_) or $self->death("Cannot open '$_': $!"); print Q(<<"EOF"); # #/* INCLUDE: Including '$_' from '$self->{filename}' */ # EOF $self->{filename} = $_; $self->{filepathname} = ( $^O =~ /^mswin/i ) ? qq($self->{dir}/$self->{filename}) # See CPAN RT #61908: gcc doesn't like backslashes on win32? : File::Spec->catfile($self->{dir}, $self->{filename}); # Prime the pump by reading the first # non-blank line # skip leading blank lines while (readline($self->{FH})) { last unless /^\s*$/; } $self->{lastline} = $_; $self->{lastline_no} = $.; } sub QuoteArgs { my $cmd = shift; my @args = split /\s+/, $cmd; $cmd = shift @args; for (@args) { $_ = q(").$_.q(") if !/^\"/ && length($_) > 0; } return join (' ', ($cmd, @args)); } # code copied from CPAN::HandleConfig::safe_quote # - that has doc saying leave if start/finish with same quote, but no code # given text, will conditionally quote it to protect from shell { my ($quote, $use_quote) = $^O eq 'MSWin32' ? (q{"}, q{"}) : (q{"'}, q{'}); sub _safe_quote { my ($self, $command) = @_; # Set up quote/default quote if (defined($command) and $command =~ /\s/ and $command !~ /[$quote]/) { return qq{$use_quote$command$use_quote} } return $command; } } sub INCLUDE_COMMAND_handler { my $self = shift; $_ = shift; # the rest of the current line should contain a valid command trim_whitespace($_); $_ = QuoteArgs($_) if $^O eq 'VMS'; $self->death("INCLUDE_COMMAND: command missing") unless $_; $self->death("INCLUDE_COMMAND: pipes are illegal") if /^\s*\|/ or /\|\s*$/; $self->PushXSStack( IsPipe => 1 ); $self->{FH} = Symbol::gensym(); # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be # the same perl interpreter as we're currently running my $X = $self->_safe_quote($^X); # quotes if has spaces s/^\s*\$\^X/$X/; # open the new file open ($self->{FH}, "-|", $_) or $self->death( $self, "Cannot run command '$_' to include its output: $!"); print Q(<<"EOF"); # #/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */ # EOF $self->{filename} = $_; $self->{filepathname} = $self->{filename}; #$self->{filepathname} =~ s/\"/\\"/g; # Fails? See CPAN RT #53938: MinGW Broken after 2.21 $self->{filepathname} =~ s/\\/\\\\/g; # Works according to reporter of #53938 # Prime the pump by reading the first # non-blank line # skip leading blank lines while (readline($self->{FH})) { last unless /^\s*$/; } $self->{lastline} = $_; $self->{lastline_no} = $.; } sub PopFile { my $self = shift; return 0 unless $self->{XSStack}->[-1]{type} eq 'file'; my $data = pop @{ $self->{XSStack} }; my $ThisFile = $self->{filename}; my $isPipe = $data->{IsPipe}; --$self->{IncludedFiles}->{$self->{filename}} unless $isPipe; close $self->{FH}; $self->{FH} = $data->{Handle}; # $filename is the leafname, which for some reason is used for diagnostic # messages, whereas $filepathname is the full pathname, and is used for # #line directives. $self->{filename} = $data->{Filename}; $self->{filepathname} = $data->{Filepathname}; $self->{lastline} = $data->{LastLine}; $self->{lastline_no} = $data->{LastLineNo}; @{ $self->{line} } = @{ $data->{Line} }; @{ $self->{line_no} } = @{ $data->{LineNo} }; if ($isPipe and $? ) { --$self->{lastline_no}; print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ; exit 1; } print Q(<<"EOF"); # #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */ # EOF return 1; } sub Q { my($text) = @_; $text =~ s/^#//gm; $text =~ s/\[\[/{/g; $text =~ s/\]\]/}/g; $text; } # Process "MODULE = Foo ..." lines and update global state accordingly sub _process_module_xs_line { my ($self, $module, $pkg, $prefix) = @_; ($self->{Module_cname} = $module) =~ s/\W/_/g; $self->{Package} = defined($pkg) ? $pkg : ''; $self->{Prefix} = quotemeta( defined($prefix) ? $prefix : '' ); ($self->{Packid} = $self->{Package}) =~ tr/:/_/; $self->{Packprefix} = $self->{Package}; $self->{Packprefix} .= "::" if $self->{Packprefix} ne ""; $self->{lastline} = ""; } # Skip any embedded POD sections sub _maybe_skip_pod { my ($self) = @_; while ($self->{lastline} =~ /^=/) { while ($self->{lastline} = readline($self->{FH})) { last if ($self->{lastline} =~ /^=cut\s*$/); } $self->death("Error: Unterminated pod") unless defined $self->{lastline}; $self->{lastline} = readline($self->{FH}); chomp $self->{lastline}; $self->{lastline} =~ s/^\s+$//; } } # This chunk of code strips out (and parses) embedded TYPEMAP blocks # which support a HEREdoc-alike block syntax. sub _maybe_parse_typemap_block { my ($self) = @_; # This is special cased from the usual paragraph-handler logic # due to the HEREdoc-ish syntax. if ($self->{lastline} =~ /^TYPEMAP\s*:\s*<<\s*(?:(["'])(.+?)\1|([^\s'"]+?))\s*;?\s*$/) { my $end_marker = quotemeta(defined($1) ? $2 : $3); # Scan until we find $end_marker alone on a line. my @tmaplines; while (1) { $self->{lastline} = readline($self->{FH}); $self->death("Error: Unterminated TYPEMAP section") if not defined $self->{lastline}; last if $self->{lastline} =~ /^$end_marker\s*$/; push @tmaplines, $self->{lastline}; } my $tmap = ExtUtils::Typemaps->new( string => join("", @tmaplines), lineno_offset => 1 + ($self->current_line_number() || 0), fake_filename => $self->{filename}, ); $self->{typemap}->merge(typemap => $tmap, replace => 1); $self->{lastline} = ""; } } # Read next xsub into @{ $self->{line} } from ($lastline, readline($self->{FH})). sub fetch_para { my $self = shift; # parse paragraph $self->death("Error: Unterminated '#if/#ifdef/#ifndef'") if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if'; @{ $self->{line} } = (); @{ $self->{line_no} } = (); return $self->PopFile() if not defined $self->{lastline}; # EOF if ($self->{lastline} =~ /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) { $self->_process_module_xs_line($1, $2, $3); } for (;;) { $self->_maybe_skip_pod; $self->_maybe_parse_typemap_block; if ($self->{lastline} !~ /^\s*#/ # not a CPP directive # CPP directives: # ANSI: if ifdef ifndef elif else endif define undef # line error pragma # gcc: warning include_next # obj-c: import # others: ident (gcc notes that some cpps have this one) || $self->{lastline} =~ /^\#[ \t]* (?: (?:if|ifn?def|elif|else|endif| define|undef|pragma|error| warning|line\s+\d+|ident) \b | (?:include(?:_next)?|import) \s* ["<] .* [>"] ) /x ) { last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq ""; push(@{ $self->{line} }, $self->{lastline}); push(@{ $self->{line_no} }, $self->{lastline_no}); } # Read next line and continuation lines last unless defined($self->{lastline} = readline($self->{FH})); $self->{lastline_no} = $.; my $tmp_line; $self->{lastline} .= $tmp_line while ($self->{lastline} =~ /\\$/ && defined($tmp_line = readline($self->{FH}))); chomp $self->{lastline}; $self->{lastline} =~ s/^\s+$//; } # Nuke trailing "line" entries until there's one that's not empty pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq ""; return 1; } sub output_init { my $self = shift; my $argsref = shift; my ($type, $num, $var, $init, $printed_name) = @{$argsref}{qw(type num var init printed_name)}; # local assign for efficiently passing in to eval_input_typemap_code local $argsref->{arg} = $num ? "ST(" . ($num-1) . ")" : "/* not a parameter */"; if ( $init =~ /^=/ ) { if ($printed_name) { $self->eval_input_typemap_code(qq/print " $init\\n"/, $argsref); } else { $self->eval_input_typemap_code(qq/print "\\t$var $init\\n"/, $argsref); } } else { if ( $init =~ s/^\+// && $num ) { $self->generate_init( { type => $type, num => $num, var => $var, printed_name => $printed_name, } ); } elsif ($printed_name) { print ";\n"; $init =~ s/^;//; } else { $self->eval_input_typemap_code(qq/print "\\t$var;\\n"/, $argsref); $init =~ s/^;//; } $self->{deferred} .= $self->eval_input_typemap_code(qq/"\\n\\t$init\\n"/, $argsref); } } sub generate_init { my $self = shift; my $argsref = shift; my ($type, $num, $var, $printed_name) = @{$argsref}{qw(type num var printed_name)}; my $argoff = $num - 1; my $arg = "ST($argoff)"; my $typemaps = $self->{typemap}; $type = ExtUtils::Typemaps::tidy_type($type); if (not $typemaps->get_typemap(ctype => $type)) { $self->report_typemap_failure($typemaps, $type); return; } (my $ntype = $type) =~ s/\s*\*/Ptr/g; (my $subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//; my $typem = $typemaps->get_typemap(ctype => $type); my $xstype = $typem->xstype; #this is an optimization from perl 5.0 alpha 6, class check is skipped #T_REF_IV_REF is missing since it has no untyped analog at the moment $xstype =~ s/OBJ$/REF/ || $xstype =~ s/^T_REF_IV_PTR$/T_PTRREF/ if $self->{func_name} =~ /DESTROY$/; if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) { print "\t$var" unless $printed_name; print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n"; die "default value not supported with length(NAME) supplied" if defined $self->{defaults}->{$var}; return; } $type =~ tr/:/_/ unless $self->{RetainCplusplusHierarchicalTypes}; my $inputmap = $typemaps->get_inputmap(xstype => $xstype); if (not defined $inputmap) { $self->blurt("Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found"); return; } my $expr = $inputmap->cleaned_code; # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen if ($expr =~ /DO_ARRAY_ELEM/) { my $subtypemap = $typemaps->get_typemap(ctype => $subtype); if (not $subtypemap) { $self->report_typemap_failure($typemaps, $subtype); return; } my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype); if (not $subinputmap) { $self->blurt("Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"); return; } my $subexpr = $subinputmap->cleaned_code; $subexpr =~ s/\$type/\$subtype/g; $subexpr =~ s/ntype/subtype/g; $subexpr =~ s/\$arg/ST(ix_$var)/g; $subexpr =~ s/\n\t/\n\t\t/g; $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g; $subexpr =~ s/\$var/${var}\[ix_$var - $argoff]/; $expr =~ s/DO_ARRAY_ELEM/$subexpr/; } if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments $self->{ScopeThisXSUB} = 1; } my $eval_vars = { var => $var, printed_name => $printed_name, type => $type, ntype => $ntype, subtype => $subtype, num => $num, arg => $arg, argoff => $argoff, }; if (defined($self->{defaults}->{$var})) { $expr =~ s/(\t+)/$1 /g; $expr =~ s/ /\t/g; if ($printed_name) { print ";\n"; } else { $self->eval_input_typemap_code(qq/print "\\t$var;\\n"/, $eval_vars); } if ($self->{defaults}->{$var} eq 'NO_INIT') { $self->{deferred} .= $self->eval_input_typemap_code( qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/, $eval_vars ); } else { $self->{deferred} .= $self->eval_input_typemap_code( qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/, $eval_vars ); } } elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) { if ($printed_name) { print ";\n"; } else { $self->eval_input_typemap_code(qq/print "\\t$var;\\n"/, $eval_vars); } $self->{deferred} .= $self->eval_input_typemap_code(qq/"\\n$expr;\\n"/, $eval_vars); } else { die "panic: do not know how to handle this branch for function pointers" if $printed_name; $self->eval_input_typemap_code(qq/print "$expr;\\n"/, $eval_vars); } } sub generate_output { my $self = shift; my $argsref = shift; my ($type, $num, $var, $do_setmagic, $do_push) = @{$argsref}{qw(type num var do_setmagic do_push)}; my $arg = "ST(" . ($num - ($num != 0)) . ")"; my $typemaps = $self->{typemap}; $type = ExtUtils::Typemaps::tidy_type($type); local $argsref->{type} = $type; if ($type =~ /^array\(([^,]*),(.*)\)/) { print "\t$arg = sv_newmortal();\n"; print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n"; print "\tSvSETMAGIC($arg);\n" if $do_setmagic; } else { my $typemap = $typemaps->get_typemap(ctype => $type); if (not $typemap) { $self->report_typemap_failure($typemaps, $type); return; } my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype); if (not $outputmap) { $self->blurt("Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"); return; } (my $ntype = $type) =~ s/\s*\*/Ptr/g; $ntype =~ s/\(\)//g; (my $subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//; my $eval_vars = {%$argsref, subtype => $subtype, ntype => $ntype, arg => $arg}; my $expr = $outputmap->cleaned_code; if ($expr =~ /DO_ARRAY_ELEM/) { my $subtypemap = $typemaps->get_typemap(ctype => $subtype); if (not $subtypemap) { $self->report_typemap_failure($typemaps, $subtype); return; } my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype); if (not $suboutputmap) { $self->blurt("Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"); return; } my $subexpr = $suboutputmap->cleaned_code; $subexpr =~ s/ntype/subtype/g; $subexpr =~ s/\$arg/ST(ix_$var)/g; $subexpr =~ s/\$var/${var}\[ix_$var]/g; $subexpr =~ s/\n\t/\n\t\t/g; $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/; $self->eval_output_typemap_code("print qq\a$expr\a", $eval_vars); print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic; } elsif ($var eq 'RETVAL') { my $orig_arg = $arg; my $indent; my $use_RETVALSV = 1; my $do_mortal = 0; my $do_copy_tmp = 1; my $pre_expr; local $eval_vars->{arg} = $arg = 'RETVALSV'; my $evalexpr = $self->eval_output_typemap_code("qq\a$expr\a", $eval_vars); if ($expr =~ /^\t\Q$arg\E = new/) { # We expect that $arg has refcnt 1, so we need to # mortalize it. $do_mortal = 1; } # If RETVAL is immortal, don't mortalize it. This code is not perfect: # It won't detect a func or expression that only returns immortals, for # example, this RE must be tried before next elsif. elsif ($evalexpr =~ /^\t\Q$arg\E\s*=\s*(boolSV\(|(&PL_sv_yes|&PL_sv_no|&PL_sv_undef)\s*;)/) { $do_copy_tmp = 0; #$arg will be a ST(X), no SV* RETVAL, no RETVALSV $use_RETVALSV = 0; } elsif ($evalexpr =~ /^\s*\Q$arg\E\s*=/) { # We expect that $arg has refcnt >=1, so we need # to mortalize it! $use_RETVALSV = 0 if $ntype eq "SVPtr";#reuse SV* RETVAL vs open new block $do_mortal = 1; } else { # Just hope that the entry would safely write it # over an already mortalized value. By # coincidence, something like $arg = &PL_sv_undef # works too, but should be caught above. $pre_expr = "RETVALSV = sv_newmortal();\n"; # new mortals don't have set magic $do_setmagic = 0; } if($use_RETVALSV) { print "\t{\n\t SV * RETVALSV;\n"; $indent = "\t "; } else { $indent = "\t"; } print $indent.$pre_expr if $pre_expr; if($use_RETVALSV) { #take control of 1 layer of indent, may or may not indent more $evalexpr =~ s/^(\t| )/$indent/gm; #"\t \t" doesn't draw right in some IDEs #break down all \t into spaces $evalexpr =~ s/\t/ /g; #rebuild back into \t'es, \t==8 spaces, indent==4 spaces $evalexpr =~ s/ /\t/g; } else { if($do_mortal || $do_setmagic) { #typemap entry evaled with RETVALSV, if we aren't using RETVALSV replace $evalexpr =~ s/RETVALSV/RETVAL/g; #all uses with RETVAL for prettier code } else { #if no extra boilerplate (no mortal, no set magic) is needed #after $evalexport, get rid of RETVALSV's visual cluter and change $evalexpr =~ s/RETVALSV/$orig_arg/g;#the lvalue to ST(X) } } #stop " RETVAL = RETVAL;" for SVPtr type print $evalexpr if $evalexpr !~ /^\s*RETVAL = RETVAL;$/; print $indent.'RETVAL'.($use_RETVALSV ? 'SV':'') .' = sv_2mortal(RETVAL'.($use_RETVALSV ? 'SV':'').");\n" if $do_mortal; print $indent.'SvSETMAGIC(RETVAL'.($use_RETVALSV ? 'SV':'').");\n" if $do_setmagic; #dont do "RETVALSV = boolSV(RETVAL); ST(0) = RETVALSV;", it is visual clutter print $indent."$orig_arg = RETVAL".($use_RETVALSV ? 'SV':'').";\n" if $do_mortal || $do_setmagic || $do_copy_tmp; print "\t}\n" if $use_RETVALSV; } elsif ($do_push) { print "\tPUSHs(sv_newmortal());\n"; local $eval_vars->{arg} = "ST($num)"; $self->eval_output_typemap_code("print qq\a$expr\a", $eval_vars); print "\tSvSETMAGIC($arg);\n" if $do_setmagic; } elsif ($arg =~ /^ST\(\d+\)$/) { $self->eval_output_typemap_code("print qq\a$expr\a", $eval_vars); print "\tSvSETMAGIC($arg);\n" if $do_setmagic; } } } # Just delegates to a clean package. # Shim to evaluate Perl code in the right variable context # for typemap code (having things such as $ALIAS set up). sub eval_output_typemap_code { my ($self, $code, $other) = @_; return ExtUtils::ParseXS::Eval::eval_output_typemap_code($self, $code, $other); } sub eval_input_typemap_code { my ($self, $code, $other) = @_; return ExtUtils::ParseXS::Eval::eval_input_typemap_code($self, $code, $other); } 1; # vim: ts=2 sw=2 et: PK!጑¤¤perl5/ExtUtils/MY.pmnuÏÃ6Ç$package ExtUtils::MY; use strict; require ExtUtils::MM; our $VERSION = '7.50'; $VERSION =~ tr/_//d; our @ISA = qw(ExtUtils::MM); { package MY; our @ISA = qw(ExtUtils::MY); } sub DESTROY {} =head1 NAME ExtUtils::MY - ExtUtils::MakeMaker subclass for customization =head1 SYNOPSIS # in your Makefile.PL sub MY::whatever { ... } =head1 DESCRIPTION B ExtUtils::MY is a subclass of L. Its provided in your Makefile.PL for you to add and override MakeMaker functionality. It also provides a convenient alias via the MY class. ExtUtils::MY might turn out to be a temporary solution, but MY won't go away. =cut PK!yEüV%%%%perl5/ExtUtils/Liblist.pmnuÏÃ6Ç$package ExtUtils::Liblist; use strict; use warnings; our $VERSION = '7.50'; $VERSION =~ tr/_//d; use File::Spec; require ExtUtils::Liblist::Kid; our @ISA = qw(ExtUtils::Liblist::Kid File::Spec); # Backwards compatibility with old interface. sub ext { goto &ExtUtils::Liblist::Kid::ext; } sub lsdir { shift; my $rex = qr/$_[1]/; opendir my $dir_fh, $_[0]; my @out = grep /$rex/, readdir $dir_fh; closedir $dir_fh; return @out; } __END__ =head1 NAME ExtUtils::Liblist - determine libraries to use and how to use them =head1 SYNOPSIS require ExtUtils::Liblist; $MM->ext($potential_libs, $verbose, $need_names); # Usually you can get away with: ExtUtils::Liblist->ext($potential_libs, $verbose, $need_names) =head1 DESCRIPTION This utility takes a list of libraries in the form C<-llib1 -llib2 -llib3> and returns lines suitable for inclusion in an extension Makefile. Extra library paths may be included with the form C<-L/another/path> this will affect the searches for all subsequent libraries. It returns an array of four or five scalar values: EXTRALIBS, BSLOADLIBS, LDLOADLIBS, LD_RUN_PATH, and, optionally, a reference to the array of the filenames of actual libraries. Some of these don't mean anything unless on Unix. See the details about those platform specifics below. The list of the filenames is returned only if $need_names argument is true. Dependent libraries can be linked in one of three ways: =over 2 =item * For static extensions by the ld command when the perl binary is linked with the extension library. See EXTRALIBS below. =item * For dynamic extensions at build/link time by the ld command when the shared object is built/linked. See LDLOADLIBS below. =item * For dynamic extensions at load time by the DynaLoader when the shared object is loaded. See BSLOADLIBS below. =back =head2 EXTRALIBS List of libraries that need to be linked with when linking a perl binary which includes this extension. Only those libraries that actually exist are included. These are written to a file and used when linking perl. =head2 LDLOADLIBS and LD_RUN_PATH List of those libraries which can or must be linked into the shared library when created using ld. These may be static or dynamic libraries. LD_RUN_PATH is a colon separated list of the directories in LDLOADLIBS. It is passed as an environment variable to the process that links the shared library. =head2 BSLOADLIBS List of those libraries that are needed but can be linked in dynamically at run time on this platform. SunOS/Solaris does not need this because ld records the information (from LDLOADLIBS) into the object file. This list is used to create a .bs (bootstrap) file. =head1 PORTABILITY This module deals with a lot of system dependencies and has quite a few architecture specific Cs in the code. =head2 VMS implementation The version of ext() which is executed under VMS differs from the Unix-OS/2 version in several respects: =over 2 =item * Input library and path specifications are accepted with or without the C<-l> and C<-L> prefixes used by Unix linkers. If neither prefix is present, a token is considered a directory to search if it is in fact a directory, and a library to search for otherwise. Authors who wish their extensions to be portable to Unix or OS/2 should use the Unix prefixes, since the Unix-OS/2 version of ext() requires them. =item * Wherever possible, shareable images are preferred to object libraries, and object libraries to plain object files. In accordance with VMS naming conventions, ext() looks for files named Ishr and Irtl; it also looks for Ilib and libI to accommodate Unix conventions used in some ported software. =item * For each library that is found, an appropriate directive for a linker options file is generated. The return values are space-separated strings of these directives, rather than elements used on the linker command line. =item * LDLOADLIBS contains both the libraries found based on C<$potential_libs> and the CRTLs, if any, specified in Config.pm. EXTRALIBS contains just those libraries found based on C<$potential_libs>. BSLOADLIBS and LD_RUN_PATH are always empty. =back In addition, an attempt is made to recognize several common Unix library names, and filter them out or convert them to their VMS equivalents, as appropriate. In general, the VMS version of ext() should properly handle input from extensions originally designed for a Unix or VMS environment. If you encounter problems, or discover cases where the search could be improved, please let us know. =head2 Win32 implementation The version of ext() which is executed under Win32 differs from the Unix-OS/2 version in several respects: =over 2 =item * If C<$potential_libs> is empty, the return value will be empty. Otherwise, the libraries specified by C<$Config{perllibs}> (see Config.pm) will be appended to the list of C<$potential_libs>. The libraries will be searched for in the directories specified in C<$potential_libs>, C<$Config{libpth}>, and in C<$Config{installarchlib}/CORE>. For each library that is found, a space-separated list of fully qualified library pathnames is generated. =item * Input library and path specifications are accepted with or without the C<-l> and C<-L> prefixes used by Unix linkers. An entry of the form C<-La:\foo> specifies the C directory to look for the libraries that follow. An entry of the form C<-lfoo> specifies the library C, which may be spelled differently depending on what kind of compiler you are using. If you are using GCC, it gets translated to C, but for other win32 compilers, it becomes C. If no files are found by those translated names, one more attempt is made to find them using either C or C, depending on whether GCC or some other win32 compiler is being used, respectively. If neither the C<-L> or C<-l> prefix is present in an entry, the entry is considered a directory to search if it is in fact a directory, and a library to search for otherwise. The C<$Config{lib_ext}> suffix will be appended to any entries that are not directories and don't already have the suffix. Note that the C<-L> and C<-l> prefixes are B, but authors who wish their extensions to be portable to Unix or OS/2 should use the prefixes, since the Unix-OS/2 version of ext() requires them. =item * Entries cannot be plain object files, as many Win32 compilers will not handle object files in the place of libraries. =item * Entries in C<$potential_libs> beginning with a colon and followed by alphanumeric characters are treated as flags. Unknown flags will be ignored. An entry that matches C disables the appending of default libraries found in C<$Config{perllibs}> (this should be only needed very rarely). An entry that matches C disables all searching for the libraries specified after it. Translation of C<-Lfoo> and C<-lfoo> still happens as appropriate (depending on compiler being used, as reflected by C<$Config{cc}>), but the entries are not verified to be valid files or directories. An entry that matches C reenables searching for the libraries specified after it. You can put it at the end to enable searching for default libraries specified by C<$Config{perllibs}>. =item * The libraries specified may be a mixture of static libraries and import libraries (to link with DLLs). Since both kinds are used pretty transparently on the Win32 platform, we do not attempt to distinguish between them. =item * LDLOADLIBS and EXTRALIBS are always identical under Win32, and BSLOADLIBS and LD_RUN_PATH are always empty (this may change in future). =item * You must make sure that any paths and path components are properly surrounded with double-quotes if they contain spaces. For example, C<$potential_libs> could be (literally): "-Lc:\Program Files\vc\lib" msvcrt.lib "la test\foo bar.lib" Note how the first and last entries are protected by quotes in order to protect the spaces. =item * Since this module is most often used only indirectly from extension C files, here is an example C entry to add a library to the build process for an extension: LIBS => ['-lgl'] When using GCC, that entry specifies that MakeMaker should first look for C (followed by C) in all the locations specified by C<$Config{libpth}>. When using a compiler other than GCC, the above entry will search for C (followed by C). If the library happens to be in a location not in C<$Config{libpth}>, you need: LIBS => ['-Lc:\gllibs -lgl'] Here is a less often used example: LIBS => ['-lgl', ':nosearch -Ld:\mesalibs -lmesa -luser32'] This specifies a search for library C as before. If that search fails to find the library, it looks at the next item in the list. The C<:nosearch> flag will prevent searching for the libraries that follow, so it simply returns the value as C<-Ld:\mesalibs -lmesa -luser32>, since GCC can use that value as is with its linker. When using the Visual C compiler, the second item is returned as C<-libpath:d:\mesalibs mesa.lib user32.lib>. When using the Borland compiler, the second item is returned as C<-Ld:\mesalibs mesa.lib user32.lib>, and MakeMaker takes care of moving the C<-Ld:\mesalibs> to the correct place in the linker command line. =back =head1 SEE ALSO L =cut PK!C@âöF F perl5/ExtUtils/ParseXS/Eval.pmnuÏÃ6Ç$package ExtUtils::ParseXS::Eval; use strict; use warnings; our $VERSION = '3.35'; =head1 NAME ExtUtils::ParseXS::Eval - Clean package to evaluate code in =head1 SYNOPSIS use ExtUtils::ParseXS::Eval; my $rv = ExtUtils::ParseXS::Eval::eval_typemap_code( $parsexs_obj, "some Perl code" ); =head1 SUBROUTINES =head2 $pxs->eval_output_typemap_code($typemapcode, $other_hashref) Sets up various bits of previously global state (formerly ExtUtils::ParseXS package variables) for eval'ing output typemap code that may refer to these variables. Warns the contents of C<$@> if any. Not all these variables are necessarily considered "public" wrt. use in typemaps, so beware. Variables set up from the ExtUtils::ParseXS object: $Package $Alias $func_name $Full_func_name $pname Variables set up from C<$other_hashref>: $var $type $ntype $subtype $arg =cut sub eval_output_typemap_code { my ($_pxs, $_code, $_other) = @_; my ($Package, $ALIAS, $func_name, $Full_func_name, $pname) = @{$_pxs}{qw(Package ALIAS func_name Full_func_name pname)}; my ($var, $type, $ntype, $subtype, $arg) = @{$_other}{qw(var type ntype subtype arg)}; my $rv = eval $_code; warn $@ if $@; return $rv; } =head2 $pxs->eval_input_typemap_code($typemapcode, $other_hashref) Sets up various bits of previously global state (formerly ExtUtils::ParseXS package variables) for eval'ing output typemap code that may refer to these variables. Warns the contents of C<$@> if any. Not all these variables are necessarily considered "public" wrt. use in typemaps, so beware. Variables set up from the ExtUtils::ParseXS object: $Package $Alias $func_name $Full_func_name $pname Variables set up from C<$other_hashref>: $var $type $ntype $subtype $num $init $printed_name $arg $argoff =cut sub eval_input_typemap_code { my ($_pxs, $_code, $_other) = @_; my ($Package, $ALIAS, $func_name, $Full_func_name, $pname) = @{$_pxs}{qw(Package ALIAS func_name Full_func_name pname)}; my ($var, $type, $num, $init, $printed_name, $arg, $ntype, $argoff, $subtype) = @{$_other}{qw(var type num init printed_name arg ntype argoff subtype)}; my $rv = eval $_code; warn $@ if $@; return $rv; } =head1 TODO Eventually, with better documentation and possible some cleanup, this could be part of C. =cut 1; # vim: ts=2 sw=2 et: PK!àÇÚ CC#perl5/ExtUtils/ParseXS/Utilities.pmnuÏÃ6Ç$package ExtUtils::ParseXS::Utilities; use strict; use warnings; use Exporter; use File::Spec; use ExtUtils::ParseXS::Constants (); our $VERSION = '3.35'; our (@ISA, @EXPORT_OK); @ISA = qw(Exporter); @EXPORT_OK = qw( standard_typemap_locations trim_whitespace C_string valid_proto_string process_typemaps map_type standard_XS_defs assign_func_args analyze_preprocessor_statements set_cond Warn current_line_number blurt death check_conditional_preprocessor_statements escape_file_for_line_directive report_typemap_failure ); =head1 NAME ExtUtils::ParseXS::Utilities - Subroutines used with ExtUtils::ParseXS =head1 SYNOPSIS use ExtUtils::ParseXS::Utilities qw( standard_typemap_locations trim_whitespace C_string valid_proto_string process_typemaps map_type standard_XS_defs assign_func_args analyze_preprocessor_statements set_cond Warn blurt death check_conditional_preprocessor_statements escape_file_for_line_directive report_typemap_failure ); =head1 SUBROUTINES The following functions are not considered to be part of the public interface. They are documented here for the benefit of future maintainers of this module. =head2 C =over 4 =item * Purpose Provide a list of filepaths where F files may be found. The filepaths -- relative paths to files (not just directory paths) -- appear in this list in lowest-to-highest priority. The highest priority is to look in the current directory. 'typemap' The second and third highest priorities are to look in the parent of the current directory and a directory called F underneath the parent directory. '../typemap', '../lib/ExtUtils/typemap', The fourth through ninth highest priorities are to look in the corresponding grandparent, great-grandparent and great-great-grandparent directories. '../../typemap', '../../lib/ExtUtils/typemap', '../../../typemap', '../../../lib/ExtUtils/typemap', '../../../../typemap', '../../../../lib/ExtUtils/typemap', The tenth and subsequent priorities are to look in directories named F which are subdirectories of directories found in C<@INC> -- I a file named F actually exists in such a directory. Example: '/usr/local/lib/perl5/5.10.1/ExtUtils/typemap', However, these filepaths appear in the list returned by C in reverse order, I, lowest-to-highest. '/usr/local/lib/perl5/5.10.1/ExtUtils/typemap', '../../../../lib/ExtUtils/typemap', '../../../../typemap', '../../../lib/ExtUtils/typemap', '../../../typemap', '../../lib/ExtUtils/typemap', '../../typemap', '../lib/ExtUtils/typemap', '../typemap', 'typemap' =item * Arguments my @stl = standard_typemap_locations( \@INC ); Reference to C<@INC>. =item * Return Value Array holding list of directories to be searched for F files. =back =cut SCOPE: { my @tm_template; sub standard_typemap_locations { my $include_ref = shift; if (not @tm_template) { @tm_template = qw(typemap); my $updir = File::Spec->updir(); foreach my $dir ( File::Spec->catdir(($updir) x 1), File::Spec->catdir(($updir) x 2), File::Spec->catdir(($updir) x 3), File::Spec->catdir(($updir) x 4), ) { unshift @tm_template, File::Spec->catfile($dir, 'typemap'); unshift @tm_template, File::Spec->catfile($dir, lib => ExtUtils => 'typemap'); } } my @tm = @tm_template; foreach my $dir (@{ $include_ref}) { my $file = File::Spec->catfile($dir, ExtUtils => 'typemap'); unshift @tm, $file if -e $file; } return @tm; } } # end SCOPE =head2 C =over 4 =item * Purpose Perform an in-place trimming of leading and trailing whitespace from the first argument provided to the function. =item * Argument trim_whitespace($arg); =item * Return Value None. Remember: this is an I modification of the argument. =back =cut sub trim_whitespace { $_[0] =~ s/^\s+|\s+$//go; } =head2 C =over 4 =item * Purpose Escape backslashes (C<\>) in prototype strings. =item * Arguments $ProtoThisXSUB = C_string($_); String needing escaping. =item * Return Value Properly escaped string. =back =cut sub C_string { my($string) = @_; $string =~ s[\\][\\\\]g; $string; } =head2 C =over 4 =item * Purpose Validate prototype string. =item * Arguments String needing checking. =item * Return Value Upon success, returns the same string passed as argument. Upon failure, returns C<0>. =back =cut sub valid_proto_string { my ($string) = @_; if ( $string =~ /^$ExtUtils::ParseXS::Constants::PrototypeRegexp+$/ ) { return $string; } return 0; } =head2 C =over 4 =item * Purpose Process all typemap files. =item * Arguments my $typemaps_object = process_typemaps( $args{typemap}, $pwd ); List of two elements: C element from C<%args>; current working directory. =item * Return Value Upon success, returns an L object. =back =cut sub process_typemaps { my ($tmap, $pwd) = @_; my @tm = ref $tmap ? @{$tmap} : ($tmap); foreach my $typemap (@tm) { die "Can't find $typemap in $pwd\n" unless -r $typemap; } push @tm, standard_typemap_locations( \@INC ); require ExtUtils::Typemaps; my $typemap = ExtUtils::Typemaps->new; foreach my $typemap_loc (@tm) { next unless -f $typemap_loc; # skip directories, binary files etc. warn("Warning: ignoring non-text typemap file '$typemap_loc'\n"), next unless -T $typemap_loc; $typemap->merge(file => $typemap_loc, replace => 1); } return $typemap; } =head2 C =over 4 =item * Purpose Performs a mapping at several places inside C loop. =item * Arguments $type = map_type($self, $type, $varname); List of three arguments. =item * Return Value String holding augmented version of second argument. =back =cut sub map_type { my ($self, $type, $varname) = @_; # C++ has :: in types too so skip this $type =~ tr/:/_/ unless $self->{RetainCplusplusHierarchicalTypes}; $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s; if ($varname) { if ($type =~ / \( \s* \* (?= \s* \) ) /xg) { (substr $type, pos $type, 0) = " $varname "; } else { $type .= "\t$varname"; } } return $type; } =head2 C =over 4 =item * Purpose Writes to the C<.c> output file certain preprocessor directives and function headers needed in all such files. =item * Arguments None. =item * Return Value Returns true. =back =cut sub standard_XS_defs { print <<"EOF"; #ifndef PERL_UNUSED_VAR # define PERL_UNUSED_VAR(var) if (0) var = var #endif #ifndef dVAR # define dVAR dNOOP #endif /* This stuff is not part of the API! You have been warned. */ #ifndef PERL_VERSION_DECIMAL # define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s) #endif #ifndef PERL_DECIMAL_VERSION # define PERL_DECIMAL_VERSION \\ PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION) #endif #ifndef PERL_VERSION_GE # define PERL_VERSION_GE(r,v,s) \\ (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s)) #endif #ifndef PERL_VERSION_LE # define PERL_VERSION_LE(r,v,s) \\ (PERL_DECIMAL_VERSION <= PERL_VERSION_DECIMAL(r,v,s)) #endif /* XS_INTERNAL is the explicit static-linkage variant of the default * XS macro. * * XS_EXTERNAL is the same as XS_INTERNAL except it does not include * "STATIC", ie. it exports XSUB symbols. You probably don't want that * for anything but the BOOT XSUB. * * See XSUB.h in core! */ /* TODO: This might be compatible further back than 5.10.0. */ #if PERL_VERSION_GE(5, 10, 0) && PERL_VERSION_LE(5, 15, 1) # undef XS_EXTERNAL # undef XS_INTERNAL # if defined(__CYGWIN__) && defined(USE_DYNAMIC_LOADING) # define XS_EXTERNAL(name) __declspec(dllexport) XSPROTO(name) # define XS_INTERNAL(name) STATIC XSPROTO(name) # endif # if defined(__SYMBIAN32__) # define XS_EXTERNAL(name) EXPORT_C XSPROTO(name) # define XS_INTERNAL(name) EXPORT_C STATIC XSPROTO(name) # endif # ifndef XS_EXTERNAL # if defined(HASATTRIBUTE_UNUSED) && !defined(__cplusplus) # define XS_EXTERNAL(name) void name(pTHX_ CV* cv __attribute__unused__) # define XS_INTERNAL(name) STATIC void name(pTHX_ CV* cv __attribute__unused__) # else # ifdef __cplusplus # define XS_EXTERNAL(name) extern "C" XSPROTO(name) # define XS_INTERNAL(name) static XSPROTO(name) # else # define XS_EXTERNAL(name) XSPROTO(name) # define XS_INTERNAL(name) STATIC XSPROTO(name) # endif # endif # endif #endif /* perl >= 5.10.0 && perl <= 5.15.1 */ /* The XS_EXTERNAL macro is used for functions that must not be static * like the boot XSUB of a module. If perl didn't have an XS_EXTERNAL * macro defined, the best we can do is assume XS is the same. * Dito for XS_INTERNAL. */ #ifndef XS_EXTERNAL # define XS_EXTERNAL(name) XS(name) #endif #ifndef XS_INTERNAL # define XS_INTERNAL(name) XS(name) #endif /* Now, finally, after all this mess, we want an ExtUtils::ParseXS * internal macro that we're free to redefine for varying linkage due * to the EXPORT_XSUB_SYMBOLS XS keyword. This is internal, use * XS_EXTERNAL(name) or XS_INTERNAL(name) in your code if you need to! */ #undef XS_EUPXS #if defined(PERL_EUPXS_ALWAYS_EXPORT) # define XS_EUPXS(name) XS_EXTERNAL(name) #else /* default to internal */ # define XS_EUPXS(name) XS_INTERNAL(name) #endif EOF print <<"EOF"; #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params) /* prototype to pass -Wmissing-prototypes */ STATIC void S_croak_xs_usage(const CV *const cv, const char *const params); STATIC void S_croak_xs_usage(const CV *const cv, const char *const params) { const GV *const gv = CvGV(cv); PERL_ARGS_ASSERT_CROAK_XS_USAGE; if (gv) { const char *const gvname = GvNAME(gv); const HV *const stash = GvSTASH(gv); const char *const hvname = stash ? HvNAME(stash) : NULL; if (hvname) Perl_croak_nocontext("Usage: %s::%s(%s)", hvname, gvname, params); else Perl_croak_nocontext("Usage: %s(%s)", gvname, params); } else { /* Pants. I don't think that it should be possible to get here. */ Perl_croak_nocontext("Usage: CODE(0x%" UVxf ")(%s)", PTR2UV(cv), params); } } #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE #define croak_xs_usage S_croak_xs_usage #endif /* NOTE: the prototype of newXSproto() is different in versions of perls, * so we define a portable version of newXSproto() */ #ifdef newXS_flags #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0) #else #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv) #endif /* !defined(newXS_flags) */ #if PERL_VERSION_LE(5, 21, 5) # define newXS_deffile(a,b) Perl_newXS(aTHX_ a,b,file) #else # define newXS_deffile(a,b) Perl_newXS_deffile(aTHX_ a,b) #endif EOF return 1; } =head2 C =over 4 =item * Purpose Perform assignment to the C attribute. =item * Arguments $string = assign_func_args($self, $argsref, $class); List of three elements. Second is an array reference; third is a string. =item * Return Value String. =back =cut sub assign_func_args { my ($self, $argsref, $class) = @_; my @func_args = @{$argsref}; shift @func_args if defined($class); for my $arg (@func_args) { $arg =~ s/^/&/ if $self->{in_out}->{$arg}; } return join(", ", @func_args); } =head2 C =over 4 =item * Purpose Within each function inside each Xsub, print to the F<.c> output file certain preprocessor statements. =item * Arguments ( $self, $XSS_work_idx, $BootCode_ref ) = analyze_preprocessor_statements( $self, $statement, $XSS_work_idx, $BootCode_ref ); List of four elements. =item * Return Value Modifed values of three of the arguments passed to the function. In particular, the C and C attributes are modified. =back =cut sub analyze_preprocessor_statements { my ($self, $statement, $XSS_work_idx, $BootCode_ref) = @_; if ($statement eq 'if') { $XSS_work_idx = @{ $self->{XSStack} }; push(@{ $self->{XSStack} }, {type => 'if'}); } else { $self->death("Error: '$statement' with no matching 'if'") if $self->{XSStack}->[-1]{type} ne 'if'; if ($self->{XSStack}->[-1]{varname}) { push(@{ $self->{InitFileCode} }, "#endif\n"); push(@{ $BootCode_ref }, "#endif"); } my(@fns) = keys %{$self->{XSStack}->[-1]{functions}}; if ($statement ne 'endif') { # Hide the functions defined in other #if branches, and reset. @{$self->{XSStack}->[-1]{other_functions}}{@fns} = (1) x @fns; @{$self->{XSStack}->[-1]}{qw(varname functions)} = ('', {}); } else { my($tmp) = pop(@{ $self->{XSStack} }); 0 while (--$XSS_work_idx && $self->{XSStack}->[$XSS_work_idx]{type} ne 'if'); # Keep all new defined functions push(@fns, keys %{$tmp->{other_functions}}); @{$self->{XSStack}->[$XSS_work_idx]{functions}}{@fns} = (1) x @fns; } } return ($self, $XSS_work_idx, $BootCode_ref); } =head2 C =over 4 =item * Purpose =item * Arguments =item * Return Value =back =cut sub set_cond { my ($ellipsis, $min_args, $num_args) = @_; my $cond; if ($ellipsis) { $cond = ($min_args ? qq(items < $min_args) : 0); } elsif ($min_args == $num_args) { $cond = qq(items != $min_args); } else { $cond = qq(items < $min_args || items > $num_args); } return $cond; } =head2 C =over 4 =item * Purpose Figures out the current line number in the XS file. =item * Arguments C<$self> =item * Return Value The current line number. =back =cut sub current_line_number { my $self = shift; my $line_number = $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1]; return $line_number; } =head2 C =over 4 =item * Purpose =item * Arguments =item * Return Value =back =cut sub Warn { my $self = shift; my $warn_line_number = $self->current_line_number(); print STDERR "@_ in $self->{filename}, line $warn_line_number\n"; } =head2 C =over 4 =item * Purpose =item * Arguments =item * Return Value =back =cut sub blurt { my $self = shift; $self->Warn(@_); $self->{errors}++ } =head2 C =over 4 =item * Purpose =item * Arguments =item * Return Value =back =cut sub death { my $self = shift; $self->Warn(@_); exit 1; } =head2 C =over 4 =item * Purpose =item * Arguments =item * Return Value =back =cut sub check_conditional_preprocessor_statements { my ($self) = @_; my @cpp = grep(/^\#\s*(?:if|e\w+)/, @{ $self->{line} }); if (@cpp) { my $cpplevel; for my $cpp (@cpp) { if ($cpp =~ /^\#\s*if/) { $cpplevel++; } elsif (!$cpplevel) { $self->Warn("Warning: #else/elif/endif without #if in this function"); print STDERR " (precede it with a blank line if the matching #if is outside the function)\n" if $self->{XSStack}->[-1]{type} eq 'if'; return; } elsif ($cpp =~ /^\#\s*endif/) { $cpplevel--; } } $self->Warn("Warning: #if without #endif in this function") if $cpplevel; } } =head2 C =over 4 =item * Purpose Escapes a given code source name (typically a file name but can also be a command that was read from) so that double-quotes and backslashes are escaped. =item * Arguments A string. =item * Return Value A string with escapes for double-quotes and backslashes. =back =cut sub escape_file_for_line_directive { my $string = shift; $string =~ s/\\/\\\\/g; $string =~ s/"/\\"/g; return $string; } =head2 C =over 4 =item * Purpose Do error reporting for missing typemaps. =item * Arguments The C object. An C object. The string that represents the C type that was not found in the typemap. Optionally, the string C or C to choose whether the error is immediately fatal or not. Default: C =item * Return Value Returns nothing. Depending on the arguments, this may call C or C, the former of which is fatal. =back =cut sub report_typemap_failure { my ($self, $tm, $ctype, $error_method) = @_; $error_method ||= 'blurt'; my @avail_ctypes = $tm->list_mapped_ctypes; my $err = "Could not find a typemap for C type '$ctype'.\n" . "The following C types are mapped by the current typemap:\n'" . join("', '", @avail_ctypes) . "'\n"; $self->$error_method($err); return(); } 1; # vim: ts=2 sw=2 et: PK!‚Ó"£ËË$perl5/ExtUtils/ParseXS/CountLines.pmnuÏÃ6Ç$package ExtUtils::ParseXS::CountLines; use strict; our $VERSION = '3.35'; our $SECTION_END_MARKER; sub TIEHANDLE { my ($class, $cfile, $fh) = @_; $cfile =~ s/\\/\\\\/g; $cfile =~ s/"/\\"/g; $SECTION_END_MARKER = qq{#line --- "$cfile"}; return bless { buffer => '', fh => $fh, line_no => 1, }, $class; } sub PRINT { my $self = shift; for (@_) { $self->{buffer} .= $_; while ($self->{buffer} =~ s/^([^\n]*\n)//) { my $line = $1; ++$self->{line_no}; $line =~ s|^\#line\s+---(?=\s)|#line $self->{line_no}|; print {$self->{fh}} $line; } } } sub PRINTF { my $self = shift; my $fmt = shift; $self->PRINT(sprintf($fmt, @_)); } sub DESTROY { # Not necessary if we're careful to end with a "\n" my $self = shift; print {$self->{fh}} $self->{buffer}; } sub UNTIE { # This sub does nothing, but is necessary for references to be released. } sub end_marker { return $SECTION_END_MARKER; } 1; PK!q9 øxx#perl5/ExtUtils/ParseXS/Constants.pmnuÏÃ6Ç$package ExtUtils::ParseXS::Constants; use strict; use warnings; use Symbol; our $VERSION = '3.35'; =head1 NAME ExtUtils::ParseXS::Constants - Initialization values for some globals =head1 SYNOPSIS use ExtUtils::ParseXS::Constants (); $PrototypeRegexp = $ExtUtils::ParseXS::Constants::PrototypeRegexp; =head1 DESCRIPTION Initialization of certain non-subroutine variables in ExtUtils::ParseXS and some of its supporting packages has been moved into this package so that those values can be defined exactly once and then re-used in any package. Nothing is exported. Use fully qualified variable names. =cut # FIXME: THESE ARE NOT CONSTANTS! our @InitFileCode; # Note that to reduce maintenance, $PrototypeRegexp is used # by ExtUtils::Typemaps, too! our $PrototypeRegexp = "[" . quotemeta('\$%&*@;[]_') . "]"; our @XSKeywords = qw( REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK EXPORT_XSUB_SYMBOLS ); our $XSKeywordsAlternation = join('|', @XSKeywords); 1; PK!�fÍyÏÏperl5/ExtUtils/xsubppnuÏÃ6Ç$#!perl use 5.006; BEGIN { pop @INC if $INC[-1] eq '.' } use strict; eval { require ExtUtils::ParseXS; 1; } or do { my $err = $@ || 'Zombie error'; my $v = $ExtUtils::ParseXS::VERSION; $v = '' if not defined $v; die "Failed to load or import from ExtUtils::ParseXS (version $v). Please check that ExtUtils::ParseXS is installed correctly and that the newest version will be found in your \@INC path: $err"; }; use Getopt::Long; my %args = (); my $usage = "Usage: xsubpp [-v] [-csuffix csuffix] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-noinout] [-noargtypes] [-strip|s pattern] [-typemap typemap]... file.xs\n"; Getopt::Long::Configure qw(no_auto_abbrev no_ignore_case); @ARGV = grep {$_ ne '-C++'} @ARGV; # Allow -C++ for backward compatibility GetOptions(\%args, qw(hiertype! prototypes! versioncheck! linenumbers! optimize! inout! argtypes! object_capi! except! v typemap=s@ output=s s|strip=s csuffix=s )) or die $usage; if ($args{v}) { print "xsubpp version $ExtUtils::ParseXS::VERSION\n"; exit; } @ARGV == 1 or die $usage; $args{filename} = shift @ARGV; my $pxs = ExtUtils::ParseXS->new; $pxs->process_file(%args); exit( $pxs->report_error_count() ? 1 : 0 ); __END__ =head1 NAME xsubpp - compiler to convert Perl XS code into C code =head1 SYNOPSIS B [B<-v>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-nooptimize>] [B<-typemap typemap>] [B<-output filename>]... file.xs =head1 DESCRIPTION This compiler is typically run by the makefiles created by L or by L or other Perl module build tools. I will compile XS code into C code by embedding the constructs necessary to let C functions manipulate Perl values and creates the glue necessary to let Perl access those functions. The compiler uses typemaps to determine how to map C function parameters and variables to Perl values. The compiler will search for typemap files called I. It will use the following search path to find default typemaps, with the rightmost typemap taking precedence. ../../../typemap:../../typemap:../typemap:typemap It will also use a default typemap installed as C. =head1 OPTIONS Note that the C MakeMaker option may be used to add these options to any makefiles generated by MakeMaker. =over 5 =item B<-hiertype> Retains '::' in type names so that C++ hierarchical types can be mapped. =item B<-except> Adds exception handling stubs to the C code. =item B<-typemap typemap> Indicates that a user-supplied typemap should take precedence over the default typemaps. This option may be used multiple times, with the last typemap having the highest precedence. =item B<-output filename> Specifies the name of the output file to generate. If no file is specified, output will be written to standard output. =item B<-v> Prints the I version number to standard output, then exits. =item B<-prototypes> By default I will not automatically generate prototype code for all xsubs. This flag will enable prototypes. =item B<-noversioncheck> Disables the run time test that determines if the object file (derived from the C<.xs> file) and the C<.pm> files have the same version number. =item B<-nolinenumbers> Prevents the inclusion of '#line' directives in the output. =item B<-nooptimize> Disables certain optimizations. The only optimization that is currently affected is the use of Is by the output C code (see L). This may significantly slow down the generated code, but this is the way B of 5.005 and earlier operated. =item B<-noinout> Disable recognition of C, C and C declarations. =item B<-noargtypes> Disable recognition of ANSI-like descriptions of function signature. =item B<-C++> Currently doesn't do anything at all. This flag has been a no-op for many versions of perl, at least as far back as perl5.003_07. It's allowed here for backwards compatibility. =item B<-s=...> or B<-strip=...> I If specified, the given string will be stripped off from the beginning of the C function name in the generated XS functions (if it starts with that prefix). This only applies to XSUBs without C or C blocks. For example, the XS: void foo_bar(int i); when C is invoked with C<-s foo_> will install a C function in Perl, but really call C in C. Most of the time, this is the opposite of what you want and failure modes are somewhat obscure, so please avoid this option where possible. =back =head1 ENVIRONMENT No environment variables are used. =head1 AUTHOR Originally by Larry Wall. Turned into the C module by Ken Williams. =head1 MODIFICATION HISTORY See the file F. =head1 SEE ALSO perl(1), perlxs(1), perlxstut(1), ExtUtils::ParseXS =cut PK!‚Ç+dPPperl5/Test/use/ok.pmnuÏÃ6Ç$package Test::use::ok; use 5.005; our $VERSION = '1.302183'; __END__ =head1 NAME Test::use::ok - Alternative to Test::More::use_ok =head1 SYNOPSIS use ok 'Some::Module'; =head1 DESCRIPTION According to the B documentation, it is recommended to run C inside a C block, so functions are exported at compile-time and prototypes are properly honored. That is, instead of writing this: use_ok( 'Some::Module' ); use_ok( 'Other::Module' ); One should write this: BEGIN { use_ok( 'Some::Module' ); } BEGIN { use_ok( 'Other::Module' ); } However, people often either forget to add C, or mistakenly group C with other tests in a single C block, which can create subtle differences in execution order. With this module, simply change all C in test scripts to C, and they will be executed at C time. The explicit space after C makes it clear that this is a single compile-time action. =head1 SEE ALSO L =head1 MAINTAINER =over 4 =item Chad Granum Eexodist@cpan.orgE =back =encoding utf8 =head1 CC0 1.0 Universal To the extent possible under law, å”�é³³ has waived all copyright and related or neighboring rights to L. This work is published from Taiwan. L =cut PK!h†/ªZþZþperl5/Test/Builder.pmnuÏÃ6Ç$package Test::Builder; use 5.006; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { if( $] < 5.008 ) { require Test::Builder::IO::Scalar; } } use Scalar::Util qw/blessed reftype weaken/; use Test2::Util qw/USE_THREADS try get_tid/; use Test2::API qw/context release/; # Make Test::Builder thread-safe for ithreads. BEGIN { warn "Test::Builder was loaded after Test2 initialization, this is not recommended." if Test2::API::test2_init_done() || Test2::API::test2_load_done(); if (USE_THREADS && ! Test2::API::test2_ipc_disabled()) { require Test2::IPC; require Test2::IPC::Driver::Files; Test2::IPC::Driver::Files->import; Test2::API::test2_ipc_enable_polling(); Test2::API::test2_no_wait(1); } } use Test2::Event::Subtest; use Test2::Hub::Subtest; use Test::Builder::Formatter; use Test::Builder::TodoDiag; our $Level = 1; our $Test = $ENV{TB_NO_EARLY_INIT} ? undef : Test::Builder->new; sub _add_ts_hooks { my $self = shift; my $hub = $self->{Stack}->top; # Take a reference to the hash key, we do this to avoid closing over $self # which is the singleton. We use a reference because the value could change # in rare cases. my $epkgr = \$self->{Exported_To}; #$hub->add_context_aquire(sub {$_[0]->{level} += $Level - 1}); $hub->pre_filter( sub { my ($active_hub, $e) = @_; my $epkg = $$epkgr; my $cpkg = $e->{trace} ? $e->{trace}->{frame}->[0] : undef; no strict 'refs'; no warnings 'once'; my $todo; $todo = ${"$cpkg\::TODO"} if $cpkg; $todo = ${"$epkg\::TODO"} if $epkg && !$todo; return $e unless defined($todo); return $e unless length($todo); # Turn a diag into a todo diag return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag'; $e->set_todo($todo) if $e->can('set_todo'); $e->add_amnesty({tag => 'TODO', details => $todo}); # Set todo on ok's if ($e->isa('Test2::Event::Ok')) { $e->set_effective_pass(1); if (my $result = $e->get_meta(__PACKAGE__)) { $result->{reason} ||= $todo; $result->{type} ||= 'todo'; $result->{ok} = 1; } } return $e; }, inherit => 1, intercept_inherit => { clean => sub { my %params = @_; my $state = $params{state}; my $trace = $params{trace}; my $epkg = $$epkgr; my $cpkg = $trace->{frame}->[0]; no strict 'refs'; no warnings 'once'; $state->{+__PACKAGE__} = {}; $state->{+__PACKAGE__}->{"$cpkg\::TODO"} = ${"$cpkg\::TODO"} if $cpkg; $state->{+__PACKAGE__}->{"$epkg\::TODO"} = ${"$epkg\::TODO"} if $epkg; ${"$cpkg\::TODO"} = undef if $cpkg; ${"$epkg\::TODO"} = undef if $epkg; }, restore => sub { my %params = @_; my $state = $params{state}; no strict 'refs'; no warnings 'once'; for my $item (keys %{$state->{+__PACKAGE__}}) { no strict 'refs'; no warnings 'once'; ${"$item"} = $state->{+__PACKAGE__}->{$item}; } }, }, ); } { no warnings; INIT { use warnings; Test2::API::test2_load() unless Test2::API::test2_in_preload(); } } sub new { my($class) = shift; unless($Test) { $Test = $class->create(singleton => 1); Test2::API::test2_add_callback_post_load( sub { $Test->{Original_Pid} = $$ if !$Test->{Original_Pid} || $Test->{Original_Pid} == 0; $Test->reset(singleton => 1); $Test->_add_ts_hooks; } ); # Non-TB tools normally expect 0 added to the level. $Level is normally 1. So # we only want the level to change if $Level != 1. # TB->ctx compensates for this later. Test2::API::test2_add_callback_context_aquire(sub { $_[0]->{level} += $Level - 1 }); Test2::API::test2_add_callback_exit(sub { $Test->_ending(@_) }); Test2::API::test2_ipc()->set_no_fatal(1) if Test2::API::test2_has_ipc(); } return $Test; } sub create { my $class = shift; my %params = @_; my $self = bless {}, $class; if ($params{singleton}) { $self->{Stack} = Test2::API::test2_stack(); } else { $self->{Stack} = Test2::API::Stack->new; $self->{Stack}->new_hub( formatter => Test::Builder::Formatter->new, ipc => Test2::API::test2_ipc(), ); $self->reset(%params); $self->_add_ts_hooks; } return $self; } sub ctx { my $self = shift; context( # 1 for our frame, another for the -1 off of $Level in our hook at the top. level => 2, fudge => 1, stack => $self->{Stack}, hub => $self->{Hub}, wrapped => 1, @_ ); } sub parent { my $self = shift; my $ctx = $self->ctx; my $chub = $self->{Hub} || $ctx->hub; $ctx->release; my $meta = $chub->meta(__PACKAGE__, {}); my $parent = $meta->{parent}; return undef unless $parent; return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $parent, }, blessed($self); } sub child { my( $self, $name ) = @_; $name ||= "Child of " . $self->name; my $ctx = $self->ctx; my $parent = $ctx->hub; my $pmeta = $parent->meta(__PACKAGE__, {}); $self->croak("You already have a child named ($pmeta->{child}) running") if $pmeta->{child}; $pmeta->{child} = $name; # Clear $TODO for the child. my $orig_TODO = $self->find_TODO(undef, 1, undef); my $subevents = []; my $hub = $ctx->stack->new_hub( class => 'Test2::Hub::Subtest', ); $hub->pre_filter(sub { my ($active_hub, $e) = @_; # Turn a diag into a todo diag return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag'; return $e; }, inherit => 1) if $orig_TODO; $hub->listen(sub { push @$subevents => $_[1] }); $hub->set_nested( $parent->nested + 1 ); my $meta = $hub->meta(__PACKAGE__, {}); $meta->{Name} = $name; $meta->{TODO} = $orig_TODO; $meta->{TODO_PKG} = $ctx->trace->package; $meta->{parent} = $parent; $meta->{Test_Results} = []; $meta->{subevents} = $subevents; $meta->{subtest_id} = $hub->id; $meta->{subtest_uuid} = $hub->uuid; $meta->{subtest_buffered} = $parent->format ? 0 : 1; $self->_add_ts_hooks; $ctx->release; return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $hub, no_log_results => $self->{no_log_results} }, blessed($self); } sub finalize { my $self = shift; my $ok = 1; ($ok) = @_ if @_; my $st_ctx = $self->ctx; my $chub = $self->{Hub} || return $st_ctx->release; my $meta = $chub->meta(__PACKAGE__, {}); if ($meta->{child}) { $self->croak("Can't call finalize() with child ($meta->{child}) active"); } local $? = 0; # don't fail if $subtests happened to set $? nonzero $self->{Stack}->pop($chub); $self->find_TODO($meta->{TODO_PKG}, 1, $meta->{TODO}); my $parent = $self->parent; my $ctx = $parent->ctx; my $trace = $ctx->trace; delete $ctx->hub->meta(__PACKAGE__, {})->{child}; $chub->finalize($trace->snapshot(hid => $chub->hid, nested => $chub->nested), 1) if $ok && $chub->count && !$chub->no_ending && !$chub->ended; my $plan = $chub->plan || 0; my $count = $chub->count; my $failed = $chub->failed; my $passed = $chub->is_passing; my $num_extra = $plan =~ m/\D/ ? 0 : $count - $plan; if ($count && $num_extra != 0) { my $s = $plan == 1 ? '' : 's'; $st_ctx->diag(<<"FAIL"); Looks like you planned $plan test$s but ran $count. FAIL } if ($failed) { my $s = $failed == 1 ? '' : 's'; my $qualifier = $num_extra == 0 ? '' : ' run'; $st_ctx->diag(<<"FAIL"); Looks like you failed $failed test$s of $count$qualifier. FAIL } if (!$passed && !$failed && $count && !$num_extra) { $st_ctx->diag(<<"FAIL"); All assertions inside the subtest passed, but errors were encountered. FAIL } $st_ctx->release; unless ($chub->bailed_out) { my $plan = $chub->plan; if ( $plan && $plan eq 'SKIP' ) { $parent->skip($chub->skip_reason, $meta->{Name}); } elsif ( !$chub->count ) { $parent->ok( 0, sprintf q[No tests run for subtest "%s"], $meta->{Name} ); } else { $parent->{subevents} = $meta->{subevents}; $parent->{subtest_id} = $meta->{subtest_id}; $parent->{subtest_uuid} = $meta->{subtest_uuid}; $parent->{subtest_buffered} = $meta->{subtest_buffered}; $parent->ok( $chub->is_passing, $meta->{Name} ); } } $ctx->release; return $chub->is_passing; } sub subtest { my $self = shift; my ($name, $code, @args) = @_; my $ctx = $self->ctx; $ctx->throw("subtest()'s second argument must be a code ref") unless $code && reftype($code) eq 'CODE'; $name ||= "Child of " . $self->name; $_->($name,$code,@args) for Test2::API::test2_list_pre_subtest_callbacks(); $ctx->note("Subtest: $name"); my $child = $self->child($name); my $start_pid = $$; my $st_ctx; my ($ok, $err, $finished, $child_error); T2_SUBTEST_WRAPPER: { my $ctx = $self->ctx; $st_ctx = $ctx->snapshot; $ctx->release; $ok = eval { local $Level = 1; $code->(@args); 1 }; ($err, $child_error) = ($@, $?); # They might have done 'BEGIN { skip_all => "whatever" }' if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) { $ok = undef; $err = undef; } else { $finished = 1; } } if ($start_pid != $$ && !$INC{'Test2/IPC.pm'}) { warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err; exit 255; } my $trace = $ctx->trace; if (!$finished) { if(my $bailed = $st_ctx->hub->bailed_out) { my $chub = $child->{Hub}; $self->{Stack}->pop($chub); $ctx->bail($bailed->reason); } my $code = $st_ctx->hub->exit_code; $ok = !$code; $err = "Subtest ended with exit code $code" if $code; } my $st_hub = $st_ctx->hub; my $plan = $st_hub->plan; my $count = $st_hub->count; if (!$count && (!defined($plan) || "$plan" ne 'SKIP')) { $st_ctx->plan(0) unless defined $plan; $st_ctx->diag('No tests run!'); } $child->finalize($st_ctx->trace); $ctx->release; die $err unless $ok; $? = $child_error if defined $child_error; return $st_hub->is_passing; } sub name { my $self = shift; my $ctx = $self->ctx; release $ctx, $ctx->hub->meta(__PACKAGE__, {})->{Name}; } sub reset { ## no critic (Subroutines::ProhibitBuiltinHomonyms) my ($self, %params) = @_; Test2::API::test2_unset_is_end(); # We leave this a global because it has to be localized and localizing # hash keys is just asking for pain. Also, it was documented. $Level = 1; $self->{no_log_results} = $ENV{TEST_NO_LOG_RESULTS} ? 1 : 0 unless $params{singleton}; $self->{Original_Pid} = Test2::API::test2_in_preload() ? -1 : $$; my $ctx = $self->ctx; my $hub = $ctx->hub; $ctx->release; unless ($params{singleton}) { $hub->reset_state(); $hub->_tb_reset(); } $ctx = $self->ctx; my $meta = $ctx->hub->meta(__PACKAGE__, {}); %$meta = ( Name => $0, Ending => 0, Done_Testing => undef, Skip_All => 0, Test_Results => [], parent => $meta->{parent}, ); $self->{Exported_To} = undef unless $params{singleton}; $self->{Orig_Handles} ||= do { my $format = $ctx->hub->format; my $out; if ($format && $format->isa('Test2::Formatter::TAP')) { $out = $format->handles; } $out ? [@$out] : []; }; $self->use_numbers(1); $self->no_header(0) unless $params{singleton}; $self->no_ending(0) unless $params{singleton}; $self->reset_outputs; $ctx->release; return; } my %plan_cmds = ( no_plan => \&no_plan, skip_all => \&skip_all, tests => \&_plan_tests, ); sub plan { my( $self, $cmd, $arg ) = @_; return unless $cmd; my $ctx = $self->ctx; my $hub = $ctx->hub; $ctx->throw("You tried to plan twice") if $hub->plan; local $Level = $Level + 1; if( my $method = $plan_cmds{$cmd} ) { local $Level = $Level + 1; $self->$method($arg); } else { my @args = grep { defined } ( $cmd, $arg ); $ctx->throw("plan() doesn't understand @args"); } release $ctx, 1; } sub _plan_tests { my($self, $arg) = @_; my $ctx = $self->ctx; if($arg) { local $Level = $Level + 1; $self->expected_tests($arg); } elsif( !defined $arg ) { $ctx->throw("Got an undefined number of tests"); } else { $ctx->throw("You said to run 0 tests"); } $ctx->release; } sub expected_tests { my $self = shift; my($max) = @_; my $ctx = $self->ctx; if(@_) { $self->croak("Number of tests must be a positive integer. You gave it '$max'") unless $max =~ /^\+?\d+$/; $ctx->plan($max); } my $hub = $ctx->hub; $ctx->release; my $plan = $hub->plan; return 0 unless $plan; return 0 if $plan =~ m/\D/; return $plan; } sub no_plan { my($self, $arg) = @_; my $ctx = $self->ctx; if (defined $ctx->hub->plan) { warn "Plan already set, no_plan() is a no-op, this will change to a hard failure in the future."; $ctx->release; return; } $ctx->alert("no_plan takes no arguments") if $arg; $ctx->hub->plan('NO PLAN'); release $ctx, 1; } sub done_testing { my($self, $num_tests) = @_; my $ctx = $self->ctx; my $meta = $ctx->hub->meta(__PACKAGE__, {}); if ($meta->{Done_Testing}) { my ($file, $line) = @{$meta->{Done_Testing}}[1,2]; local $ctx->hub->{ended}; # OMG This is awful. $self->ok(0, "done_testing() was already called at $file line $line"); $ctx->release; return; } $meta->{Done_Testing} = [$ctx->trace->call]; my $plan = $ctx->hub->plan; my $count = $ctx->hub->count; # If done_testing() specified the number of tests, shut off no_plan if( defined $num_tests ) { $ctx->plan($num_tests) if !$plan || $plan eq 'NO PLAN'; } elsif ($count && defined $num_tests && $count != $num_tests) { $self->ok(0, "planned to run @{[ $self->expected_tests ]} but done_testing() expects $num_tests"); } else { $num_tests = $self->current_test; } if( $self->expected_tests && $num_tests != $self->expected_tests ) { $self->ok(0, "planned to run @{[ $self->expected_tests ]} ". "but done_testing() expects $num_tests"); } $ctx->plan($num_tests) if $ctx->hub->plan && $ctx->hub->plan eq 'NO PLAN'; $ctx->hub->finalize($ctx->trace, 1); release $ctx, 1; } sub has_plan { my $self = shift; my $ctx = $self->ctx; my $plan = $ctx->hub->plan; $ctx->release; return( $plan ) if $plan && $plan !~ m/\D/; return('no_plan') if $plan && $plan eq 'NO PLAN'; return(undef); } sub skip_all { my( $self, $reason ) = @_; my $ctx = $self->ctx; $ctx->hub->meta(__PACKAGE__, {})->{Skip_All} = $reason || 1; # Work around old perl bug if ($] < 5.020000) { my $begin = 0; my $level = 0; while (my @call = caller($level++)) { last unless @call && $call[0]; next unless $call[3] =~ m/::BEGIN$/; $begin++; last; } # HACK! die 'Label not found for "last T2_SUBTEST_WRAPPER"' if $begin && $ctx->hub->meta(__PACKAGE__, {})->{parent}; } $ctx->plan(0, SKIP => $reason); } sub exported_to { my( $self, $pack ) = @_; if( defined $pack ) { $self->{Exported_To} = $pack; } return $self->{Exported_To}; } sub ok { my( $self, $test, $name ) = @_; my $ctx = $self->ctx; # $test might contain an object which we don't want to accidentally # store, so we turn it into a boolean. $test = $test ? 1 : 0; # In case $name is a string overloaded object, force it to stringify. no warnings qw/uninitialized numeric/; $name = "$name" if defined $name; # Profiling showed that the regex here was a huge time waster, doing the # numeric addition first cuts our profile time from ~300ms to ~50ms $self->diag(<<" ERR") if 0 + $name && $name =~ /^[\d\s]+$/; You named your test '$name'. You shouldn't use numbers for your test names. Very confusing. ERR use warnings qw/uninitialized numeric/; my $trace = $ctx->{trace}; my $hub = $ctx->{hub}; my $result = { ok => $test, actual_ok => $test, reason => '', type => '', (name => defined($name) ? $name : ''), }; $hub->{_meta}->{+__PACKAGE__}->{Test_Results}[ $hub->{count} ] = $result unless $self->{no_log_results}; my $orig_name = $name; my @attrs; my $subevents = delete $self->{subevents}; my $subtest_id = delete $self->{subtest_id}; my $subtest_uuid = delete $self->{subtest_uuid}; my $subtest_buffered = delete $self->{subtest_buffered}; my $epkg = 'Test2::Event::Ok'; if ($subevents) { $epkg = 'Test2::Event::Subtest'; push @attrs => (subevents => $subevents, subtest_id => $subtest_id, subtest_uuid => $subtest_uuid, buffered => $subtest_buffered); } my $e = bless { trace => bless( {%$trace}, 'Test2::EventFacet::Trace'), pass => $test, name => $name, _meta => {'Test::Builder' => $result}, effective_pass => $test, @attrs, }, $epkg; $hub->send($e); $self->_ok_debug($trace, $orig_name) unless($test); $ctx->release; return $test; } sub _ok_debug { my $self = shift; my ($trace, $orig_name) = @_; my $is_todo = $self->in_todo; my $msg = $is_todo ? "Failed (TODO)" : "Failed"; my (undef, $file, $line) = $trace->call; if (defined $orig_name) { $self->diag(qq[ $msg test '$orig_name'\n at $file line $line.\n]); } else { $self->diag(qq[ $msg test at $file line $line.\n]); } } sub _diag_fh { my $self = shift; local $Level = $Level + 1; return $self->in_todo ? $self->todo_output : $self->failure_output; } sub _unoverload { my ($self, $type, $thing) = @_; return unless ref $$thing; return unless blessed($$thing) || scalar $self->_try(sub{ $$thing->isa('UNIVERSAL') }); { local ($!, $@); require overload; } my $string_meth = overload::Method( $$thing, $type ) || return; $$thing = $$thing->$string_meth(); } sub _unoverload_str { my $self = shift; $self->_unoverload( q[""], $_ ) for @_; } sub _unoverload_num { my $self = shift; $self->_unoverload( '0+', $_ ) for @_; for my $val (@_) { next unless $self->_is_dualvar($$val); $$val = $$val + 0; } } # This is a hack to detect a dualvar such as $! sub _is_dualvar { my( $self, $val ) = @_; # Objects are not dualvars. return 0 if ref $val; no warnings 'numeric'; my $numval = $val + 0; return ($numval != 0 and $numval ne $val ? 1 : 0); } sub is_eq { my( $self, $got, $expect, $name ) = @_; my $ctx = $self->ctx; local $Level = $Level + 1; if( !defined $got || !defined $expect ) { # undef only matches undef and nothing else my $test = !defined $got && !defined $expect; $self->ok( $test, $name ); $self->_is_diag( $got, 'eq', $expect ) unless $test; $ctx->release; return $test; } release $ctx, $self->cmp_ok( $got, 'eq', $expect, $name ); } sub is_num { my( $self, $got, $expect, $name ) = @_; my $ctx = $self->ctx; local $Level = $Level + 1; if( !defined $got || !defined $expect ) { # undef only matches undef and nothing else my $test = !defined $got && !defined $expect; $self->ok( $test, $name ); $self->_is_diag( $got, '==', $expect ) unless $test; $ctx->release; return $test; } release $ctx, $self->cmp_ok( $got, '==', $expect, $name ); } sub _diag_fmt { my( $self, $type, $val ) = @_; if( defined $$val ) { if( $type eq 'eq' or $type eq 'ne' ) { # quote and force string context $$val = "'$$val'"; } else { # force numeric context $self->_unoverload_num($val); } } else { $$val = 'undef'; } return; } sub _is_diag { my( $self, $got, $type, $expect ) = @_; $self->_diag_fmt( $type, $_ ) for \$got, \$expect; local $Level = $Level + 1; return $self->diag(<<"DIAGNOSTIC"); got: $got expected: $expect DIAGNOSTIC } sub _isnt_diag { my( $self, $got, $type ) = @_; $self->_diag_fmt( $type, \$got ); local $Level = $Level + 1; return $self->diag(<<"DIAGNOSTIC"); got: $got expected: anything else DIAGNOSTIC } sub isnt_eq { my( $self, $got, $dont_expect, $name ) = @_; my $ctx = $self->ctx; local $Level = $Level + 1; if( !defined $got || !defined $dont_expect ) { # undef only matches undef and nothing else my $test = defined $got || defined $dont_expect; $self->ok( $test, $name ); $self->_isnt_diag( $got, 'ne' ) unless $test; $ctx->release; return $test; } release $ctx, $self->cmp_ok( $got, 'ne', $dont_expect, $name ); } sub isnt_num { my( $self, $got, $dont_expect, $name ) = @_; my $ctx = $self->ctx; local $Level = $Level + 1; if( !defined $got || !defined $dont_expect ) { # undef only matches undef and nothing else my $test = defined $got || defined $dont_expect; $self->ok( $test, $name ); $self->_isnt_diag( $got, '!=' ) unless $test; $ctx->release; return $test; } release $ctx, $self->cmp_ok( $got, '!=', $dont_expect, $name ); } sub like { my( $self, $thing, $regex, $name ) = @_; my $ctx = $self->ctx; local $Level = $Level + 1; release $ctx, $self->_regex_ok( $thing, $regex, '=~', $name ); } sub unlike { my( $self, $thing, $regex, $name ) = @_; my $ctx = $self->ctx; local $Level = $Level + 1; release $ctx, $self->_regex_ok( $thing, $regex, '!~', $name ); } my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" ); # Bad, these are not comparison operators. Should we include more? my %cmp_ok_bl = map { ( $_, 1 ) } ( "=", "+=", ".=", "x=", "^=", "|=", "||=", "&&=", "..."); sub cmp_ok { my( $self, $got, $type, $expect, $name ) = @_; my $ctx = $self->ctx; if ($cmp_ok_bl{$type}) { $ctx->throw("$type is not a valid comparison operator in cmp_ok()"); } my ($test, $succ); my $error; { ## no critic (BuiltinFunctions::ProhibitStringyEval) local( $@, $!, $SIG{__DIE__} ); # isolate eval my($pack, $file, $line) = $ctx->trace->call(); my $warning_bits = $ctx->trace->warning_bits; # convert this to a code string so the BEGIN doesn't have to close # over it, which can lead to issues with Devel::Cover my $bits_code = defined $warning_bits ? qq["\Q$warning_bits\E"] : 'undef'; # This is so that warnings come out at the caller's level $succ = eval qq[ BEGIN {\${^WARNING_BITS} = $bits_code}; #line $line "(eval in cmp_ok) $file" \$test = (\$got $type \$expect); 1; ]; $error = $@; } local $Level = $Level + 1; my $ok = $self->ok( $test, $name ); # Treat overloaded objects as numbers if we're asked to do a # numeric comparison. my $unoverload = $numeric_cmps{$type} ? '_unoverload_num' : '_unoverload_str'; $self->diag(<<"END") unless $succ; An error occurred while using $type: ------------------------------------ $error ------------------------------------ END unless($ok) { $self->$unoverload( \$got, \$expect ); if( $type =~ /^(eq|==)$/ ) { $self->_is_diag( $got, $type, $expect ); } elsif( $type =~ /^(ne|!=)$/ ) { no warnings; my $eq = ($got eq $expect || $got == $expect) && ( (defined($got) xor defined($expect)) || (length($got) != length($expect)) ); use warnings; if ($eq) { $self->_cmp_diag( $got, $type, $expect ); } else { $self->_isnt_diag( $got, $type ); } } else { $self->_cmp_diag( $got, $type, $expect ); } } return release $ctx, $ok; } sub _cmp_diag { my( $self, $got, $type, $expect ) = @_; $got = defined $got ? "'$got'" : 'undef'; $expect = defined $expect ? "'$expect'" : 'undef'; local $Level = $Level + 1; return $self->diag(<<"DIAGNOSTIC"); $got $type $expect DIAGNOSTIC } sub _caller_context { my $self = shift; my( $pack, $file, $line ) = $self->caller(1); my $code = ''; $code .= "#line $line $file\n" if defined $file and defined $line; return $code; } sub BAIL_OUT { my( $self, $reason ) = @_; my $ctx = $self->ctx; $self->{Bailed_Out} = 1; $ctx->bail($reason); } { no warnings 'once'; *BAILOUT = \&BAIL_OUT; } sub skip { my( $self, $why, $name ) = @_; $why ||= ''; $name = '' unless defined $name; $self->_unoverload_str( \$why ); my $ctx = $self->ctx; $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = { 'ok' => 1, actual_ok => 1, name => $name, type => 'skip', reason => $why, } unless $self->{no_log_results}; $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness. $name =~ s{\n}{\n# }sg; $why =~ s{\n}{\n# }sg; my $tctx = $ctx->snapshot; $tctx->skip('', $why); return release $ctx, 1; } sub todo_skip { my( $self, $why ) = @_; $why ||= ''; my $ctx = $self->ctx; $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = { 'ok' => 1, actual_ok => 0, name => '', type => 'todo_skip', reason => $why, } unless $self->{no_log_results}; $why =~ s{\n}{\n# }sg; my $tctx = $ctx->snapshot; $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0); return release $ctx, 1; } sub maybe_regex { my( $self, $regex ) = @_; my $usable_regex = undef; return $usable_regex unless defined $regex; my( $re, $opts ); # Check for qr/foo/ if( _is_qr($regex) ) { $usable_regex = $regex; } # Check for '/foo/' or 'm,foo,' elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx ) { $usable_regex = length $opts ? "(?$opts)$re" : $re; } return $usable_regex; } sub _is_qr { my $regex = shift; # is_regexp() checks for regexes in a robust manner, say if they're # blessed. return re::is_regexp($regex) if defined &re::is_regexp; return ref $regex eq 'Regexp'; } sub _regex_ok { my( $self, $thing, $regex, $cmp, $name ) = @_; my $ok = 0; my $usable_regex = $self->maybe_regex($regex); unless( defined $usable_regex ) { local $Level = $Level + 1; $ok = $self->ok( 0, $name ); $self->diag(" '$regex' doesn't look much like a regex to me."); return $ok; } { my $test; my $context = $self->_caller_context; { ## no critic (BuiltinFunctions::ProhibitStringyEval) local( $@, $!, $SIG{__DIE__} ); # isolate eval # No point in issuing an uninit warning, they'll see it in the diagnostics no warnings 'uninitialized'; $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0}; } $test = !$test if $cmp eq '!~'; local $Level = $Level + 1; $ok = $self->ok( $test, $name ); } unless($ok) { $thing = defined $thing ? "'$thing'" : 'undef'; my $match = $cmp eq '=~' ? "doesn't match" : "matches"; local $Level = $Level + 1; $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex ); %s %13s '%s' DIAGNOSTIC } return $ok; } sub is_fh { my $self = shift; my $maybe_fh = shift; return 0 unless defined $maybe_fh; return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob return eval { $maybe_fh->isa("IO::Handle") } || eval { tied($maybe_fh)->can('TIEHANDLE') }; } sub level { my( $self, $level ) = @_; if( defined $level ) { $Level = $level; } return $Level; } sub use_numbers { my( $self, $use_nums ) = @_; my $ctx = $self->ctx; my $format = $ctx->hub->format; unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) { warn "The current formatter does not support 'use_numbers'" if $format; return release $ctx, 0; } $format->set_no_numbers(!$use_nums) if defined $use_nums; return release $ctx, $format->no_numbers ? 0 : 1; } BEGIN { for my $method (qw(no_header no_diag)) { my $set = "set_$method"; my $code = sub { my( $self, $no ) = @_; my $ctx = $self->ctx; my $format = $ctx->hub->format; unless ($format && $format->can($set)) { warn "The current formatter does not support '$method'" if $format; $ctx->release; return } $format->$set($no) if defined $no; return release $ctx, $format->$method ? 1 : 0; }; no strict 'refs'; ## no critic *$method = $code; } } sub no_ending { my( $self, $no ) = @_; my $ctx = $self->ctx; $ctx->hub->set_no_ending($no) if defined $no; return release $ctx, $ctx->hub->no_ending; } sub diag { my $self = shift; return unless @_; my $text = join '' => map {defined($_) ? $_ : 'undef'} @_; if (Test2::API::test2_in_preload()) { chomp($text); $text =~ s/^/# /msg; print STDERR $text, "\n"; return 0; } my $ctx = $self->ctx; $ctx->diag($text); $ctx->release; return 0; } sub note { my $self = shift; return unless @_; my $text = join '' => map {defined($_) ? $_ : 'undef'} @_; if (Test2::API::test2_in_preload()) { chomp($text); $text =~ s/^/# /msg; print STDOUT $text, "\n"; return 0; } my $ctx = $self->ctx; $ctx->note($text); $ctx->release; return 0; } sub explain { my $self = shift; local ($@, $!); require Data::Dumper; return map { ref $_ ? do { my $dumper = Data::Dumper->new( [$_] ); $dumper->Indent(1)->Terse(1); $dumper->Sortkeys(1) if $dumper->can("Sortkeys"); $dumper->Dump; } : $_ } @_; } sub output { my( $self, $fh ) = @_; my $ctx = $self->ctx; my $format = $ctx->hub->format; $ctx->release; return unless $format && $format->isa('Test2::Formatter::TAP'); $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh) if defined $fh; return $format->handles->[Test2::Formatter::TAP::OUT_STD()]; } sub failure_output { my( $self, $fh ) = @_; my $ctx = $self->ctx; my $format = $ctx->hub->format; $ctx->release; return unless $format && $format->isa('Test2::Formatter::TAP'); $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh) if defined $fh; return $format->handles->[Test2::Formatter::TAP::OUT_ERR()]; } sub todo_output { my( $self, $fh ) = @_; my $ctx = $self->ctx; my $format = $ctx->hub->format; $ctx->release; return unless $format && $format->isa('Test::Builder::Formatter'); $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh) if defined $fh; return $format->handles->[Test::Builder::Formatter::OUT_TODO()]; } sub _new_fh { my $self = shift; my($file_or_fh) = shift; my $fh; if( $self->is_fh($file_or_fh) ) { $fh = $file_or_fh; } elsif( ref $file_or_fh eq 'SCALAR' ) { # Scalar refs as filehandles was added in 5.8. if( $] >= 5.008 ) { open $fh, ">>", $file_or_fh or $self->croak("Can't open scalar ref $file_or_fh: $!"); } # Emulate scalar ref filehandles with a tie. else { $fh = Test::Builder::IO::Scalar->new($file_or_fh) or $self->croak("Can't tie scalar ref $file_or_fh"); } } else { open $fh, ">", $file_or_fh or $self->croak("Can't open test output log $file_or_fh: $!"); _autoflush($fh); } return $fh; } sub _autoflush { my($fh) = shift; my $old_fh = select $fh; $| = 1; select $old_fh; return; } sub reset_outputs { my $self = shift; my $ctx = $self->ctx; my $format = $ctx->hub->format; $ctx->release; return unless $format && $format->isa('Test2::Formatter::TAP'); $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles}; return; } sub carp { my $self = shift; my $ctx = $self->ctx; $ctx->alert(join "", @_); $ctx->release; } sub croak { my $self = shift; my $ctx = $self->ctx; $ctx->throw(join "", @_); $ctx->release; } sub current_test { my( $self, $num ) = @_; my $ctx = $self->ctx; my $hub = $ctx->hub; if( defined $num ) { $hub->set_count($num); unless ($self->{no_log_results}) { # If the test counter is being pushed forward fill in the details. my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}; if ($num > @$test_results) { my $start = @$test_results ? @$test_results : 0; for ($start .. $num - 1) { $test_results->[$_] = { 'ok' => 1, actual_ok => undef, reason => 'incrementing test number', type => 'unknown', name => undef }; } } # If backward, wipe history. Its their funeral. elsif ($num < @$test_results) { $#{$test_results} = $num - 1; } } } return release $ctx, $hub->count; } sub is_passing { my $self = shift; my $ctx = $self->ctx; my $hub = $ctx->hub; if( @_ ) { my ($bool) = @_; $hub->set_failed(0) if $bool; $hub->is_passing($bool); } return release $ctx, $hub->is_passing; } sub summary { my($self) = shift; return if $self->{no_log_results}; my $ctx = $self->ctx; my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}; $ctx->release; return map { $_ ? $_->{'ok'} : () } @$data; } sub details { my $self = shift; return if $self->{no_log_results}; my $ctx = $self->ctx; my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}; $ctx->release; return @$data; } sub find_TODO { my( $self, $pack, $set, $new_value ) = @_; my $ctx = $self->ctx; $pack ||= $ctx->trace->package || $self->exported_to; $ctx->release; return unless $pack; no strict 'refs'; ## no critic no warnings 'once'; my $old_value = ${ $pack . '::TODO' }; $set and ${ $pack . '::TODO' } = $new_value; return $old_value; } sub todo { my( $self, $pack ) = @_; local $Level = $Level + 1; my $ctx = $self->ctx; $ctx->release; my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}; return $meta->[-1]->[1] if $meta && @$meta; $pack ||= $ctx->trace->package; return unless $pack; no strict 'refs'; ## no critic no warnings 'once'; return ${ $pack . '::TODO' }; } sub in_todo { my $self = shift; local $Level = $Level + 1; my $ctx = $self->ctx; $ctx->release; my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}; return 1 if $meta && @$meta; my $pack = $ctx->trace->package || return 0; no strict 'refs'; ## no critic no warnings 'once'; my $todo = ${ $pack . '::TODO' }; return 0 unless defined $todo; return 0 if "$todo" eq ''; return 1; } sub todo_start { my $self = shift; my $message = @_ ? shift : ''; my $ctx = $self->ctx; my $hub = $ctx->hub; my $filter = $hub->pre_filter(sub { my ($active_hub, $e) = @_; # Turn a diag into a todo diag return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag'; # Set todo on ok's if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) { $e->set_todo($message); $e->set_effective_pass(1); if (my $result = $e->get_meta(__PACKAGE__)) { $result->{reason} ||= $message; $result->{type} ||= 'todo'; $result->{ok} = 1; } } return $e; }, inherit => 1); push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message]; $ctx->release; return; } sub todo_end { my $self = shift; my $ctx = $self->ctx; my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}}; $ctx->throw('todo_end() called without todo_start()') unless $set; $ctx->hub->pre_unfilter($set->[0]); $ctx->release; return; } sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms) my( $self ) = @_; my $ctx = $self->ctx; my $trace = $ctx->trace; $ctx->release; return wantarray ? $trace->call : $trace->package; } sub _try { my( $self, $code, %opts ) = @_; my $error; my $return; { local $!; # eval can mess up $! local $@; # don't set $@ in the test local $SIG{__DIE__}; # don't trip an outside DIE handler. $return = eval { $code->() }; $error = $@; } die $error if $error and $opts{die_on_fail}; return wantarray ? ( $return, $error ) : $return; } sub _ending { my $self = shift; my ($ctx, $real_exit_code, $new) = @_; unless ($ctx) { my $octx = $self->ctx; $ctx = $octx->snapshot; $octx->release; } return if $ctx->hub->no_ending; return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++; # Don't bother with an ending if this is a forked copy. Only the parent # should do the ending. return unless $self->{Original_Pid} == $$; my $hub = $ctx->hub; return if $hub->bailed_out; my $plan = $hub->plan; my $count = $hub->count; my $failed = $hub->failed; my $passed = $hub->is_passing; return unless $plan || $count || $failed; # Ran tests but never declared a plan or hit done_testing if( !$hub->plan and $hub->count ) { $self->diag("Tests were run but no plan was declared and done_testing() was not seen."); if($real_exit_code) { $self->diag(<<"FAIL"); Looks like your test exited with $real_exit_code just after $count. FAIL $$new ||= $real_exit_code; return; } # But if the tests ran, handle exit code. if($failed > 0) { my $exit_code = $failed <= 254 ? $failed : 254; $$new ||= $exit_code; return; } $$new ||= 254; return; } if ($real_exit_code && !$count) { $self->diag("Looks like your test exited with $real_exit_code before it could output anything."); $$new ||= $real_exit_code; return; } return if $plan && "$plan" eq 'SKIP'; if (!$count) { $self->diag('No tests run!'); $$new ||= 255; return; } if ($real_exit_code) { $self->diag(<<"FAIL"); Looks like your test exited with $real_exit_code just after $count. FAIL $$new ||= $real_exit_code; return; } if ($plan eq 'NO PLAN') { $ctx->plan( $count ); $plan = $hub->plan; } # Figure out if we passed or failed and print helpful messages. my $num_extra = $count - $plan; if ($num_extra != 0) { my $s = $plan == 1 ? '' : 's'; $self->diag(<<"FAIL"); Looks like you planned $plan test$s but ran $count. FAIL } if ($failed) { my $s = $failed == 1 ? '' : 's'; my $qualifier = $num_extra == 0 ? '' : ' run'; $self->diag(<<"FAIL"); Looks like you failed $failed test$s of $count$qualifier. FAIL } if (!$passed && !$failed && $count && !$num_extra) { $ctx->diag(<<"FAIL"); All assertions passed, but errors were encountered. FAIL } my $exit_code = 0; if ($failed) { $exit_code = $failed <= 254 ? $failed : 254; } elsif ($num_extra != 0) { $exit_code = 255; } elsif (!$passed) { $exit_code = 255; } $$new ||= $exit_code; return; } # Some things used this even though it was private... I am looking at you # Test::Builder::Prefix... sub _print_comment { my( $self, $fh, @msgs ) = @_; return if $self->no_diag; return unless @msgs; # Prevent printing headers when compiling (i.e. -c) return if $^C; # Smash args together like print does. # Convert undef to 'undef' so its readable. my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs; # Escape the beginning, _print will take care of the rest. $msg =~ s/^/# /; local( $\, $", $, ) = ( undef, ' ', '' ); print $fh $msg; return 0; } # This is used by Test::SharedFork to turn on IPC after the fact. Not # documenting because I do not want it used. The method name is borrowed from # Test::Builder 2 # Once Test2 stuff goes stable this method will be removed and Test::SharedFork # will be made smarter. sub coordinate_forks { my $self = shift; { local ($@, $!); require Test2::IPC; } Test2::IPC->import; Test2::API::test2_ipc_enable_polling(); Test2::API::test2_load(); my $ipc = Test2::IPC::apply_ipc($self->{Stack}); $ipc->set_no_fatal(1); Test2::API::test2_no_wait(1); } sub no_log_results { $_[0]->{no_log_results} = 1 } 1; __END__ =head1 NAME Test::Builder - Backend for building test libraries =head1 SYNOPSIS package My::Test::Module; use base 'Test::Builder::Module'; my $CLASS = __PACKAGE__; sub ok { my($test, $name) = @_; my $tb = $CLASS->builder; $tb->ok($test, $name); } =head1 DESCRIPTION L and L have proven to be popular testing modules, but they're not always flexible enough. Test::Builder provides a building block upon which to write your own test libraries I. =head2 Construction =over 4 =item B my $Test = Test::Builder->new; Returns a Test::Builder object representing the current state of the test. Since you only run one test per program C always returns the same Test::Builder object. No matter how many times you call C, you're getting the same object. This is called a singleton. This is done so that multiple modules share such global information as the test counter and where test output is going. If you want a completely new Test::Builder object different from the singleton, use C. =item B my $Test = Test::Builder->create; Ok, so there can be more than one Test::Builder object and this is how you get it. You might use this instead of C if you're testing a Test::Builder based module, but otherwise you probably want C. B: the implementation is not complete. C, for example, is still shared by B Test::Builder objects, even ones created using this method. Also, the method name may change in the future. =item B $builder->subtest($name, \&subtests, @args); See documentation of C in Test::More. C also, and optionally, accepts arguments which will be passed to the subtests reference. =item B diag $builder->name; Returns the name of the current builder. Top level builders default to C<$0> (the name of the executable). Child builders are named via the C method. If no name is supplied, will be named "Child of $parent->name". =item B $Test->reset; Reinitializes the Test::Builder singleton to its original state. Mostly useful for tests run in persistent environments where the same test might be run multiple times in the same process. =back =head2 Setting up tests These methods are for setting up tests and declaring how many there are. You usually only want to call one of these methods. =over 4 =item B $Test->plan('no_plan'); $Test->plan( skip_all => $reason ); $Test->plan( tests => $num_tests ); A convenient way to set up your tests. Call this and Test::Builder will print the appropriate headers and take the appropriate actions. If you call C, don't call any of the other methods below. =item B my $max = $Test->expected_tests; $Test->expected_tests($max); Gets/sets the number of tests we expect this test to run and prints out the appropriate headers. =item B $Test->no_plan; Declares that this test will run an indeterminate number of tests. =item B $Test->done_testing(); $Test->done_testing($num_tests); Declares that you are done testing, no more tests will be run after this point. If a plan has not yet been output, it will do so. $num_tests is the number of tests you planned to run. If a numbered plan was already declared, and if this contradicts, a failing test will be run to reflect the planning mistake. If C was declared, this will override. If C is called twice, the second call will issue a failing test. If C<$num_tests> is omitted, the number of tests run will be used, like no_plan. C is, in effect, used when you'd want to use C, but safer. You'd use it like so: $Test->ok($a == $b); $Test->done_testing(); Or to plan a variable number of tests: for my $test (@tests) { $Test->ok($test); } $Test->done_testing(scalar @tests); =item B $plan = $Test->has_plan Find out whether a plan has been defined. C<$plan> is either C (no plan has been set), C (indeterminate # of tests) or an integer (the number of expected tests). =item B $Test->skip_all; $Test->skip_all($reason); Skips all the tests, using the given C<$reason>. Exits immediately with 0. =item B my $pack = $Test->exported_to; $Test->exported_to($pack); Tells Test::Builder what package you exported your functions to. This method isn't terribly useful since modules which share the same Test::Builder object might get exported to different packages and only the last one will be honored. =back =head2 Running tests These actually run the tests, analogous to the functions in Test::More. They all return true if the test passed, false if the test failed. C<$name> is always optional. =over 4 =item B $Test->ok($test, $name); Your basic test. Pass if C<$test> is true, fail if $test is false. Just like Test::Simple's C. =item B $Test->is_eq($got, $expected, $name); Like Test::More's C. Checks if C<$got eq $expected>. This is the string version. C only ever matches another C. =item B $Test->is_num($got, $expected, $name); Like Test::More's C. Checks if C<$got == $expected>. This is the numeric version. C only ever matches another C. =item B $Test->isnt_eq($got, $dont_expect, $name); Like L's C. Checks if C<$got ne $dont_expect>. This is the string version. =item B $Test->isnt_num($got, $dont_expect, $name); Like L's C. Checks if C<$got ne $dont_expect>. This is the numeric version. =item B $Test->like($thing, qr/$regex/, $name); $Test->like($thing, '/$regex/', $name); Like L's C. Checks if $thing matches the given C<$regex>. =item B $Test->unlike($thing, qr/$regex/, $name); $Test->unlike($thing, '/$regex/', $name); Like L's C. Checks if $thing B the given C<$regex>. =item B $Test->cmp_ok($thing, $type, $that, $name); Works just like L's C. $Test->cmp_ok($big_num, '!=', $other_big_num); =back =head2 Other Testing Methods These are methods which are used in the course of writing a test but are not themselves tests. =over 4 =item B $Test->BAIL_OUT($reason); Indicates to the L that things are going so badly all testing should terminate. This includes running any additional test scripts. It will exit with 255. =for deprecated BAIL_OUT() used to be BAILOUT() =item B $Test->skip; $Test->skip($why); Skips the current test, reporting C<$why>. =item B $Test->todo_skip; $Test->todo_skip($why); Like C, only it will declare the test as failing and TODO. Similar to print "not ok $tnum # TODO $why\n"; =begin _unimplemented =item B $Test->skip_rest; $Test->skip_rest($reason); Like C, only it skips all the rest of the tests you plan to run and terminates the test. If you're running under C, it skips once and terminates the test. =end _unimplemented =back =head2 Test building utility methods These methods are useful when writing your own test methods. =over 4 =item B $Test->maybe_regex(qr/$regex/); $Test->maybe_regex('/$regex/'); This method used to be useful back when Test::Builder worked on Perls before 5.6 which didn't have qr//. Now its pretty useless. Convenience method for building testing functions that take regular expressions as arguments. Takes a quoted regular expression produced by C, or a string representing a regular expression. Returns a Perl value which may be used instead of the corresponding regular expression, or C if its argument is not recognized. For example, a version of C, sans the useful diagnostic messages, could be written as: sub laconic_like { my ($self, $thing, $regex, $name) = @_; my $usable_regex = $self->maybe_regex($regex); die "expecting regex, found '$regex'\n" unless $usable_regex; $self->ok($thing =~ m/$usable_regex/, $name); } =item B my $is_fh = $Test->is_fh($thing); Determines if the given C<$thing> can be used as a filehandle. =cut =back =head2 Test style =over 4 =item B $Test->level($how_high); How far up the call stack should C<$Test> look when reporting where the test failed. Defaults to 1. Setting C<$Test::Builder::Level> overrides. This is typically useful localized: sub my_ok { my $test = shift; local $Test::Builder::Level = $Test::Builder::Level + 1; $TB->ok($test); } To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant. =item B $Test->use_numbers($on_or_off); Whether or not the test should output numbers. That is, this if true: ok 1 ok 2 ok 3 or this if false ok ok ok Most useful when you can't depend on the test output order, such as when threads or forking is involved. Defaults to on. =item B $Test->no_diag($no_diag); If set true no diagnostics will be printed. This includes calls to C. =item B $Test->no_ending($no_ending); Normally, Test::Builder does some extra diagnostics when the test ends. It also changes the exit code as described below. If this is true, none of that will be done. =item B $Test->no_header($no_header); If set to true, no "1..N" header will be printed. =back =head2 Output Controlling where the test output goes. It's ok for your test to change where STDOUT and STDERR point to, Test::Builder's default output settings will not be affected. =over 4 =item B $Test->diag(@msgs); Prints out the given C<@msgs>. Like C, arguments are simply appended together. Normally, it uses the C handle, but if this is for a TODO test, the C handle is used. Output will be indented and marked with a # so as not to interfere with test output. A newline will be put on the end if there isn't one already. We encourage using this rather than calling print directly. Returns false. Why? Because C is often used in conjunction with a failing test (C) it "passes through" the failure. return ok(...) || diag(...); =for blame transfer Mark Fowler =item B $Test->note(@msgs); Like C, but it prints to the C handle so it will not normally be seen by the user except in verbose mode. =item B my @dump = $Test->explain(@msgs); Will dump the contents of any references in a human readable format. Handy for things like... is_deeply($have, $want) || diag explain $have; or is_deeply($have, $want) || note explain $have; =item B =item B =item B my $filehandle = $Test->output; $Test->output($filehandle); $Test->output($filename); $Test->output(\$scalar); These methods control where Test::Builder will print its output. They take either an open C<$filehandle>, a C<$filename> to open and write to or a C<$scalar> reference to append to. It will always return a C<$filehandle>. B is where normal "ok/not ok" test output goes. Defaults to STDOUT. B is where diagnostic output on test failures and C goes. It is normally not read by Test::Harness and instead is displayed to the user. Defaults to STDERR. C is used instead of C for the diagnostics of a failing TODO test. These will not be seen by the user. Defaults to STDOUT. =item reset_outputs $tb->reset_outputs; Resets all the output filehandles back to their defaults. =item carp $tb->carp(@message); Warns with C<@message> but the message will appear to come from the point where the original test function was called (C<< $tb->caller >>). =item croak $tb->croak(@message); Dies with C<@message> but the message will appear to come from the point where the original test function was called (C<< $tb->caller >>). =back =head2 Test Status and Info =over 4 =item B This will turn off result long-term storage. Calling this method will make C
and C useless. You may want to use this if you are running enough tests to fill up all available memory. Test::Builder->new->no_log_results(); There is no way to turn it back on. =item B my $curr_test = $Test->current_test; $Test->current_test($num); Gets/sets the current test number we're on. You usually shouldn't have to set this. If set forward, the details of the missing tests are filled in as 'unknown'. if set backward, the details of the intervening tests are deleted. You can erase history if you really want to. =item B my $ok = $builder->is_passing; Indicates if the test suite is currently passing. More formally, it will be false if anything has happened which makes it impossible for the test suite to pass. True otherwise. For example, if no tests have run C will be true because even though a suite with no tests is a failure you can add a passing test to it and start passing. Don't think about it too much. =item B my @tests = $Test->summary; A simple summary of the tests so far. True for pass, false for fail. This is a logical pass/fail, so todos are passes. Of course, test #1 is $tests[0], etc... =item B
my @tests = $Test->details; Like C, but with a lot more detail. $tests[$test_num - 1] = { 'ok' => is the test considered a pass? actual_ok => did it literally say 'ok'? name => name of the test (if any) type => type of test (if any, see below). reason => reason for the above (if any) }; 'ok' is true if Test::Harness will consider the test to be a pass. 'actual_ok' is a reflection of whether or not the test literally printed 'ok' or 'not ok'. This is for examining the result of 'todo' tests. 'name' is the name of the test. 'type' indicates if it was a special test. Normal tests have a type of ''. Type can be one of the following: skip see skip() todo see todo() todo_skip see todo_skip() unknown see below Sometimes the Test::Builder test counter is incremented without it printing any test output, for example, when C is changed. In these cases, Test::Builder doesn't know the result of the test, so its type is 'unknown'. These details for these tests are filled in. They are considered ok, but the name and actual_ok is left C. For example "not ok 23 - hole count # TODO insufficient donuts" would result in this structure: $tests[22] = # 23 - 1, since arrays start from 0. { ok => 1, # logically, the test passed since its todo actual_ok => 0, # in absolute terms, it failed name => 'hole count', type => 'todo', reason => 'insufficient donuts' }; =item B my $todo_reason = $Test->todo; my $todo_reason = $Test->todo($pack); If the current tests are considered "TODO" it will return the reason, if any. This reason can come from a C<$TODO> variable or the last call to C. Since a TODO test does not need a reason, this function can return an empty string even when inside a TODO block. Use C<< $Test->in_todo >> to determine if you are currently inside a TODO block. C is about finding the right package to look for C<$TODO> in. It's pretty good at guessing the right package to look at. It first looks for the caller based on C<$Level + 1>, since C is usually called inside a test function. As a last resort it will use C. Sometimes there is some confusion about where C should be looking for the C<$TODO> variable. If you want to be sure, tell it explicitly what $pack to use. =item B my $todo_reason = $Test->find_TODO(); my $todo_reason = $Test->find_TODO($pack); Like C but only returns the value of C<$TODO> ignoring C. Can also be used to set C<$TODO> to a new value while returning the old value: my $old_reason = $Test->find_TODO($pack, 1, $new_reason); =item B my $in_todo = $Test->in_todo; Returns true if the test is currently inside a TODO block. =item B $Test->todo_start(); $Test->todo_start($message); This method allows you declare all subsequent tests as TODO tests, up until the C method has been called. The C and C<$TODO> syntax is generally pretty good about figuring out whether or not we're in a TODO test. However, often we find that this is not possible to determine (such as when we want to use C<$TODO> but the tests are being executed in other packages which can't be inferred beforehand). Note that you can use this to nest "todo" tests $Test->todo_start('working on this'); # lots of code $Test->todo_start('working on that'); # more code $Test->todo_end; $Test->todo_end; This is generally not recommended, but large testing systems often have weird internal needs. We've tried to make this also work with the TODO: syntax, but it's not guaranteed and its use is also discouraged: TODO: { local $TODO = 'We have work to do!'; $Test->todo_start('working on this'); # lots of code $Test->todo_start('working on that'); # more code $Test->todo_end; $Test->todo_end; } Pick one style or another of "TODO" to be on the safe side. =item C $Test->todo_end; Stops running tests as "TODO" tests. This method is fatal if called without a preceding C method call. =item B my $package = $Test->caller; my($pack, $file, $line) = $Test->caller; my($pack, $file, $line) = $Test->caller($height); Like the normal C, except it reports according to your C. C<$height> will be added to the C. If C winds up off the top of the stack it report the highest context. =back =head1 EXIT CODES If all your tests passed, Test::Builder will exit with zero (which is normal). If anything failed it will exit with how many failed. If you run less (or more) tests than you planned, the missing (or extras) will be considered failures. If no tests were ever run Test::Builder will throw a warning and exit with 255. If the test died, even after having successfully completed all its tests, it will still be considered a failure and will exit with 255. So the exit codes are... 0 all tests successful 255 test died or all passed but wrong # of tests run any other number how many failed (including missing or extras) If you fail more than 254 tests, it will be reported as 254. =head1 THREADS In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is shared by all threads. This means if one thread sets the test number using C they will all be effected. While versions earlier than 5.8.1 had threads they contain too many bugs to support. Test::Builder is only thread-aware if threads.pm is loaded I Test::Builder. You can directly disable thread support with one of the following: $ENV{T2_NO_IPC} = 1 or no Test2::IPC; or Test2::API::test2_ipc_disable() =head1 MEMORY An informative hash, accessible via C, is stored for each test you perform. So memory usage will scale linearly with each test run. Although this is not a problem for most test suites, it can become an issue if you do large (hundred thousands to million) combinatorics tests in the same run. In such cases, you are advised to either split the test file into smaller ones, or use a reverse approach, doing "normal" (code) compares and triggering C should anything go unexpected. Future versions of Test::Builder will have a way to turn history off. =head1 EXAMPLES CPAN can provide the best examples. L, L, L and L all use Test::Builder. =head1 SEE ALSO =head2 INTERNALS L, L =head2 LEGACY L, L =head2 EXTERNAL L =head1 AUTHORS Original code by chromatic, maintained by Michael G Schwern Eschwern@pobox.comE =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2002-2008 by chromatic Echromatic@wgz.orgE and Michael G Schwern Eschwern@pobox.comE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F PK!z{ã9ÍÃÍÃperl5/Test/Deep.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep; use Carp qw( confess ); use Test::Deep::Cache; use Test::Deep::Stack; use Test::Deep::RegexpVersion; require overload; use Scalar::Util; my $Test; unless (defined $Test::Deep::NoTest::NoTest) { # for people who want eq_deeply but not Test::Builder require Test::Builder; $Test = Test::Builder->new; } our ($Stack, %Compared, $CompareCache, %WrapCache, $Shallow); our $VERSION = '1.130'; $VERSION =~ tr/_//d; require Exporter; our @ISA = qw( Exporter ); our $Snobby = 1; # should we compare classes? our $Expects = 0; # are we comparing got vs expect or expect vs expect our $LeafWrapper; # to wrap simple values in a test; if not set, shallow() our $DNE = \""; our $DNE_ADDR = Scalar::Util::refaddr($DNE); # if no sub name is supplied then we use the package name in lower case my @constructors = ( All => "", Any => "", Array => "", ArrayEach => "array_each", ArrayElementsOnly => "", ArrayLength => "", ArrayLengthOnly => "", Blessed => "", Boolean => "bool", Code => "", Hash => "", HashEach => "hash_each", HashKeys => "", HashKeysOnly => "", Ignore => "", Isa => "Isa", ListMethods => "", Methods => "", None => "", Number => "num", Obj => "obj_isa", RefType => "", Regexp => "re", RegexpMatches => "", RegexpOnly => "", RegexpRef => "", RegexpRefOnly => "", ScalarRef => "scalref", ScalarRefOnly => "", Shallow => "", String => "str", ); my @CONSTRUCTORS_FROM_CLASSES; while (my ($pkg, $name) = splice @constructors, 0, 2) { $name = lc($pkg) unless $name; my $full_pkg = "Test::Deep::$pkg"; my $file = "$full_pkg.pm"; $file =~ s#::#/#g; my $sub = sub { require $file; return $full_pkg->new(@_); }; { no strict 'refs'; *{$name} = $sub; } push @CONSTRUCTORS_FROM_CLASSES, $name; } { our @EXPORT_OK = qw( descend render_stack cmp_details deep_diag true false ); our %EXPORT_TAGS; $EXPORT_TAGS{preload} = []; $EXPORT_TAGS{v0} = [ qw( Isa blessed obj_isa all any array array_each arrayelementsonly arraylength arraylengthonly bag bool cmp_bag cmp_deeply cmp_methods cmp_set code eq_deeply hash hash_each hashkeys hashkeysonly ignore isa listmethods methods noclass none noneof num re reftype regexpmatches regexponly regexpref regexprefonly scalarrefonly scalref set shallow str subbagof subhashof subsetof superbagof superhashof supersetof useclass ) ]; $EXPORT_TAGS{v1} = [ qw( obj_isa all any array array_each arrayelementsonly arraylength arraylengthonly bag bool cmp_bag cmp_deeply cmp_methods cmp_set code eq_deeply hash hash_each hashkeys hashkeysonly ignore listmethods methods noclass none noneof num re reftype regexpmatches regexponly regexpref regexprefonly scalarrefonly scalref set shallow str subbagof subhashof subsetof superbagof superhashof supersetof useclass ) ]; our @EXPORT = @{ $EXPORT_TAGS{ v0 } }; $EXPORT_TAGS{all} = [ @EXPORT, @EXPORT_OK ]; } sub import { my $self = shift; my $from_notest = grep {$_ eq '_notest'} @_; if ($from_notest) { @_ = grep {$_ ne '_notest'} @_; } else { require Test::Builder; $Test = Test::Builder->new; } my @sans_preload = grep {; $_ ne ':preload' } @_; if (@_ != @sans_preload) { require Test::Deep::All; require Test::Deep::Any; require Test::Deep::Array; require Test::Deep::ArrayEach; require Test::Deep::ArrayElementsOnly; require Test::Deep::ArrayLength; require Test::Deep::ArrayLengthOnly; require Test::Deep::Blessed; require Test::Deep::Boolean; require Test::Deep::Cache::Simple; require Test::Deep::Cache; require Test::Deep::Class; require Test::Deep::Cmp; require Test::Deep::Code; require Test::Deep::Hash; require Test::Deep::HashEach; require Test::Deep::HashElements; require Test::Deep::HashKeys; require Test::Deep::HashKeysOnly; require Test::Deep::Ignore; require Test::Deep::Isa; require Test::Deep::ListMethods; require Test::Deep::Methods; require Test::Deep::MM; require Test::Deep::None; require Test::Deep::Number; require Test::Deep::Obj; require Test::Deep::Ref; require Test::Deep::RefType; require Test::Deep::Regexp; require Test::Deep::RegexpMatches; require Test::Deep::RegexpOnly; require Test::Deep::RegexpRef; require Test::Deep::RegexpRefOnly; require Test::Deep::RegexpVersion; require Test::Deep::ScalarRef; require Test::Deep::ScalarRefOnly; require Test::Deep::Set; require Test::Deep::Shallow; require Test::Deep::Stack; require Test::Deep::String; } $self->export_to_level(1, $self, @_); } # this is ugly, I should never have exported a sub called isa now I # have to try figure out if the recipient wanted my isa or if a class # imported us and UNIVERSAL::isa is being called on that class. # Luckily our isa always expects 1 argument and U::isa always expects # 2, so we can figure out (assuming the caller is not buggy). sub isa { if (@_ == 1) { goto &Isa; } else { goto &UNIVERSAL::isa; } } sub cmp_deeply { my ($d1, $d2, $name) = @_; my ($ok, $stack) = cmp_details($d1, $d2); if (not $Test->ok($ok, $name)) { my $diag = deep_diag($stack); $Test->diag($diag); } return $ok; } sub cmp_details { my ($d1, $d2) = @_; local $Stack = Test::Deep::Stack->new; local $CompareCache = Test::Deep::Cache->new; local %WrapCache; my $ok = descend($d1, $d2); return ($ok, $Stack); } sub eq_deeply { my ($d1, $d2) = @_; my ($ok) = cmp_details($d1, $d2); return $ok } sub eq_deeply_cache { # this is like cross between eq_deeply and descend(). It doesn't start # with a new $CompareCache but if the comparison fails it will leave # $CompareCache as if nothing happened. However, if the comparison # succeeds then $CompareCache retains all the new information # this allows Set and Bag to handle circular refs my ($d1, $d2, $name) = @_; local $Stack = Test::Deep::Stack->new; $CompareCache->local; my $ok = descend($d1, $d2); $CompareCache->finish($ok); return $ok; } sub deep_diag { my $stack = shift; # ick! incArrow and other things expect the stack has to be visible # in a well known place . TODO clean this up local $Stack = $stack; my $where = render_stack('$data', $stack); confess "No stack to diagnose" unless $stack; my $last = $stack->getLast; my $diag; my $message; my $got; my $expected; my $exp = $last->{exp}; if (Scalar::Util::blessed($exp)) { if ($exp->can("diagnostics")) { $diag = $exp->diagnostics($where, $last); $diag =~ s/\n+$/\n/; } else { if ($exp->can("diag_message")) { $message = $exp->diag_message($where); } } } if (not defined $diag) { $got = $exp->renderGot($last->{got}) unless defined $got; $expected = $exp->renderExp unless defined $expected; $message = "Compared $where" unless defined $message; $diag = <isa("Test::Deep::Cmp")) { my $where = $Stack->render('$data'); confess "Found a special comparison in $where\nYou can only use specials in the expects structure"; } if (ref $d1 and ref $d2) { # this check is only done when we're comparing 2 expecteds against each # other if ($Expects and Scalar::Util::blessed($d1) and $d1->isa("Test::Deep::Cmp")) { # check they are the same class return 0 unless Test::Deep::blessed(Scalar::Util::blessed($d2))->descend($d1); if ($d1->can("compare")) { return $d1->compare($d2); } } my $s1 = Scalar::Util::refaddr($d1); my $s2 = Scalar::Util::refaddr($d2); if ($s1 eq $s2) { return 1; } if ($CompareCache->cmp($d1, $d2)) { # we've tried comparing these already so either they turned out to # be the same or we must be in a loop and we have to assume they're # the same return 1; } else { $CompareCache->add($d1, $d2) } } $d2 = wrap($d2); $Stack->push({exp => $d2, got => $d1}); if (ref($d1) and (Scalar::Util::refaddr($d1) == $DNE_ADDR)) { # whatever it was supposed to be, it didn't exist and so it's an # automatic fail return 0; } if ($d2->descend($d1)) { # print "d1 = $d1, d2 = $d2\nok\n"; $Stack->pop; return 1; } else { # print "d1 = $d1, d2 = $d2\nnot ok\n"; return 0; } } sub wrap { my $data = shift; my $class = Scalar::Util::blessed($data); return $data if defined $class and $data->isa("Test::Deep::Cmp"); if (defined $class and $data->can('as_test_deep_cmp')) { my $cmp = $data->as_test_deep_cmp; return $cmp if $cmp->isa('Test::Deep::Cmp'); Carp::confess("object in expected structure provides as_test_deep_cmp but it did not return a Test::Deep::Cmp"); } my $reftype = _td_reftype($data); my $cmp; if($reftype eq '') { $cmp = $Test::Deep::LeafWrapper ? $Test::Deep::LeafWrapper->($data) : shallow($data); } else { my $addr = Scalar::Util::refaddr($data); return $WrapCache{$addr} if $WrapCache{$addr}; if($reftype eq 'ARRAY') { $cmp = array($data); } elsif($reftype eq 'HASH') { $cmp = hash($data); } elsif($reftype eq 'SCALAR' or $reftype eq 'REF') { $cmp = scalref($data); } elsif(($reftype eq 'Regexp') or ($reftype eq 'REGEXP')) { $cmp = regexpref($data); } else { $cmp = $Test::Deep::LeafWrapper ? $Test::Deep::LeafWrapper->($data) : shallow($data); } $WrapCache{$addr} = $cmp; } return $cmp; } sub _td_reftype { my $val = shift; my $reftype = Scalar::Util::reftype($val); return '' unless defined $reftype; return $reftype unless $Test::Deep::RegexpVersion::OldStyle; my $blessed = Scalar::Util::blessed($val); return $reftype unless defined $blessed; if ($blessed && $blessed eq "Regexp" and $reftype eq "SCALAR") { $reftype = "Regexp" } return $reftype; } sub render_stack { my ($var, $stack) = @_; return $stack->render($var); } sub cmp_methods { local $Test::Builder::Level = $Test::Builder::Level + 1; return cmp_deeply(shift, methods(@{shift()}), shift); } sub requireclass { require Test::Deep::Class; my $val = shift; return Test::Deep::Class->new(1, $val); } # docs and export say this is called useclass, doh! *useclass = \&requireclass; sub noclass { require Test::Deep::Class; my $val = shift; return Test::Deep::Class->new(0, $val); } sub set { require Test::Deep::Set; return Test::Deep::Set->new(1, "", @_); } sub supersetof { require Test::Deep::Set; return Test::Deep::Set->new(1, "sup", @_); } sub subsetof { require Test::Deep::Set; return Test::Deep::Set->new(1, "sub", @_); } sub noneof { require Test::Deep::Set; return Test::Deep::Set->new(1, "none", @_); } sub cmp_set { local $Test::Builder::Level = $Test::Builder::Level + 1; return cmp_deeply(shift, set(@{shift()}), shift); } sub bag { require Test::Deep::Set; return Test::Deep::Set->new(0, "", @_); } sub superbagof { require Test::Deep::Set; return Test::Deep::Set->new(0, "sup", @_); } sub subbagof { require Test::Deep::Set; return Test::Deep::Set->new(0, "sub", @_); } sub cmp_bag { local $Test::Builder::Level = $Test::Builder::Level + 1; my $ref = ref($_[1]) || ""; confess "Argument 2 to cmp_bag is not an ARRAY ref (".render_val($_[1]).")" unless $ref eq "ARRAY"; return cmp_deeply(shift, bag(@{shift()}), shift); } sub superhashof { require Test::Deep::Hash; my $val = shift; return Test::Deep::SuperHash->new($val); } sub subhashof { require Test::Deep::Hash; my $val = shift; return Test::Deep::SubHash->new($val); } sub true { bool(1); } sub false { bool(0); } sub builder { if (@_) { $Test = shift; } return $Test; } 1; __END__ =head1 NAME Test::Deep - Extremely flexible deep comparison =head1 SYNOPSIS use Test::More tests => $Num_Tests; use Test::Deep; cmp_deeply( $actual_horrible_nested_data_structure, $expected_horrible_nested_data_structure, "got the right horrible nested data structure" ); cmp_deeply( $object, methods(name => "John", phone => "55378008"), "object methods ok" ); cmp_deeply( \@array, [$hash1, $hash2, ignore()], "first 2 elements are as expected, ignoring 3" ); cmp_deeply( $object, noclass({value => 5}), "object looks ok, not checking its class" ); cmp_deeply( \@result, bag('a', 'b', {key => [1, 2]}), "array has the 3 things we wanted in some order" ); =head1 DESCRIPTION If you don't know anything about automated testing in Perl then you should probably read about L and L before preceding. Test::Deep uses the L framework. Test::Deep gives you very flexible ways to check that the result you got is the result you were expecting. At its simplest it compares two structures by going through each level, ensuring that the values match, that arrays and hashes have the same elements and that references are blessed into the correct class. It also handles circular data structures without getting caught in an infinite loop. Where it becomes more interesting is in allowing you to do something besides simple exact comparisons. With strings, the C operator checks that 2 strings are exactly equal but sometimes that's not what you want. When you don't know exactly what the string should be but you do know some things about how it should look, C is no good and you must use pattern matching instead. Test::Deep provides pattern matching for complex data structures Test::Deep has B> of exports. See L below. =head1 EXAMPLES How Test::Deep works is much easier to understand by seeing some examples. =head2 Without Test::Deep Say you want to test a function which returns a string. You know that your string should be a 7 digit number beginning with 0, C is no good in this situation, you need a regular expression. So you could use Test::More's C function: like($string, qr/^0[0-9]{6}$/, "number looks good"); Similarly, to check that a string looks like a name, you could do: like($string, qr/^(Mr|Mrs|Miss) \w+ \w+$/, "got title, first and last name"); Now imagine your function produces a hash with some personal details in it. You want to make sure that there are 2 keys, Name and Phone and that the name looks like a name and the phone number looks like a phone number. You could do: $hash = make_person(); like($hash->{Name}, qr/^(Mr|Mrs|Miss) \w+ \w+$/, "name ok"); like($hash->{Phone}, qr/^0[0-9]{6}$/, "phone ok"); is(scalar keys %$hash, 2, "correct number of keys"); But that's not quite right, what if make_person has a serious problem and didn't even return a hash? We really need to write if (ref($hash) eq "HASH") { like($hash->{Name}, qr/^(Mr|Mrs|Miss) \w+ \w+$/, "name ok"); like($hash->{Phone}, qr/^0[0-9]{6}$/, "phone ok"); is(scalar keys %$hash, 2, "correct number of keys"); } else { fail("person not a hash"); fail("person not a hash"); fail("person not a hash"); # need 3 to keep the plan correct } Already this is getting messy, now imagine another entry in the hash, an array of children's names. This would require if (ref($hash) eq "HASH") { like($hash->{Name}, $name_pat, "name ok"); like($hash->{Phone}, '/^0d{6}$/', "phone ok"); my $cn = $hash->{ChildNames}; if (ref($cn) eq "ARRAY") { foreach my $child (@$cn) { like($child, $name_pat); } } else { fail("child names not an array") } } else { fail("person not a hash"); } This is a horrible mess and because we don't know in advance how many children's names there will be, we can't make a plan for our test anymore (actually, we could but it would make things even more complicated). Test::Deep to the rescue. =head2 With Test::Deep my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$'); cmp_deeply( $person, { Name => $name_re, Phone => re('^0d{6}$'), ChildNames => array_each($name_re) }, "person ok" ); This will do everything that the messy code above does and it will give a sensible message telling you exactly what went wrong if it finds a part of $person that doesn't match the pattern. C and C are special function imported from Test::Deep. They create a marker that tells Test::Deep that something different is happening here. Instead of just doing a simple comparison and checking are two things exactly equal, it should do something else. If a person was asked to check that 2 structures are equal, they could print them both out and compare them line by line. The markers above are similar to writing a note in red pen on one of the printouts telling the person that for this piece of the structure, they should stop doing simple line by line comparison and do something else. C means that Test::Deep should check that the current piece of data matches the regex in C<$regex>. C means that Test::Deep should expect the current piece of data to be an array and it should check that every element of that array matches C<$struct>. In this case, every element of C<< $person->{ChildNames} >> should look like a name. If say the 3rd one didn't you would get an error message something like Using Regexp on $data->{ChildNames}[3] got : 'Queen John Paul Sartre' expect : /^(Mr|Mrs|Miss) \w+ \w+$/ There are lots of other special comparisons available, see L below for the full list. =head2 Reusing structures Test::Deep is good for reusing test structures so you can do this my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$'); my $person_cmp = { Name => $name_re, Phone => re('^0d{6}$'), ChildNames => array_each($name_re) }; cmp_deeply($person1, $person_cmp, "person ok"); cmp_deeply($person2, $person_cmp, "person ok"); cmp_deeply($person3, $person_cmp, "person ok"); You can even put $person_cmp in a module and let other people use it when they are writing test scripts for modules that use your modules. To make things a little more difficult, lets change the person data structure so that instead of a list of ChildNames, it contains a list of hashes, one for each child. So in fact our person structure will contain other person structures which may contain other person structures and so on. This is easy to handle with Test::Deep because Test::Deep structures can include themselves. Simply do my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$'); my $person_cmp = { Name => $name_re, Phone => re('^0d{6}$'), # note no mention of Children here }; $person_cmp->{Children} = array_each($person_cmp); cmp_deeply($person, $person_cmp, "person ok"); This will now check that $person->{Children} is an array and that every element of that array also matches C<$person_cmp>, this includes checking that its children also match the same pattern and so on. =head2 Circular data structures A circular data structure is one which loops back on itself, you can make one easily by doing my @b; my @a = (1, 2, 3, \@b); push(@b, \@a); now C<@a> contains a reference to be C<@b> and C<@b> contains a reference to C<@a>. This causes problems if you have a program that wants to look inside C<@a> and keep looking deeper and deeper at every level, it could get caught in an infinite loop looking into C<@a> then C<@b> then C<@a> then C<@b> and so on. Test::Deep avoids this problem so we can extend our example further by saying that a person should also list their parents. my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$'); my $person_cmp = { Name => $name_re, Phone => re('^0d{6}$'), # note no mention of Children here }; $person_cmp->{Children} = each_array($person_cmp); $person_cmp->{Parents} = each_array($person_cmp); cmp_deeply($person, $person_cmp, "person ok"); So this will check that for each child C<$child> in C<< $person->{Children} >> that the C<< $child->{Parents} >> matches C<$person_cmp> however it is smart enough not to get caught in an infinite loop where it keeps bouncing between the same Parent and Child. =head1 TERMINOLOGY C takes 3 arguments. C<$got> is the structure that you are checking, you must not include any special comparisons in this structure or you will get a fatal error. C<$expected> describes what Test::Deep will be looking for in $got. You can put special comparisons in $expected if you want to. As Test::Deep descends through the 2 structures, it compares them one piece at a time, so at any point in the process, Test::Deep is thinking about 2 things - the current value from C<$got> and the current value from C<$expected>. In the documentation, I call them C<$got_v> and C respectively. =head1 COMPARISON FUNCTIONS =head3 cmp_deeply my $ok = cmp_deeply($got, $expected, $name) C<$got> is the result to be checked. C<$expected> is the structure against which C<$got> will be check. C<$name> is the test name. This is the main comparison function, the others are just wrappers around this. C<$got> and C<$expected> are compared recursively. Each value in C<$expected> defines what's expected at the corresponding location in C<$got>. Simple scalars are compared with C. References to structures like hashes and arrays are compared recursively. Items in C<$expected>, though, can also represent complex tests that check for numbers in a given range, hashes with at least a certain set of keys, a string matching a regex, or many other things. See L for details. =head3 cmp_bag my $ok = cmp_bag(\@got, \@bag, $name) Is shorthand for cmp_deeply(\@got, bag(@bag), $name) I: Both arguments must be array refs. If they aren't an exception will be thrown. =head3 cmp_set my $ok = cmp_set(\@got, \@set, $name) Is shorthand for cmp_deeply(\@got, set(@set), $name) =head3 cmp_methods my $ok = cmp_methods(\@got, \@methods, $name) Is shorthand for cmp_deeply(\@got, methods(@methods), $name) =head3 eq_deeply my $ok = eq_deeply($got, $expected) This is the same as cmp_deeply() except it just returns true or false. It does not create diagnostics or talk to L, but if you want to use it in a non-testing environment then you should import it through L. For example use Test::Deep::NoTest; print "a equals b" unless eq_deeply($a, $b); otherwise the L framework will be loaded and testing messages will be output when your program ends. =head3 cmp_details ($ok, $stack) = cmp_details($got, $expected) This behaves much like eq_deeply, but it additionally allows you to produce diagnostics in case of failure by passing the value in C<$stack> to C. Do not make assumptions about the structure or content of C<$stack> and do not use it if C<$ok> contains a true value. See L for example uses. =head1 SPECIAL COMPARISONS PROVIDED In the documentation below, C<$got_v> is used to indicate any given value within the C<$got> structure. =head3 ignore cmp_deeply( $got, ignore() ); This makes Test::Deep skip tests on C<$got_v>. No matter what value C<$got_v> has, Test::Deep will think it's correct. This is useful if some part of the structure you are testing is very complicated and already tested elsewhere, or if it is unpredictable. cmp_deeply( $got, { name => 'John', random => ignore(), address => [ '5 A street', 'a town', 'a country' ], } ); is the equivalent of checking $got->{name} eq 'John'; exists $got->{random}; cmp_deeply($got->{address}, ['5 A street', 'a town', 'a country']); =head3 methods cmp_deeply( $got, methods(%hash) ); %hash is a hash of method call => expected value pairs. This lets you call methods on an object and check the result of each call. The methods will be called in the order supplied. If you want to pass arguments to the method you should wrap the method name and arguments in an array reference. cmp_deeply( $obj, methods(name => "John", ["favourite", "food"] => "taco") ); is roughly the equivalent of checking that $obj->name eq "John" $obj->favourite("food") eq "taco" The methods will be called in the order you supply them and will be called in scalar context. If you need to test methods called in list context then you should use C. B Just as in a normal test script, you need to be careful if the methods you call have side effects like changing the object or other objects in the structure. Although the order of the methods is fixed, the order of some other tests is not so if C<$expected> is { manager => methods(@manager_methods), coder => methods(@coder_methods) } there is no way to know which if manager and coder will be tested first. If the methods you are testing depend on and alter global variables or if manager and coder are the same object then you may run into problems. =head3 listmethods cmp_deeply( $got, listmethods(%hash) ); C<%hash> is a hash of pairs mapping method names to expected return values. This is almost identical to methods() except the methods are called in list context instead of scalar context. This means that the expected return values supplied must be in array references. cmp_deeply( $obj, listmethods( name => [ "John" ], ["favourites", "food"] => ["Mapo tofu", "Gongbao chicken"] ) ); is the equivalent of checking that cmp_deeply([$obj->name], ["John"]); cmp_deeply([$obj->favourites("food")], ["Mapo tofu", "Gongbao chicken"]); The methods will be called in the order you supply them. B The same caveats apply as for methods(). =head3 shallow cmp_deeply( $got, shallow($thing) ); C<$thing> is a ref. This prevents Test::Deep from looking inside C<$thing>. It allows you to check that C<$got_v> and C<$thing> are references to the same variable. So my @a = @b = (1, 2, 3); cmp_deeply(\@a, \@b); will pass because C<@a> and C<@b> have the same elements however cmp_deeply(\@a, shallow(\@b)) will fail because although C<\@a> and C<\@b> both contain C<1, 2, 3> they are references to different arrays. =head3 noclass cmp_deeply( $got, noclass($thing) ); C<$thing> is a structure to be compared against. This makes Test::Deep ignore the class of objects, so it just looks at the data they contain. Class checking will be turned off until Test::Deep is finished comparing C<$got_v> against C<$thing>. Once Test::Deep comes out of C<$thing> it will go back to its previous setting for checking class. This can be useful when you want to check that objects have been constructed correctly but you don't want to write lots of Ces. If C<@people> is an array of Person objects then cmp_deeply(\@people, [ bless {name => 'John', phone => '555-5555'}, "Person", bless {name => 'Anne', phone => '444-4444'}, "Person", ]); can be replaced with cmp_deeply(\@people, noclass([ {name => 'John', phone => '555-5555'}, {name => 'Anne', phone => '444-4444'} ])); However, this is testing so you should also check that the objects are blessed correctly. You could use a map to bless all those hashes or you could do a second test like cmp_deeply(\@people, array_each(isa("Person")); =head3 useclass cmp_deeply( $got, useclass($thing) ); This turns back on the class comparison while inside a C. cmp_deeply( $got, noclass( [ useclass( $object ) ] ) ) In this example the class of the array reference in C<$got> is ignored but the class of C<$object> is checked, as is the class of everything inside C<$object>. =head3 re cmp_deeply( $got, re($regexp, $capture_data, $flags) ); C<$regexp> is either a regular expression reference produced with C or a string which will be used to construct a regular expression. C<$capture_data> is optional and is used to check the strings captured by an regex. This should can be an array ref or a Test::Deep comparator that works on array refs. C<$flags> is an optional string which controls whether the regex runs as a global match. If C<$flags> is "g" then the regex will run as C. Without C<$capture_data>, this simply compares C<$got_v> with the regular expression provided. So cmp_deeply($got, [ re("ferg") ]) is the equivalent of $got->[0] =~ /ferg/ With C<$capture_data>, cmp_deeply($got, [re($regex, $capture_data)]) is the equivalent of my @data = $got->[0] =~ /$regex/; cmp_deeply(\@data, $capture_data); So you can do something simple like cmp_deeply($got, re(qr/(\d\d)(\w\w)/, [25, "ab" ])) to check that C<(\d\d)> was 25 and C<(\w\w)> was "ab" but you can also use Test::Deep objects to do more complex testing of the captured values cmp_deeply( "cat=2,dog=67,sheep=3,goat=2,dog=5", re( qr/(\D+)=\d+,?/, set(qw( cat sheep dog )), "g" ), ); here, the regex will match the string and will capture the animal names and check that they match the specified set, in this case it will fail, complaining that "goat" is not in the set. =head3 all cmp_deeply( $got, all(@expecteds) ); C<@expecteds> is an array of expected structures. This allows you to compare data against multiple expected results and make sure each of them matches. cmp_deeply($got, all(isa("Person"), methods(name => 'John'))) is equivalent to $got->isa("Person") $got->name eq 'John' If either test fails then the whole thing is considered a fail. This is a short-circuit test, the testing is stopped after the first failure, although in the future it may complete all tests so that diagnostics can be output for all failures. When reporting failure, the parts are counted from 1. Thanks to the magic of overloading, you can write any( re("^wi"), all(isa("Person"), methods(name => 'John')) ) as re("^wi") | isa("Person") & methods(name => 'John') Note B C<|> not double, as C<||> cannot be overloaded. This will only work when there is a special comparison involved. If you write "john" | "anne" | "robert" Perl will turn this into "{onort" which is presumably not what you wanted. This is because perl ors them together as strings before Test::Deep gets a chance to do any overload tricks. =head3 any cmp_deeply( $got, any(@expecteds) ); C<@expecteds> is an array of expected structures. This can be used to compare data against multiple expected results and make sure that at least one of them matches. This is a short-circuit test so if a test passes then none of the tests after that will be attempted. You can also use overloading with C<|> similarly to all(). =head3 Isa cmp_deeply( $got, Isa($class) ); =head3 isa cmp_deeply( $got, isa($class) ); C<$class> is a class name. This uses C to check that C<$got_v> is blessed into the class C<$class>. B C does exactly as documented here, but C is slightly different. If C is called with 1 argument it falls through to C. If C called with 2 arguments, it falls through to C. This is to prevent breakage when you import C into a package that is used as a class. Without this, anyone calling Cisa($other_class)> would get the wrong answer. This is a hack to patch over the fact that C is exported by default. =head3 obj_isa cmp_deeply( $got, obj_isa($class) ); This test accepts only objects that are instances of C<$class> or a subclass. Unlike the C test, this test will never accept class names. =head3 array_each cmp_deeply( \@got, array_each($thing) ); C<$thing> is a structure to be compared against. <$got_v> must be an array reference. Each element of it will be compared to C<$thing>. This is useful when you have an array of similar things, for example objects of a known type and you don't want to have to repeat the same test for each one. my $common_tests = all( isa("MyFile"), methods( handle => isa("IO::Handle") filename => re("^/home/ted/tmp"), ) ); cmp_deeply($got, array_each($common_tests)); is similar to foreach my $got_v (@$got) { cmp_deeply($got_v, $common_tests) } Except it will not explode if C<$got> is not an array reference. It will check that each of the objects in C<@$got> is a MyFile and that each one gives the correct results for its methods. You could go further, if for example there were 3 files and you knew the size of each one you could do this cmp_deeply( $got, all( array_each($common_tests), [ methods(size => 1000), methods(size => 200), methods(size => 20) ] ) ) cmp_deeply($got, array_each($structure)); =head3 hash_each cmp_deeply( \%got, hash_each($thing) ); This test behaves like C (see above) but tests that each hash value passes its tests. =head3 str cmp_deeply( $got, str($string) ); $string is a string. This will stringify C<$got_v> and compare it to C<$string> using C, even if C<$got_v> is a ref. It is useful for checking the stringified value of an overloaded reference. =head3 num cmp_deeply( $got, num($number, $tolerance) ); C<$number> is a number. C<$tolerance> is an optional number. This will add 0 to C<$got_v> and check if it's numerically equal to C<$number>, even if C<$got_v> is a ref. It is useful for checking the numerical value of an overloaded reference. If C<$tolerance> is supplied then this will check that C<$got_v> and C<$exp_v> are less than C<$tolerance> apart. This is useful when comparing floating point numbers as rounding errors can make it hard or impossible for C<$got_v> to be exactly equal to C<$exp_v>. When C<$tolerance> is supplied, the test passes if C. B in Perl, C<"12blah" == 12> because Perl will be smart and convert "12blah" into 12. You may not want this. There was a strict mode but that is now gone. A "looks like a number" test will replace it soon. Until then you can usually just use the string() comparison to be more strict. This will work fine for almost all situations, however it will not work when <$got_v> is an overloaded value who's string and numerical values differ. =head3 bool, true, false cmp_deeply( $got, bool($value) ); cmp_deeply( $got, true ); cmp_deeply( $got, false ); C<$value> is anything you like but it's probably best to use 0 or 1 This will check that C<$got_v> and C<$value> have the same truth value, that is they will give the same result when used in boolean context, like in an C statement. B C and C are only imported by special request. =head3 code cmp_deeply( $got, code(\&subref) ); C<\&subref> is a reference to a subroutine which will be passed a single argument, it then should return a true or false and possibly a string This will pass C<$got_v> to the subroutine which returns true or false to indicate a pass or fail. Fails can be accompanied by a diagnostic string which gives an explanation of why it's a fail. sub check_name { my $name = shift; if ($boss->likes($name)) { return 1; } else { return (0, "the boss doesn't like your name"); } } cmp_deeply("Brian", code(\&check_name)); =head2 SET COMPARISONS Set comparisons give special semantics to array comparisons: =over 4 =item * The order of items in a set is irrelevant =item * The presence of duplicate items in a set is ignored. =back As such, in any set comparison, the following arrays are equal: [ 1, 2 ] [ 1, 1, 2 ] [ 1, 2, 1 ] [ 2, 1, 1 ] [ 1, 1, 2 ] All are interpreted by C semantics as if the set was only specified as: [ 1, 2 ] All C functions return an object which can have additional items added to it: my $set = set( 1, 2 ); $set->add(1, 3, 1 ); # Set is now ( 1, 2, 3 ) Special care must be taken when using special comparisons within sets. See L for details. =head3 set cmp_deeply( \@got, set(@elements) ); This does a set comparison, that is, it compares two arrays but ignores the order of the elements and it ignores duplicate elements, but ensures that all items in C<@elements> will be in C<$got> and all items in C<$got> will be in C<@elements>. So the following tests will be passes, and will be equivalent: cmp_deeply([1, 2, 2, 3], set(3, 2, 1, 1)); cmp_deeply([1, 2, 3], set(3, 2, 1)); =head3 supersetof cmp_deeply( \@got, supersetof(@elements) ); This function works much like L<< C|/set >>, and performs a set comparison of C<$got_v> with the elements of C<@elements>. C is however slightly relaxed, such that C<$got> may contain things not in C<@elements>, but must at least contain all C<@elements>. These two statements are equivalent, and will be passes: cmp_deeply([1,2,3,3,4,5], supersetof(2,2,3)); cmp_deeply([1,2,3,4,5], supersetof(2,3)); But these will be failures: cmp_deeply([1,2,3,4,5], supersetof(2,3,6)); # 6 not in superset cmp_deeply([1], supersetof(1,2)); # 2 not in superset =head3 subsetof cmp_deeply( \@got, subsetof(@elements) ); This function works much like L<< C|/set >>, and performs a set comparison of C<$got_v> with the elements of C<@elements>. This is the inverse of C, which expects all unique elements found in C<$got_v> must be in C<@elements>. cmp_deeply([1,2,4,5], subsetof(2,3,3) ) # Fail: 1,4 & 5 extra cmp_deeply([2,3,3], subsetof(1,2,4,5) ) # Fail: 3 extra cmp_deeply([2,3,3], subsetof(1,2,4,5,3)) # Pass =head3 none cmp_deeply( $got, none(@elements) ); @elements is an array of elements, wherein no elements in C<@elements> may be equal to C<$got_v>. =head3 noneof cmp_deeply( \@got, noneof(@elements) ); @elements is an array of elements, wherein no elements in C<@elements> may be found in C<$got_v>. For example: # Got has no 1, no 2, and no 3 cmp_deeply( [1], noneof( 1, 2, 3 ) ); # fail cmp_deeply( [5], noneof( 1, 2, 3 ) ); # pass =head2 BAG COMPARISONS Bag comparisons give special semantics to array comparisons, that are similar to L<< set comparisons|/SET COMPARISONS >>, but slightly different. =over 4 =item * The order of items in a bag is irrelevant =item * The presence of duplicate items in a bag is B =back As such, in any bag comparison, the following arrays are equal: [ 1, 1, 2 ] [ 1, 2, 1 ] [ 2, 1, 1 ] [ 1, 1, 2 ] However, they are B equal to any of the following: [ 1, 2 ] [ 1, 2, 2 ] [ 1, 1, 1, 2 ] All C functions return an object which can have additional items added to it: my $bag = bag( 1, 2 ); $bag->add(1, 3, 1 ); # Bag is now ( 1, 1, 1, 2, 3 ) Special care must be taken when using special comparisons within bags. See L for details. =head3 bag cmp_deeply( \@got, bag(@elements) ); This does an order-insensitive bag comparison between C<$got> and C<@elements>, ensuring that: =over 4 =item each item in C<@elements> is found in C<$got> =item the number of times a C<$expected_v> is found in C<@elements> is reflected in C<$got> =item no items are found in C<$got> other than those in C<@elements>. =back As such, the following are passes, and are equivalent to each other: cmp_deeply([1, 2, 2], bag(2, 2, 1)) cmp_deeply([2, 1, 2], bag(2, 2, 1)) cmp_deeply([2, 2, 1], bag(2, 2, 1)) But the following are failures: cmp_deeply([1, 2, 2], bag(2, 2, 1, 1)) # Not enough 1's in Got cmp_deeply([1, 2, 2, 1], bag(2, 2, 1) ) # Too many 1's in Got =head3 superbagof cmp_deeply( \@got, superbagof( @elements ) ); This function works much like L<< C|/bag >>, and performs a bag comparison of C<$got_v> with the elements of C<@elements>. C is however slightly relaxed, such that C<$got> may contain things not in C<@elements>, but must at least contain all C<@elements>. So: # pass cmp_deeply( [1, 1, 2], superbagof( 1 ) ); # fail: not enough 1's in superbag cmp_deeply( [1, 1, 2], superbagof( 1, 1, 1 )); =head3 subbagof cmp_deeply( \@got, subbagof(@elements) ); This function works much like L<< C|/bag >>, and performs a bag comparison of C<$got_v> with the elements of C<@elements>. This is the inverse of C, and expects all elements in C<$got> to be in C<@elements>, while allowing items to exist in C<@elements> that are not in C<$got> # pass cmp_deeply( [1], subbagof( 1, 1, 2 ) ); # fail: too many 1's in subbag cmp_deeply( [1, 1, 1], subbagof( 1, 1, 2 ) ); =head2 HASH COMPARISONS Typically, if you're doing simple hash comparisons, cmp_deeply( \%got, \%expected ) is sufficient. C will ensure C<%got> and C<%hash> have identical keys, and each key from either has the same corresponding value. =head3 superhashof cmp_deeply( \%got, superhashof(\%hash) ); This will check that the hash C<%$got> is a "super-hash" of C<%hash>. That is that all the key and value pairs in C<%hash> appear in C<%$got> but C<%$got> can have extra ones also. For example cmp_deeply({a => 1, b => 2}, superhashof({a => 1})) will pass but cmp_deeply({a => 1, b => 2}, superhashof({a => 1, c => 3})) will fail. =head3 subhashof cmp_deeply( \%got, subhashof(\%hash) ); This will check that the hash C<%$got> is a "sub-hash" of C<%hash>. That is that all the key and value pairs in C<%$got> also appear in C<%hash>. For example cmp_deeply({a => 1}, subhashof({a => 1, b => 2})) will pass but cmp_deeply({a => 1, c => 3}, subhashof({a => 1, b => 2})) will fail. =head1 DIAGNOSTIC FUNCTIONS =head3 deep_diag my $reason = deep_diag($stack); C<$stack> is a value returned by cmp_details. Do not call this function if cmp_details returned a true value for C<$ok>. C returns a human readable string describing how the comparison failed. =head1 ANOTHER EXAMPLE You've written a module to handle people and their film interests. Say you have a function that returns an array of people from a query, each person is a hash with 2 keys: Name and Age and the array is sorted by Name. You can do cmp_deeply( $result, [ {Name => 'Anne', Age => 26}, {Name => "Bill", Age => 47} {Name => 'John', Age => 25}, ] ); Soon after, your query function changes and all the results now have an ID field. Now your test is failing again because you left out ID from each of the hashes. The problem is that the IDs are generated by the database and you have no way of knowing what each person's ID is. With Test::Deep you can change your query to cmp_deeply( $result, [ {Name => 'John', Age => 25, ID => ignore()}, {Name => 'Anne', Age => 26, ID => ignore()}, {Name => "Bill", Age => 47, ID => ignore()} ] ); But your test still fails. Now, because you're using a database, you no longer know what order the people will appear in. You could add a sort into the database query but that could slow down your application. Instead you can get Test::Deep to ignore the order of the array by doing a bag comparison instead. cmp_deeply( $result, bag( {Name => 'John', Age => 25, ID => ignore()}, {Name => 'Anne', Age => 26, ID => ignore()}, {Name => "Bill", Age => 47, ID => ignore()} ) ); Finally person gets even more complicated and includes a new field called Movies, this is a list of movies that the person has seen recently, again these movies could also come back in any order so we need a bag inside our other bag comparison, giving us something like cmp_deeply( $result, bag( {Name => 'John', Age => 25, ID => ignore(), Movies => bag(...)}, {Name => 'Anne', Age => 26, ID => ignore(), Movies => bag(...)}, {Name => "Bill", Age => 47, ID => ignore(), Movies => bag(...)} ) ); =head1 USING TEST::DEEP WITH TEST::BUILDER Combining C and C makes it possible to use Test::Deep in your own test classes. In a L subclass, create a test method in the following form: sub behaves_ok { my $self = shift; my $expected = shift; my $test_name = shift; my $got = do_the_important_work_here(); my ($ok, $stack) = cmp_details($got, $expected); unless ($Test->ok($ok, $test_name)) { my $diag = deep_diag($stack); $Test->diag($diag); } } As the subclass defines a test class, not tests themselves, make sure it uses L, not C itself. =head1 LIMITATIONS Currently any CODE, GLOB or IO refs will be compared using shallow(), which means only their memory addresses are compared. =head1 BUGS There is a bug in set and bag compare to do with competing SCs. It only occurs when you put certain special comparisons inside bag or set comparisons you don't need to worry about it. The full details are in the C docs. It will be fixed in an upcoming version. =head1 CAVEATS =head2 SPECIAL CARE WITH SPECIAL COMPARISONS IN SETS AND BAGS If you use certain special comparisons within a bag or set comparison there is a danger that a test will fail when it should have passed. It can only happen if two or more special comparisons in the bag are competing to match elements. Consider this comparison cmp_deeply(['furry', 'furball'], bag(re("^fur"), re("furb"))) There are two things that could happen, hopefully C is paired with "furry" and C is paired with "furb" and everything is fine but it could happen that C is paired with "furball" and then C cannot find a match and so the test fails. Examples of other competing comparisons are C vs C and C<< methods(m1 => "v1", m2 => "v2") >> vs C<< methods(m1 => "v1") >> This problem is could be solved by using a slower and more complicated algorithm for set and bag matching. Something for the future... =head1 WHAT ARE SPECIAL COMPARISONS? A special comparison (SC) is simply an object that inherits from Test::Deep::Cmp. Whenever C<$expected_v> is an SC then instead of checking C<$got_v eq $expected_v>, we pass control over to the SC and let it do its thing. Test::Deep exports lots of SC constructors, to make it easy for you to use them in your test scripts. For example is C is just a handy way of creating a Test::Deep::Regexp object that will match any string containing "hello". So cmp_deeply([ 'a', 'b', 'hello world'], ['a', 'b', re("^hello")]); will check C<'a' eq 'a'>, C<'b' eq 'b'> but when it comes to comparing C<'hello world'> and C it will see that $expected_v is an SC and so will pass control to the Test::Deep::Regexp class by do something like C<< $expected_v->descend($got_v) >>. The C method should just return true or false. This gives you enough to write your own SCs but I haven't documented how diagnostics works because it's about to get an overhaul (theoretically). =head1 EXPORTS By default, Test::Deep will export everything in its C tag, as if you had written: use Test::Deep ':v0'; Those things are: all any array array_each arrayelementsonly arraylength arraylengthonly bag blessed bool cmp_bag cmp_deeply cmp_methods cmp_set code eq_deeply hash hash_each hashkeys hashkeysonly ignore Isa isa listmethods methods noclass none noneof num obj_isa re reftype regexpmatches regexponly regexpref regexprefonly scalarrefonly scalref set shallow str subbagof subhashof subsetof superbagof superhashof supersetof useclass A slightly better set of exports is the C set. It's all the same things, with the exception of C and C. If you want to import "everything", you probably want to C<< use Test::Deep ':V1'; >>. There's another magic export group: C<:preload>. If that is specified, all of the Test::Deep plugins will be loaded immediately instead of lazily. =head1 SEE ALSO L =head1 MAINTAINER Ricardo Signes =head1 AUTHOR Fergal Daly Efergal@esatclear.ieE, with thanks to Michael G Schwern for Test::More's is_deeply function which inspired this. B do not bother Fergal Daly with bug reports. Send them to the maintainer (above) or submit them at L. =head1 COPYRIGHT Copyright 2003, 2004 by Fergal Daly Efergal@esatclear.ieE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!‚Ô»"perl5/Test/Tester/CaptureRunner.pmnuÏÃ6Ç$# $Header: /home/fergal/my/cvs/Test-Tester/lib/Test/Tester/CaptureRunner.pm,v 1.3 2003/03/05 01:07:55 fergal Exp $ use strict; package Test::Tester::CaptureRunner; our $VERSION = '1.302183'; use Test::Tester::Capture; require Exporter; sub new { my $pkg = shift; my $self = bless {}, $pkg; return $self; } sub run_tests { my $self = shift; my $test = shift; capture()->reset; $self->{StartLevel} = $Test::Builder::Level; &$test(); } sub get_results { my $self = shift; my @results = capture()->details; my $start = $self->{StartLevel}; foreach my $res (@results) { next if defined $res->{depth}; my $depth = $res->{_depth} - $res->{_level} - $start - 3; # print "my $depth = $res->{_depth} - $res->{_level} - $start - 1\n"; $res->{depth} = $depth; } return @results; } sub get_premature { return capture()->premature; } sub capture { return Test::Tester::Capture->new; } __END__ =head1 NAME Test::Tester::CaptureRunner - Help testing test modules built with Test::Builder =head1 DESCRIPTION This stuff if needed to allow me to play with other ways of monitoring the test results. =head1 AUTHOR Copyright 2003 by Fergal Daly . =head1 LICENSE Under the same license as Perl itself See http://www.perl.com/perl/misc/Artistic.html =cut PK!ø¢ù>HHperl5/Test/Tester/Capture.pmnuÏÃ6Ç$use strict; package Test::Tester::Capture; our $VERSION = '1.302183'; use Test::Builder; use vars qw( @ISA ); @ISA = qw( Test::Builder ); # Make Test::Tester::Capture thread-safe for ithreads. BEGIN { use Config; *share = sub { 0 }; *lock = sub { 0 }; } my $Curr_Test = 0; share($Curr_Test); my @Test_Results = (); share(@Test_Results); my $Prem_Diag = {diag => ""}; share($Curr_Test); sub new { # Test::Tester::Capgture::new used to just return __PACKAGE__ # because Test::Builder::new enforced its singleton nature by # return __PACKAGE__. That has since changed, Test::Builder::new now # returns a blessed has and around version 0.78, Test::Builder::todo # started wanting to modify $self. To cope with this, we now return # a blessed hash. This is a short-term hack, the correct thing to do # is to detect which style of Test::Builder we're dealing with and # act appropriately. my $class = shift; return bless {}, $class; } sub ok { my($self, $test, $name) = @_; my $ctx = $self->ctx; # $test might contain an object which we don't want to accidentally # store, so we turn it into a boolean. $test = $test ? 1 : 0; lock $Curr_Test; $Curr_Test++; my($pack, $file, $line) = $self->caller; my $todo = $self->todo(); my $result = {}; share($result); unless( $test ) { @$result{ 'ok', 'actual_ok' } = ( ( $todo ? 1 : 0 ), 0 ); } else { @$result{ 'ok', 'actual_ok' } = ( 1, $test ); } if( defined $name ) { $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness. $result->{name} = $name; } else { $result->{name} = ''; } if( $todo ) { my $what_todo = $todo; $result->{reason} = $what_todo; $result->{type} = 'todo'; } else { $result->{reason} = ''; $result->{type} = ''; } $Test_Results[$Curr_Test-1] = $result; unless( $test ) { my $msg = $todo ? "Failed (TODO)" : "Failed"; $result->{fail_diag} = (" $msg test ($file at line $line)\n"); } $result->{diag} = ""; $result->{_level} = $Test::Builder::Level; $result->{_depth} = Test::Tester::find_run_tests(); $ctx->release; return $test ? 1 : 0; } sub skip { my($self, $why) = @_; $why ||= ''; my $ctx = $self->ctx; lock($Curr_Test); $Curr_Test++; my %result; share(%result); %result = ( 'ok' => 1, actual_ok => 1, name => '', type => 'skip', reason => $why, diag => "", _level => $Test::Builder::Level, _depth => Test::Tester::find_run_tests(), ); $Test_Results[$Curr_Test-1] = \%result; $ctx->release; return 1; } sub todo_skip { my($self, $why) = @_; $why ||= ''; my $ctx = $self->ctx; lock($Curr_Test); $Curr_Test++; my %result; share(%result); %result = ( 'ok' => 1, actual_ok => 0, name => '', type => 'todo_skip', reason => $why, diag => "", _level => $Test::Builder::Level, _depth => Test::Tester::find_run_tests(), ); $Test_Results[$Curr_Test-1] = \%result; $ctx->release; return 1; } sub diag { my($self, @msgs) = @_; return unless @msgs; # Prevent printing headers when compiling (i.e. -c) return if $^C; my $ctx = $self->ctx; # Escape each line with a #. foreach (@msgs) { $_ = 'undef' unless defined; } push @msgs, "\n" unless $msgs[-1] =~ /\n\Z/; my $result = $Curr_Test ? $Test_Results[$Curr_Test - 1] : $Prem_Diag; $result->{diag} .= join("", @msgs); $ctx->release; return 0; } sub details { return @Test_Results; } # Stub. Feel free to send me a patch to implement this. sub note { } sub explain { return Test::Builder::explain(@_); } sub premature { return $Prem_Diag->{diag}; } sub current_test { if (@_ > 1) { die "Don't try to change the test number!"; } else { return $Curr_Test; } } sub reset { $Curr_Test = 0; @Test_Results = (); $Prem_Diag = {diag => ""}; } 1; __END__ =head1 NAME Test::Tester::Capture - Help testing test modules built with Test::Builder =head1 DESCRIPTION This is a subclass of Test::Builder that overrides many of the methods so that they don't output anything. It also keeps track of its own set of test results so that you can use Test::Builder based modules to perform tests on other Test::Builder based modules. =head1 AUTHOR Most of the code here was lifted straight from Test::Builder and then had chunks removed by Fergal Daly . =head1 LICENSE Under the same license as Perl itself See http://www.perl.com/perl/misc/Artistic.html =cut PK!ÆæuY;;perl5/Test/Tester/Delegate.pmnuÏÃ6Ç$use strict; use warnings; package Test::Tester::Delegate; our $VERSION = '1.302183'; use Scalar::Util(); use vars '$AUTOLOAD'; sub new { my $pkg = shift; my $obj = shift; my $self = bless {}, $pkg; return $self; } sub AUTOLOAD { my ($sub) = $AUTOLOAD =~ /.*::(.*?)$/; return if $sub eq "DESTROY"; my $obj = $_[0]->{Object}; my $ref = $obj->can($sub); shift(@_); unshift(@_, $obj); goto &$ref; } sub can { my $this = shift; my ($sub) = @_; return $this->{Object}->can($sub) if Scalar::Util::blessed($this); return $this->SUPER::can(@_); } 1; PK!ÀšÔ\\perl5/Test/Simple.pmnuÏÃ6Ç$package Test::Simple; use 5.006; use strict; our $VERSION = '1.302183'; use Test::Builder::Module; our @ISA = qw(Test::Builder::Module); our @EXPORT = qw(ok); my $CLASS = __PACKAGE__; =head1 NAME Test::Simple - Basic utilities for writing tests. =head1 SYNOPSIS use Test::Simple tests => 1; ok( $foo eq $bar, 'foo is bar' ); =head1 DESCRIPTION ** If you are unfamiliar with testing B first!> ** This is an extremely simple, extremely basic module for writing tests suitable for CPAN modules and other pursuits. If you wish to do more complicated testing, use the Test::More module (a drop-in replacement for this one). The basic unit of Perl testing is the ok. For each thing you want to test your program will print out an "ok" or "not ok" to indicate pass or fail. You do this with the C function (see below). The only other constraint is you must pre-declare how many tests you plan to run. This is in case something goes horribly wrong during the test and your test program aborts, or skips a test or whatever. You do this like so: use Test::Simple tests => 23; You must have a plan. =over 4 =item B ok( $foo eq $bar, $name ); ok( $foo eq $bar ); C is given an expression (in this case C<$foo eq $bar>). If it's true, the test passed. If it's false, it didn't. That's about it. C prints out either "ok" or "not ok" along with a test number (it keeps track of that for you). # This produces "ok 1 - Hell not yet frozen over" (or not ok) ok( get_temperature($hell) > 0, 'Hell not yet frozen over' ); If you provide a $name, that will be printed along with the "ok/not ok" to make it easier to find your test when if fails (just search for the name). It also makes it easier for the next guy to understand what your test is for. It's highly recommended you use test names. All tests are run in scalar context. So this: ok( @stuff, 'I have some stuff' ); will do what you mean (fail if stuff is empty) =cut sub ok ($;$) { ## no critic (Subroutines::ProhibitSubroutinePrototypes) return $CLASS->builder->ok(@_); } =back Test::Simple will start by printing number of tests run in the form "1..M" (so "1..5" means you're going to run 5 tests). This strange format lets L know how many tests you plan on running in case something goes horribly wrong. If all your tests passed, Test::Simple will exit with zero (which is normal). If anything failed it will exit with how many failed. If you run less (or more) tests than you planned, the missing (or extras) will be considered failures. If no tests were ever run Test::Simple will throw a warning and exit with 255. If the test died, even after having successfully completed all its tests, it will still be considered a failure and will exit with 255. So the exit codes are... 0 all tests successful 255 test died or all passed but wrong # of tests run any other number how many failed (including missing or extras) If you fail more than 254 tests, it will be reported as 254. This module is by no means trying to be a complete testing system. It's just to get you started. Once you're off the ground its recommended you look at L. =head1 EXAMPLE Here's an example of a simple .t file for the fictional Film module. use Test::Simple tests => 5; use Film; # What you're testing. my $btaste = Film->new({ Title => 'Bad Taste', Director => 'Peter Jackson', Rating => 'R', NumExplodingSheep => 1 }); ok( defined($btaste) && ref $btaste eq 'Film', 'new() works' ); ok( $btaste->Title eq 'Bad Taste', 'Title() get' ); ok( $btaste->Director eq 'Peter Jackson', 'Director() get' ); ok( $btaste->Rating eq 'R', 'Rating() get' ); ok( $btaste->NumExplodingSheep == 1, 'NumExplodingSheep() get' ); It will produce output like this: 1..5 ok 1 - new() works ok 2 - Title() get ok 3 - Director() get not ok 4 - Rating() get # Failed test 'Rating() get' # in t/film.t at line 14. ok 5 - NumExplodingSheep() get # Looks like you failed 1 tests of 5 Indicating the Film::Rating() method is broken. =head1 CAVEATS Test::Simple will only report a maximum of 254 failures in its exit code. If this is a problem, you probably have a huge test script. Split it into multiple files. (Otherwise blame the Unix folks for using an unsigned short integer as the exit status). Because VMS's exit codes are much, much different than the rest of the universe, and perl does horrible mangling to them that gets in my way, it works like this on VMS. 0 SS$_NORMAL all tests successful 4 SS$_ABORT something went wrong Unfortunately, I can't differentiate any further. =head1 NOTES Test::Simple is B tested all the way back to perl 5.6.0. Test::Simple is thread-safe in perl 5.8.1 and up. =head1 HISTORY This module was conceived while talking with Tony Bowden in his kitchen one night about the problems I was having writing some really complicated feature into the new Testing module. He observed that the main problem is not dealing with these edge cases but that people hate to write tests B. What was needed was a dead simple module that took all the hard work out of testing and was really, really easy to learn. Paul Johnson simultaneously had this idea (unfortunately, he wasn't in Tony's kitchen). This is it. =head1 SEE ALSO =over 4 =item L More testing functions! Once you outgrow Test::Simple, look at L. Test::Simple is 100% forward compatible with L (i.e. you can just use L instead of Test::Simple in your programs and things will still work). =back Look in L's SEE ALSO for more testing modules. =head1 AUTHORS Idea by Tony Bowden and Paul Johnson, code by Michael G Schwern Eschwern@pobox.comE, wardrobe by Calvin Klein. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2001-2008 by Michael G Schwern Eschwern@pobox.comE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut 1; PK!O�£�¾)¾)perl5/Test/utf8.pmnuÏÃ6Ç$package Test::utf8; use 5.007003; use strict; use warnings; use base qw(Exporter); use Encode; use charnames ':full'; our $VERSION = "1.02"; our @EXPORT = qw( is_valid_string is_dodgy_utf8 is_sane_utf8 is_within_ascii is_within_latin1 is_within_latin_1 is_flagged_utf8 isnt_flagged_utf8 ); # A Regexp string to match valid UTF8 bytes # this info comes from page 78 of "The Unicode Standard 4.0" # published by the Unicode Consortium our $valid_utf8_regexp = <<'REGEX' ; [\x{00}-\x{7f}] | [\x{c2}-\x{df}][\x{80}-\x{bf}] | \x{e0} [\x{a0}-\x{bf}][\x{80}-\x{bf}] | [\x{e1}-\x{ec}][\x{80}-\x{bf}][\x{80}-\x{bf}] | \x{ed} [\x{80}-\x{9f}][\x{80}-\x{bf}] | [\x{ee}-\x{ef}][\x{80}-\x{bf}][\x{80}-\x{bf}] | \x{f0} [\x{90}-\x{bf}][\x{80}-\x{bf}] | [\x{f1}-\x{f3}][\x{80}-\x{bf}][\x{80}-\x{bf}][\x{80}-\x{bf}] | \x{f4} [\x{80}-\x{8f}][\x{80}-\x{bf}][\x{80}-\x{bf}] REGEX =head1 NAME Test::utf8 - handy utf8 tests =head1 SYNOPSIS # check the string is good is_valid_string($string); # check the string is valid is_sane_utf8($string); # check not double encoded # check the string has certain attributes is_flagged_utf8($string1); # has utf8 flag set is_within_ascii($string2); # only has ascii chars in it isnt_within_ascii($string3); # has chars outside the ascii range is_within_latin_1($string4); # only has latin-1 chars in it isnt_within_ascii($string5); # has chars outside the latin-1 range =head1 DESCRIPTION This module is a collection of tests useful for dealing with utf8 strings in Perl. This module has two types of tests: The validity tests check if a string is valid and not corrupt, whereas the characteristics tests will check that string has a given set of characteristics. =head2 Validity Tests =over =item is_valid_string($string, $testname) Checks if the string is "valid", i.e. this passes and returns true unless the internal utf8 flag hasn't been set on scalar that isn't made up of a valid utf-8 byte sequence. This should I happen and, in theory, this test should always pass. Unless you (or a module you use) goes monkeying around inside a scalar using Encode's private functions or XS code you shouldn't ever end up in a situation where you've got a corrupt scalar. But if you do, and you do, then this function should help you detect the problem. To be clear, here's an example of the error case this can detect: my $mark = "Mark"; my $leon = "L\x{e9}on"; is_valid_string($mark); # passes, not utf-8 is_valid_string($leon); # passes, not utf-8 my $iloveny = "I \x{2665} NY"; is_valid_string($iloveny); # passes, proper utf-8 my $acme = "L\x{c3}\x{a9}on"; Encode::_utf8_on($acme); # (please don't do things like this) is_valid_string($acme); # passes, proper utf-8 byte sequence upgraded Encode::_utf8_on($leon); # (this is why you don't do things like this) is_valid_string($leon); # fails! the byte \x{e9} isn't valid utf-8 =cut sub is_valid_string($;$) { my $string = shift; my $name = shift || "valid string test"; # check we're a utf8 string - if not, we pass. unless (Encode::is_utf8($string)) { return _pass($name) } # work out at what byte (if any) we have an invalid byte sequence # and return the correct test result my $pos = _invalid_sequence_at_byte($string); if (_ok(!defined($pos), $name)) { return 1 } _diag("malformed byte sequence starting at byte $pos"); return; } sub _invalid_sequence_at_byte($) { my $string = shift; # examine the bytes that make up the string (not the chars) # by turning off the utf8 flag (no, use bytes doesn't # work, we're dealing with a regexp) Encode::_utf8_off($string); ## no critic (ProtectPrivateSubs) # work out the index of the first non matching byte my $result = $string =~ m/^($valid_utf8_regexp)*/ogx; # if we matched all the string return the empty list my $pos = pos $string || 0; return if $pos == length($string); # otherwise return the position we found return $pos } =item is_sane_utf8($string, $name) This test fails if the string contains something that looks like it might be dodgy utf8, i.e. containing something that looks like the multi-byte sequence for a latin-1 character but perl hasn't been instructed to treat as such. Strings that are not utf8 always automatically pass. Some examples may help: # This will pass as it's a normal latin-1 string is_sane_utf8("Hello L\x{e9}eon"); # this will fail because the \x{c3}\x{a9} looks like the # utf8 byte sequence for e-acute my $string = "Hello L\x{c3}\x{a9}on"; is_sane_utf8($string); # this will pass because the utf8 is correctly interpreted as utf8 Encode::_utf8_on($string) is_sane_utf8($string); Obviously this isn't a hundred percent reliable. The edge case where this will fail is where you have C<\x{c2}> (which is "LATIN CAPITAL LETTER WITH CIRCUMFLEX") or C<\x{c3}> (which is "LATIN CAPITAL LETTER WITH TILDE") followed by one of the latin-1 punctuation symbols. # a capital letter A with tilde surrounded by smart quotes # this will fail because it'll see the "\x{c2}\x{94}" and think # it's actually the utf8 sequence for the end smart quote is_sane_utf8("\x{93}\x{c2}\x{94}"); However, since this hardly comes up this test is reasonably reliable in most cases. Still, care should be applied in cases where dynamic data is placed next to latin-1 punctuation to avoid false negatives. There exists two situations to cause this test to fail; The string contains utf8 byte sequences and the string hasn't been flagged as utf8 (this normally means that you got it from an external source like a C library; When Perl needs to store a string internally as utf8 it does it's own encoding and flagging transparently) or a utf8 flagged string contains byte sequences that when translated to characters themselves look like a utf8 byte sequence. The test diagnostics tells you which is the case. =cut # build my regular expression out of the latin-1 bytes # NOTE: This won't work if our locale is nonstandard will it? my $re_bit = join "|", map { Encode::encode("utf8",chr($_)) } (127..255); sub is_sane_utf8($;$) { my $string = shift; my $name = shift || "sane utf8"; # regexp in scalar context with 'g', meaning this loop will run for # each match. Should only have to run it once, but will redo if # the failing case turns out to be allowed in %allowed. while ($string =~ /($re_bit)/o) { # work out what the double encoded string was my $bytes = $1; my $index = $+[0] - length($bytes); my $codes = join '', map { sprintf '<%00x>', ord($_) } split //, $bytes; # what character does that represent? my $char = Encode::decode("utf8",$bytes); my $ord = ord($char); my $hex = sprintf '%00x', $ord; $char = charnames::viacode($ord); # print out diagnostic messages _fail($name); _diag(qq{Found dodgy chars "$codes" at char $index\n}); if (Encode::is_utf8($string)) { _diag("Chars in utf8 string look like utf8 byte sequence.") } else { _diag("String not flagged as utf8...was it meant to be?\n") } _diag("Probably originally a $char char - codepoint $ord (dec)," ." $hex (hex)\n"); return 0; } # got this far, must have passed. _ok(1,$name); return 1; } # historic name of method; deprecated sub is_dodgy_utf8 { goto &is_sane_utf8 } =back =head2 String Characteristic Tests These routines allow you to check the range of characters in a string. Note that these routines are blind to the actual encoding perl internally uses to store the characters, they just check if the string contains only characters that can be represented in the named encoding: =over =item is_within_ascii Tests that a string only contains characters that are in the ASCII character set. =cut sub is_within_ascii($;$) { my $string = shift; my $name = shift || "within ascii"; # look for anything that isn't ascii or pass $string =~ /([^\x{00}-\x{7f}])/ or return _pass($name); # explain why we failed my $dec = ord($1); my $hex = sprintf '%02x', $dec; _fail($name); _diag("Char $+[0] not ASCII (it's $dec dec / $hex hex)"); return 0; } =item is_within_latin_1 Tests that a string only contains characters that are in latin-1. =cut sub is_within_latin_1($;$) { my $string = shift; my $name = shift || "within latin-1"; # look for anything that isn't ascii or pass $string =~ /([^\x{00}-\x{ff}])/ or return _pass($name); # explain why we failed my $dec = ord($1); my $hex = sprintf '%x', $dec; _fail($name); _diag("Char $+[0] not Latin-1 (it's $dec dec / $hex hex)"); return 0; } sub is_within_latin1 { goto &is_within_latin_1 } =back Simply check if a scalar is or isn't flagged as utf8 by perl's internals: =over =item is_flagged_utf8($string, $name) Passes if the string is flagged by perl's internals as utf8, fails if it's not. =cut sub is_flagged_utf8 { my $string = shift; my $name = shift || "flagged as utf8"; return _ok(Encode::is_utf8($string),$name); } =item isnt_flagged_utf8($string,$name) The opposite of C, passes if and only if the string isn't flagged as utf8 by perl's internals. Note: you can refer to this function as C if you really want to. =cut sub isnt_flagged_utf8($;$) { my $string = shift; my $name = shift || "not flagged as utf8"; return _ok(!Encode::is_utf8($string), $name); } sub isn::t_flagged_utf8($;$) { my $string = shift; my $name = shift || "not flagged as utf8"; return _ok(!Encode::is_utf8($string), $name); } =back =head1 AUTHOR Written by Mark Fowler B =head1 COPYRIGHT Copyright Mark Fowler 2004,2012. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 BUGS None known. Please report any to me via the CPAN RT system. See http://rt.cpan.org/ for more details. =head1 SEE ALSO L for testing for double encoded HTML entities. =cut ########## # shortcuts for Test::Builder. use Test::Builder; my $tester = Test::Builder->new(); sub _ok { local $Test::Builder::Level = $Test::Builder::Level + 1; return $tester->ok(@_) } sub _diag { local $Test::Builder::Level = $Test::Builder::Level + 1; $tester->diag(@_); return; } sub _fail { local $Test::Builder::Level = $Test::Builder::Level + 1; return _ok(0,@_) } sub _pass { local $Test::Builder::Level = $Test::Builder::Level + 1; return _ok(1,@_) } 1; PK!(죸ќќperl5/Test/File.pmnuÏÃ6Ç$package Test::File; use strict; use base qw(Exporter); use vars qw(@EXPORT $VERSION); use File::Spec; use Test::Builder; @EXPORT = qw( file_exists_ok file_not_exists_ok file_empty_ok file_not_empty_ok file_size_ok file_max_size_ok file_min_size_ok file_readable_ok file_not_readable_ok file_writeable_ok file_not_writeable_ok file_executable_ok file_not_executable_ok file_mode_is file_mode_isnt file_mode_has file_mode_hasnt file_is_symlink_ok symlink_target_exists_ok symlink_target_is symlink_target_dangles_ok dir_exists_ok dir_contains_ok link_count_is_ok link_count_gt_ok link_count_lt_ok owner_is owner_isnt group_is group_isnt file_line_count_is file_line_count_isnt file_line_count_between file_contains_like file_contains_unlike file_contains_utf8_like file_contains_utf8_unlike file_contains_encoded_like file_contains_encoded_unlike file_mtime_gt_ok file_mtime_lt_ok file_mtime_age_ok ); $VERSION = '1.443'; { use warnings; } my $Test = Test::Builder->new(); =encoding utf8 =head1 NAME Test::File -- test file attributes =head1 SYNOPSIS use Test::File; =head1 DESCRIPTION This modules provides a collection of test utilities for file attributes. Some file attributes depend on the owner of the process testing the file in the same way the file test operators do. For instance, root (or super-user or Administrator) may always be able to read files no matter the permissions. Some attributes don't make sense outside of Unix, either, so some tests automatically skip if they think they won't work on the platform. If you have a way to make these functions work on Windows, for instance, please send me a patch. :) IF you want to pretend to be Windows on a non-Windows machine (for instance, to test C), you can set the C environment variable. The optional NAME parameter for every function allows you to specify a name for the test. If not supplied, a reasonable default will be generated. =head2 Functions =cut sub _normalize { my $file = shift; return unless defined $file; return $file =~ m|/| ? File::Spec->catfile( split m|/|, $file ) : $file; } sub _win32 { return 0 if $^O eq 'darwin'; return $ENV{PRETEND_TO_BE_WIN32} if defined $ENV{PRETEND_TO_BE_WIN32}; return $^O =~ m/Win/; } # returns true if symlinks can't exist sub _no_symlinks_here { ! eval { symlink("",""); 1 } } # owner_is and owner_isn't should skip on OS where the question makes no # sense. I really don't know a good way to test for that, so I'm going # to skip on the two OS's that I KNOW aren't multi-user. I'd love to add # more if anyone knows of any # Note: I don't have a dos or mac os < 10 machine to test this on sub _obviously_non_multi_user { foreach my $os ( qw(dos MacOS) ) { return 1 if $^O eq $os } return 0 if $^O eq 'MSWin32'; eval { my $holder = getpwuid(0) }; return 1 if $@; eval { my $holder = getgrgid(0) }; return 1 if $@; return 0; } =over 4 =item file_exists_ok( FILENAME [, NAME ] ) Ok if the file exists, and not ok otherwise. =cut sub file_exists_ok { my $filename = _normalize( shift ); my $name = shift || "$filename exists"; my $ok = -e $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag("File [$filename] does not exist"); $Test->ok(0, $name); } } =item file_not_exists_ok( FILENAME [, NAME ] ) Ok if the file does not exist, and not okay if it does exist. =cut sub file_not_exists_ok { my $filename = _normalize( shift ); my $name = shift || "$filename does not exist"; my $ok = not -e $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag("File [$filename] exists"); $Test->ok(0, $name); } } =item file_empty_ok( FILENAME [, NAME ] ) Ok if the file exists and has empty size, not ok if the file does not exist or exists with non-zero size. =cut sub file_empty_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is empty"; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } my $ok = -z $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] exists with non-zero size!" ); $Test->ok(0, $name); } } =item file_not_empty_ok( FILENAME [, NAME ] ) Ok if the file exists and has non-zero size, not ok if the file does not exist or exists with zero size. =cut sub file_not_empty_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is not empty"; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } my $ok = not -z _; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] exists with zero size!" ); $Test->ok(0, $name); } } =item file_size_ok( FILENAME, SIZE [, NAME ] ) Ok if the file exists and has SIZE size in bytes (exactly), not ok if the file does not exist or exists with size other than SIZE. =cut sub file_size_ok { my $filename = _normalize( shift ); my $expected = int shift; my $name = shift || "$filename has right size"; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } my $ok = ( -s $filename ) == $expected; if( $ok ) { $Test->ok(1, $name); } else { my $actual = -s $filename; $Test->diag( "File [$filename] has actual size [$actual] not [$expected]!" ); $Test->ok(0, $name); } } =item file_max_size_ok( FILENAME, MAX [, NAME ] ) Ok if the file exists and has size less than or equal to MAX bytes, not ok if the file does not exist or exists with size greater than MAX bytes. =cut sub file_max_size_ok { my $filename = _normalize( shift ); my $max = int shift; my $name = shift || "$filename is under $max bytes"; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } my $ok = ( -s $filename ) <= $max; if( $ok ) { $Test->ok(1, $name); } else { my $actual = -s $filename; $Test->diag( "File [$filename] has actual size [$actual] " . "greater than [$max]!" ); $Test->ok(0, $name); } } =item file_min_size_ok( FILENAME, MIN [, NAME ] ) Ok if the file exists and has size greater than or equal to MIN bytes, not ok if the file does not exist or exists with size less than MIN bytes. =cut sub file_min_size_ok { my $filename = _normalize( shift ); my $min = int shift; my $name = shift || "$filename is over $min bytes"; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } my $ok = ( -s $filename ) >= $min; if( $ok ) { $Test->ok(1, $name); } else { my $actual = -s $filename; $Test->diag( "File [$filename] has actual size ". "[$actual] less than [$min]!" ); $Test->ok(0, $name); } } =item file_line_count_is( FILENAME, COUNT [, NAME ] ) Ok if the file exists and has COUNT lines (exactly), not ok if the file does not exist or exists with a line count other than COUNT. This function uses the current value of C<$/> as the line ending and counts the lines by reading them and counting how many it read. =cut sub _ENOFILE () { -1 } sub _ECANTOPEN () { -2 } sub _file_line_counter { my $filename = shift; return _ENOFILE unless -e $filename; # does not exist return _ECANTOPEN unless open my( $fh ), "<", $filename; my $count = 0; while( <$fh> ) { $count++ } return $count; } # XXX: lots of cut and pasting here, needs refactoring # looks like the refactoring might be worse than this though sub file_line_count_is { my $filename = _normalize( shift ); my $expected = shift; my $name = do { no warnings 'uninitialized'; shift || "$filename line count is $expected lines"; }; unless( defined $expected && int( $expected ) == $expected ) { no warnings 'uninitialized'; $Test->diag( "file_line_count_is expects a positive whole number for " . "the second argument. Got [$expected]!" ); return $Test->ok( 0, $name ); } my $got = _file_line_counter( $filename ); if( $got eq _ENOFILE ) { $Test->diag( "File [$filename] does not exist!" ); $Test->ok( 0, $name ); } elsif( $got == _ECANTOPEN ) { $Test->diag( "Could not open [$filename]: \$! is [$!]!" ); $Test->ok( 0, $name ); } elsif( $got == $expected ) { $Test->ok( 1, $name ); } else { $Test->diag( "Expected [$expected] lines in [$filename], " . "got [$got] lines!" ); $Test->ok( 0, $name ); } } =item file_line_count_isnt( FILENAME, COUNT [, NAME ] ) Ok if the file exists and doesn't have exactly COUNT lines, not ok if the file does not exist or exists with a line count of COUNT. Read that carefully: the file must exist for this test to pass! This function uses the current value of C<$/> as the line ending and counts the lines by reading them and counting how many it read. =cut sub file_line_count_isnt { my $filename = _normalize( shift ); my $expected = shift; my $name = do { no warnings 'uninitialized'; shift || "$filename line count is not $expected lines"; }; unless( defined $expected && int( $expected ) == $expected ) { no warnings 'uninitialized'; $Test->diag( "file_line_count_is expects a positive whole number for " . "the second argument. Got [$expected]!" ); return $Test->ok( 0, $name ); } my $got = _file_line_counter( $filename ); if( $got eq _ENOFILE ) { $Test->diag( "File [$filename] does not exist!" ); $Test->ok( 0, $name ); } elsif( $got == _ECANTOPEN ) { $Test->diag( "Could not open [$filename]: \$! is [$!]!" ); $Test->ok( 0, $name ); } elsif( $got != $expected ) { $Test->ok( 1, $name ); } else { $Test->diag( "Expected something other than [$expected] lines in [$filename], " . "but got [$got] lines!" ); $Test->ok( 0, $name ); } } =item file_line_count_between( FILENAME, MIN, MAX, [, NAME ] ) Ok if the file exists and has a line count between MIN and MAX, inclusively. This function uses the current value of C<$/> as the line ending and counts the lines by reading them and counting how many it read. =cut sub file_line_count_between { my $filename = _normalize( shift ); my $min = shift; my $max = shift; my $name = do { no warnings 'uninitialized'; shift || "$filename line count is between [$min] and [$max] lines"; }; foreach my $ref ( \$min, \$max ) { unless( defined $$ref && int( $$ref ) == $$ref ) { no warnings 'uninitialized'; $Test->diag( "file_line_count_between expects positive whole numbers for " . "the second and third arguments. Got [$min] and [$max]!" ); return $Test->ok( 0, $name ); } } my $got = _file_line_counter( $filename ); if( $got eq _ENOFILE ) { $Test->diag( "File [$filename] does not exist!" ); $Test->ok( 0, $name ); } elsif( $got == _ECANTOPEN ) { $Test->diag( "Could not open [$filename]: \$! is [$!]!" ); $Test->ok( 0, $name ); } elsif( $min <= $got and $got <= $max ) { $Test->ok( 1, $name ); } else { $Test->diag( "Expected a line count between [$min] and [$max] " . "in [$filename], but got [$got] lines!" ); $Test->ok( 0, $name ); } } =item file_contains_like ( FILENAME, PATTERN [, NAME ] ) Ok if the file exists and its contents (as one big string) match PATTERN, not ok if the file does not exist, is not readable, or exists but doesn't match PATTERN. Since the file contents are read into memory, you should not use this for large files. Besides memory consumption, test diagnostics for failing tests might be difficult to decipher. However, for short files this works very well. Because the entire contents are treated as one large string, you can make a pattern that tests multiple lines. Don't forget that you may need to use the /s modifier for such patterns: # make sure file has one or more paragraphs with CSS class X file_contains_like($html_file, qr{

.*?

}s); Contrariwise, if you need to match at the beginning or end of a line inside the file, use the /m modifier: # make sure file has a setting for foo file_contains_like($config_file, qr/^ foo \s* = \s* \w+ $/mx); If you want to test your file contents against multiple patterns, but don't want to have the file read in repeatedly, you can pass an arrayref of patterns instead of a single pattern, like so: # make sure our template has rendered correctly file_contains_like($template_out, [ qr/^ $title_line $/mx, map { qr/^ $_ $/mx } @chapter_headings, qr/^ $footer_line $/mx, ]); Please note that if you do this, and your file does not exist or is not readable, you'll only get one test failure instead of a failure for each pattern. This could cause your test plan to be off, although you may not care at that point because your test failed anyway. If you do care, either skip the test plan altogether by employing L's C function, or use L in conjunction with a C block. Contributed by Buddy Burden C<< >>. =item file_contains_unlike ( FILENAME, PATTERN [, NAME ] ) Ok if the file exists and its contents (as one big string) do B match PATTERN, not ok if the file does not exist, is not readable, or exists but matches PATTERN. All notes and caveats for L apply to this function as well. Contributed by Buddy Burden C<< >>. =item file_contains_utf8_like ( FILENAME, PATTERN [, NAME ] ) The same as C, except the file is opened as UTF-8. =item file_contains_utf8_unlike ( FILENAME, PATTERN [, NAME ] ) The same as C, except the file is opened as UTF-8. =item file_contains_encoded_like ( FILENAME, ENCODING, PATTERN [, NAME ] ) The same as C, except the file is opened with ENCODING =item file_contains_encoded_unlike ( FILENAME, ENCODING, PATTERN [, NAME ] ) The same as C, except the file is opened with ENCODING. =cut sub file_contains_like { local $Test::Builder::Level = $Test::Builder::Level + 1; _file_contains(like => "contains", undef, @_); } sub file_contains_unlike { local $Test::Builder::Level = $Test::Builder::Level + 1; _file_contains(unlike => "doesn't contain", undef, @_); } sub file_contains_utf8_like { local $Test::Builder::Level = $Test::Builder::Level + 1; _file_contains(like => "contains", 'UTF-8', @_); } sub file_contains_utf8_unlike { local $Test::Builder::Level = $Test::Builder::Level + 1; _file_contains(unlike => "doesn't contain", 'UTF-8', @_); } sub file_contains_encoded_like { local $Test::Builder::Level = $Test::Builder::Level + 1; my $filename = shift; my $encoding = shift; _file_contains(like => "contains", $encoding, $filename, @_); } sub file_contains_encoded_unlike { local $Test::Builder::Level = $Test::Builder::Level + 1; my $filename = shift; my $encoding = shift; _file_contains(unlike => "doesn't contain", $encoding, $filename, @_); } sub _file_contains { my $method = shift; my $verb = shift; my $encoding = shift; my $filename = _normalize( shift ); my $patterns = shift; my $name = shift; my (@patterns, %patterns); if (ref $patterns eq 'ARRAY') { @patterns = @$patterns; %patterns = map { $_ => $name || "$filename $verb $_" } @patterns; } else { @patterns = ($patterns); %patterns = ( $patterns => $name || "$filename $verb $patterns" ); } # for purpose of checking the file's existence, just use the first # test name as the name $name = $patterns{$patterns[0]}; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } unless( -r $filename ) { $Test->diag( "File [$filename] is not readable!" ); return $Test->ok(0, $name); } # do the slurp my $file_contents; { unless (open(FH, $filename)) { $Test->diag( "Could not open [$filename]: \$! is [$!]!" ); return $Test->ok( 0, $name ); } if (defined $encoding) { binmode FH, ":encoding($encoding)"; } local $/ = undef; $file_contents = ; close FH; } foreach my $p (@patterns) { $Test->$method($file_contents, $p, $patterns{$p}); } } =item file_readable_ok( FILENAME [, NAME ] ) Ok if the file exists and is readable, not ok if the file does not exist or is not readable. =cut sub file_readable_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is readable"; my $ok = -r $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] is not readable!" ); $Test->ok(0, $name); } } =item file_not_readable_ok( FILENAME [, NAME ] ) Ok if the file exists and is not readable, not ok if the file does not exist or is readable. =cut sub file_not_readable_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is not readable"; my $ok = not -r $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] is readable!" ); $Test->ok(0, $name); } } =item file_writeable_ok( FILENAME [, NAME ] ) Ok if the file exists and is writeable, not ok if the file does not exist or is not writeable. =cut sub file_writeable_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is writeable"; my $ok = -w $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] is not writeable!" ); $Test->ok(0, $name); } } =item file_not_writeable_ok( FILENAME [, NAME ] ) Ok if the file exists and is not writeable, not ok if the file does not exist or is writeable. =cut sub file_not_writeable_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is not writeable"; my $ok = not -w $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag("File [$filename] is writeable!"); $Test->ok(0, $name); } } =item file_executable_ok( FILENAME [, NAME ] ) Ok if the file exists and is executable, not ok if the file does not exist or is not executable. This test automatically skips if it thinks it is on a Windows platform. =cut sub file_executable_ok { if( _win32() ) { $Test->skip( "file_executable_ok doesn't work on Windows!" ); return; } my $filename = _normalize( shift ); my $name = shift || "$filename is executable"; my $ok = -x $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag("File [$filename] is not executable!"); $Test->ok(0, $name); } } =item file_not_executable_ok( FILENAME [, NAME ] ) Ok if the file exists and is not executable, not ok if the file does not exist or is executable. This test automatically skips if it thinks it is on a Windows platform. =cut sub file_not_executable_ok { if( _win32() ) { $Test->skip( "file_not_executable_ok doesn't work on Windows!" ); return; } my $filename = _normalize( shift ); my $name = shift || "$filename is not executable"; my $ok = not -x $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag("File [$filename] is executable!"); $Test->ok(0, $name); } } =item file_mode_is( FILENAME, MODE [, NAME ] ) Ok if the file exists and the mode matches, not ok if the file does not exist or the mode does not match. This test automatically skips if it thinks it is on a Windows platform. Contributed by Shawn Sorichetti C<< >> =cut sub file_mode_is { if( _win32() ) { $Test->skip( "file_mode_is doesn't work on Windows!" ); return; } my $filename = _normalize( shift ); my $mode = shift; my $name = shift || sprintf("%s mode is %04o", $filename, $mode); my $ok = -e $filename && ((stat($filename))[2] & 07777) == $mode; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag(sprintf("File [%s] mode is not %04o!", $filename, $mode) ); $Test->ok(0, $name); } } =item file_mode_isnt( FILENAME, MODE [, NAME ] ) Ok if the file exists and mode does not match, not ok if the file does not exist or mode does match. This test automatically skips if it thinks it is on a Windows platform. Contributed by Shawn Sorichetti C<< >> =cut sub file_mode_isnt { if( _win32() ) { $Test->skip( "file_mode_isnt doesn't work on Windows!" ); return; } my $filename = _normalize( shift ); my $mode = shift; my $name = shift || sprintf("%s mode is not %04o",$filename,$mode); my $ok = not (-e $filename && ((stat($filename))[2] & 07777) == $mode); if( $ok ) { $Test->ok(1, $name); } else { $Test->diag(sprintf("File [%s] mode is %04o!",$filename,$mode)); $Test->ok(0, $name); } } =item file_mode_has( FILENAME, MODE [, NAME ] ) Ok if the file exists and has all the bits in mode turned on, not ok if the file does not exist or the mode does not match. That is, C<< FILEMODE & MODE == MODE >> must be true. This test automatically skips if it thinks it is on a Windows platform. Contributed by Ricardo Signes C<< >> =cut sub file_mode_has { if( _win32() ) { $Test->skip( "file_mode_has doesn't work on Windows!" ); return; } my $filename = _normalize( shift ); my $mode = shift; my $name = shift || sprintf("%s mode has all bits of %04o", $filename, $mode); my $present = -e $filename; my $gotmode = $present ? (stat($filename))[2] : undef; my $ok = $present && ($gotmode & $mode) == $mode; if( $ok ) { $Test->ok(1, $name); } else { my $missing = ($gotmode ^ $mode) & $mode; $Test->diag(sprintf("File [%s] mode is missing component %04o!", $filename, $missing) ); $Test->ok(0, $name); } } =item file_mode_hasnt( FILENAME, MODE [, NAME ] ) Ok if the file exists and has all the bits in mode turned off, not ok if the file does not exist or the mode does not match. That is, C<< FILEMODE & MODE == 0 >> must be true. This test automatically skips if it thinks it is on a Windows platform. Contributed by Ricardo Signes C<< >> =cut sub file_mode_hasnt { if( _win32() ) { $Test->skip( "file_mode_hasnt doesn't work on Windows!" ); return; } my $filename = _normalize( shift ); my $mode = shift; my $name = shift || sprintf("%s mode has no bits of %04o", $filename, $mode); my $present = -e $filename; my $gotmode = $present ? (stat($filename))[2] : undef; my $ok = $present && ($gotmode & $mode) == 0; if( $ok ) { $Test->ok(1, $name); } else { my $bad = $gotmode & $mode; $Test->diag(sprintf("File [%s] mode has forbidden component %04o!", $filename, $bad) ); $Test->ok(0, $name); } } =item file_is_symlink_ok( FILENAME [, NAME ] ) Ok if FILENAME is a symlink, even if it points to a non-existent file. This test automatically skips if the operating system does not support symlinks. If the file does not exist, the test fails. =cut sub file_is_symlink_ok { if( _no_symlinks_here() ) { $Test->skip( "file_is_symlink_ok doesn't work on systems without symlinks!" ); return; } my $file = shift; my $name = shift || "$file is a symlink"; if( -l $file ) { $Test->ok(1, $name) } else { $Test->diag( "File [$file] is not a symlink!" ); $Test->ok(0, $name); } } =item symlink_target_exists_ok( SYMLINK [, TARGET] [, NAME ] ) Ok if FILENAME is a symlink and it points to a existing file. With the optional TARGET argument, the test fails if SYMLINK's target is not TARGET. This test automatically skips if the operating system does not support symlinks. If the file does not exist, the test fails. =cut sub symlink_target_exists_ok { if( _no_symlinks_here() ) { $Test->skip( "symlink_target_exists_ok doesn't work on systems without symlinks!" ); return; } my $file = shift; my $dest = shift || readlink( $file ); my $name = shift || "$file is a symlink"; unless( -l $file ) { $Test->diag( "File [$file] is not a symlink!" ); return $Test->ok( 0, $name ); } unless( -e $dest ) { $Test->diag( "Symlink [$file] points to non-existent target [$dest]!" ); return $Test->ok( 0, $name ); } my $actual = readlink( $file ); unless( $dest eq $actual ) { $Test->diag( "Symlink [$file] points to\n" . " got: $actual\n" . " expected: $dest\n" ); return $Test->ok( 0, $name ); } $Test->ok( 1, $name ); } =item symlink_target_dangles_ok( SYMLINK [, NAME ] ) Ok if FILENAME is a symlink and if it doesn't point to a existing file. This test automatically skips if the operating system does not support symlinks. If the file does not exist, the test fails. =cut sub symlink_target_dangles_ok { if( _no_symlinks_here() ) { $Test->skip( "symlink_target_dangles_ok doesn't work on systems without symlinks!" ); return; } my $file = shift; my $dest = readlink( $file ); my $name = shift || "$file is a symlink"; unless( -l $file ) { $Test->diag( "File [$file] is not a symlink!" ); return $Test->ok( 0, $name ); } if( -e $dest ) { $Test->diag( "Symlink [$file] points to existing file [$dest] but shouldn't!" ); return $Test->ok( 0, $name ); } $Test->ok( 1, $name ); } =item symlink_target_is( SYMLINK, TARGET [, NAME ] ) Ok if FILENAME is a symlink and if points to TARGET. This test automatically skips if the operating system does not support symlinks. If the file does not exist, the test fails. =cut sub symlink_target_is { if( _no_symlinks_here() ) { $Test->skip( "symlink_target_is doesn't work on systems without symlinks!" ); return; } my $file = shift; my $dest = shift; my $name = shift || "symlink $file points to $dest"; unless( -l $file ) { $Test->diag( "File [$file] is not a symlink!" ); return $Test->ok( 0, $name ); } my $actual_dest = readlink( $file ); my $link_error = $!; unless( defined $actual_dest ) { $Test->diag( "Symlink [$file] does not have a defined target!" ); $Test->diag( "readlink error: $link_error" ) if defined $link_error; return $Test->ok( 0, $name ); } if( $dest eq $actual_dest ) { $Test->ok( 1, $name ); } else { $Test->ok( 0, $name ); $Test->diag(" got: $actual_dest" ); $Test->diag(" expected: $dest" ); } } =item symlink_target_is_absolute_ok( SYMLINK [, NAME ] ) Ok if FILENAME is a symlink and if its target is an absolute path. This test automatically skips if the operating system does not support symlinks. If the file does not exist, the test fails. =cut sub symlink_target_is_absolute_ok { if( _no_symlinks_here() ) { $Test->skip( "symlink_target_exists_ok doesn't work on systems without symlinks" ); return; } my( $from, $from_base, $to, $to_base, $name ) = @_; my $link = readlink( $from ); my $link_err = defined( $link ) ? '' : $!; # $! doesn't always get reset my $link_abs = abs_path( rel2abs($link, $from_base) ); my $to_abs = abs_path( rel2abs($to, $to_base) ); if (defined( $link_abs ) && defined( $to_abs ) && $link_abs eq $to_abs) { $Test->ok( 1, $name ); } else { $Test->ok( 0, $name ); $link ||= 'undefined'; $link_abs ||= 'undefined'; $to_abs ||= 'undefined'; $Test->diag(" link: $from"); $Test->diag(" got: $link"); $Test->diag(" (abs): $link_abs"); $Test->diag(" expected: $to"); $Test->diag(" (abs): $to_abs"); $Test->diag(" readlink() error: $link_err") if ($link_err); } } =item dir_exists_ok( DIRECTORYNAME [, NAME ] ) Ok if the file exists and is a directory, not ok if the file doesn't exist, or exists but isn't a directory. Contributed by Buddy Burden C<< >>. =cut sub dir_exists_ok { my $filename = _normalize( shift ); my $name = shift || "$filename is a directory"; unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok(0, $name); } my $ok = -d $filename; if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] exists but is not a directory!" ); $Test->ok(0, $name); } } =item dir_contains_ok( DIRECTORYNAME, FILENAME [, NAME ] ) Ok if the directory exists and contains the file, not ok if the directory doesn't exist, or exists but doesn't contain the file. Contributed by Buddy Burden C<< >>. =cut sub dir_contains_ok { my $dirname = _normalize( shift ); my $filename = _normalize( shift ); my $name = shift || "directory $dirname contains file $filename"; unless( -d $dirname ) { $Test->diag( "Directory [$dirname] does not exist!" ); return $Test->ok(0, $name); } my $ok = -e File::Spec->catfile($dirname, $filename); if( $ok ) { $Test->ok(1, $name); } else { $Test->diag( "File [$filename] does not exist in directory $dirname!" ); $Test->ok(0, $name); } } =item link_count_is_ok( FILE, LINK_COUNT [, NAME ] ) Ok if the link count to FILE is LINK_COUNT. LINK_COUNT is interpreted as an integer. A LINK_COUNT that evaluates to 0 returns Ok if the file does not exist. =cut sub link_count_is_ok { my $file = shift; my $count = int( 0 + shift ); my $name = shift || "$file has a link count of [$count]"; my $actual = ( stat $file )[3]; unless( $actual == $count ) { $Test->diag( "File [$file] points has [$actual] links: expected [$count]!" ); return $Test->ok( 0, $name ); } $Test->ok( 1, $name ); } =item link_count_gt_ok( FILE, LINK_COUNT [, NAME ] ) Ok if the link count to FILE is greater than LINK_COUNT. LINK_COUNT is interpreted as an integer. A LINK_COUNT that evaluates to 0 returns Ok if the file has at least one link. =cut sub link_count_gt_ok { my $file = shift; my $count = int( 0 + shift ); my $name = shift || "$file has a link count of [$count]"; my $actual = (stat $file )[3]; unless( $actual > $count ) { $Test->diag( "File [$file] points has [$actual] links: ". "expected more than [$count]!" ); return $Test->ok( 0, $name ); } $Test->ok( 1, $name ); } =item link_count_lt_ok( FILE, LINK_COUNT [, NAME ] ) Ok if the link count to FILE is less than LINK_COUNT. LINK_COUNT is interpreted as an integer. A LINK_COUNT that evaluates to 0 returns Ok if the file has at least one link. =cut sub link_count_lt_ok { my $file = shift; my $count = int( 0 + shift ); my $name = shift || "$file has a link count of [$count]"; my $actual = (stat $file )[3]; unless( $actual < $count ) { $Test->diag( "File [$file] points has [$actual] links: ". "expected less than [$count]!" ); return $Test->ok( 0, $name ); } $Test->ok( 1, $name ); } # owner_is, owner_isnt, group_is and group_isnt are almost # identical in the beginning, so I'm writing a skeleton they can all use. # I can't think of a better name... sub _dm_skeleton { no warnings 'uninitialized'; if( _obviously_non_multi_user() ) { my $calling_sub = (caller(1))[3]; $Test->skip( $calling_sub . " only works on a multi-user OS!" ); return 'skip'; } my $filename = _normalize( shift ); my $testing_for = shift; my $name = shift; unless( defined $filename ) { $Test->diag( "File name not specified!" ); return $Test->ok( 0, $name ); } unless( -e $filename ) { $Test->diag( "File [$filename] does not exist!" ); return $Test->ok( 0, $name ); } return; } =item owner_is( FILE , OWNER [, NAME ] ) Ok if FILE's owner is the same as OWNER. OWNER may be a text user name or a numeric userid. Test skips on Dos, and Mac OS <= 9. If the file does not exist, the test fails. Contributed by Dylan Martin =cut sub owner_is { my $filename = shift; my $owner = shift; my $name = shift || "$filename belongs to $owner"; my $err = _dm_skeleton( $filename, $owner, $name ); return if( defined( $err ) && $err eq 'skip' ); return $err if defined($err); my $owner_uid = _get_uid( $owner ); unless( defined $owner_uid ) { $Test->diag("User [$owner] does not exist on this system!"); return $Test->ok( 0, $name ); } my $file_uid = ( stat $filename )[4]; unless( defined $file_uid ) { $Test->skip("stat failed to return owner uid for $filename!"); return; } return $Test->ok( 1, $name ) if $file_uid == $owner_uid; my $real_owner = ( getpwuid $file_uid )[0]; unless( defined $real_owner ) { $Test->diag("File does not belong to $owner!"); return $Test->ok( 0, $name ); } $Test->diag( "File [$filename] belongs to $real_owner ($file_uid), ". "not $owner ($owner_uid)!" ); return $Test->ok( 0, $name ); } =item owner_isnt( FILE, OWNER [, NAME ] ) Ok if FILE's owner is not the same as OWNER. OWNER may be a text user name or a numeric userid. Test skips on Dos and Mac OS <= 9. If the file does not exist, the test fails. Contributed by Dylan Martin =cut sub owner_isnt { my $filename = shift; my $owner = shift; my $name = shift || "$filename doesn't belong to $owner"; my $err = _dm_skeleton( $filename, $owner, $name ); return if( defined( $err ) && $err eq 'skip' ); return $err if defined($err); my $owner_uid = _get_uid( $owner ); unless( defined $owner_uid ) { return $Test->ok( 1, $name ); } my $file_uid = ( stat $filename )[4]; #$Test->diag( "owner_isnt: $owner_uid $file_uid" ); return $Test->ok( 1, $name ) if $file_uid != $owner_uid; $Test->diag( "File [$filename] belongs to $owner ($owner_uid)!" ); return $Test->ok( 0, $name ); } =item group_is( FILE , GROUP [, NAME ] ) Ok if FILE's group is the same as GROUP. GROUP may be a text group name or a numeric group id. Test skips on Dos, Mac OS <= 9 and any other operating systems that do not support getpwuid() and friends. If the file does not exist, the test fails. Contributed by Dylan Martin =cut sub group_is { my $filename = shift; my $group = shift; my $name = ( shift || "$filename belongs to group $group" ); my $err = _dm_skeleton( $filename, $group, $name ); return if( defined( $err ) && $err eq 'skip' ); return $err if defined($err); my $group_gid = _get_gid( $group ); unless( defined $group_gid ) { $Test->diag("Group [$group] does not exist on this system!"); return $Test->ok( 0, $name ); } my $file_gid = ( stat $filename )[5]; unless( defined $file_gid ) { $Test->skip("stat failed to return group gid for $filename!"); return; } return $Test->ok( 1, $name ) if $file_gid == $group_gid; my $real_group = ( getgrgid $file_gid )[0]; unless( defined $real_group ) { $Test->diag("File does not belong to $group!"); return $Test->ok( 0, $name ); } $Test->diag( "File [$filename] belongs to $real_group ($file_gid), ". "not $group ($group_gid)!" ); return $Test->ok( 0, $name ); } =item group_isnt( FILE , GROUP [, NAME ] ) Ok if FILE's group is not the same as GROUP. GROUP may be a text group name or a numeric group id. Test skips on Dos, Mac OS <= 9 and any other operating systems that do not support getpwuid() and friends. If the file does not exist, the test fails. Contributed by Dylan Martin =cut sub group_isnt { my $filename = shift; my $group = shift; my $name = shift || "$filename does not belong to group $group"; my $err = _dm_skeleton( $filename, $group, $name ); return if( defined( $err ) && $err eq 'skip' ); return $err if defined($err); my $group_gid = _get_gid( $group ); my $file_gid = ( stat $filename )[5]; unless( defined $file_gid ) { $Test->skip("stat failed to return group gid for $filename!"); return; } return $Test->ok( 1, $name ) if $file_gid != $group_gid; $Test->diag( "File [$filename] belongs to $group ($group_gid)!" ); return $Test->ok( 0, $name ); } sub _get_uid { my $owner = shift; my $owner_uid; if ($owner =~ /^\d+/) { $owner_uid = $owner; $owner = ( getpwuid $owner )[0]; } else { $owner_uid = (getpwnam($owner))[2]; } $owner_uid; } sub _get_gid { my $group = shift; my $group_uid; if ($group =~ /^\d+/) { $group_uid = $group; $group = ( getgrgid $group )[0]; } else { $group_uid = (getgrnam($group))[2]; } $group_uid; } =item file_mtime_age_ok( FILE [, WITHIN_SECONDS ] [, NAME ] ) Ok if FILE's modified time is WITHIN_SECONDS inclusive of the system's current time. This test uses stat() to obtain the mtime. If the file does not exist the test returns failure. If stat() fails, the test is skipped. =cut sub file_mtime_age_ok { my $filename = shift; my $within_secs = int shift || 0; my $name = shift || "$filename mtime within $within_secs seconds of current time"; my $time = time(); my $filetime = _stat_file($filename, 9); return if ( $filetime == -1 ); #skip return $Test->ok(1, $name) if ( $filetime + $within_secs > $time-1 ); $Test->diag( "Filename [$filename] mtime [$filetime] is not $within_secs seconds within current system time [$time]."); return $Test->ok(0, $name); } =item file_mtime_gt_ok( FILE, UNIXTIME [, NAME ] ) Ok if FILE's mtime is > UNIXTIME. This test uses stat() to get the mtime. If stat() fails this test is skipped. If FILE does not exist, this test fails. =cut sub file_mtime_gt_ok { my $filename = shift; my $time = int shift; my $name = shift || "$filename mtime is less than unix timestamp $time"; my $filetime = _stat_file($filename, 9); return if ( $filetime == -1 ); #skip return $Test->ok(1, $name) if ( $filetime > $time ); $Test->diag( "Filename [$filename] mtime [$filetime] not greater than $time" ); $Test->ok(0, $name); } =item file_mtime_lt_ok( FILE, UNIXTIME, [, NAME ] ) Ok if FILE's modified time is < UNIXTIME. This test uses stat() to get the mtime. If stat() fails this test is skipped. If FILE does not exist, this test fails. =cut sub file_mtime_lt_ok { my $filename = shift; my $time = int shift; my $name = shift || "$filename mtime less than unix timestamp $time"; # gets mtime my $filetime = _stat_file($filename, 9); return if ( $filetime == -1 ); #skip return $Test->ok(1, $name) if ( $filetime < $time ); $Test->diag( "Filename [$filename] mtime [$filetime] not less than $time" ); $Test->ok(0, $name); } # private function to safely stat a file # # Arugments: # filename file to perform on # attr_pos pos of the array returned from stat we want to compare. perldoc -f stat # # Returns: # -1 - stat failed # 0 - failure (file doesn't exist etc) # filetime - on success, time requested provided by stat # sub _stat_file { my $filename = _normalize( shift ); my $attr_pos = shift; unless( defined $filename ) { $Test->diag( "Filename not specified!" ); return 0; } unless( -e $filename ) { $Test->diag( "Filename [$filename] does not exist!" ); return 0; } my $filetime = ( stat($filename) )[$attr_pos]; unless( $filetime ) { $Test->diag( "stat of $filename failed" ); return -1; #skip on stat failure } return $filetime; } =back =head1 TO DO * check properties for other users (readable_by_root, for instance) * check times * check number of links to file * check path parts (directory, filename, extension) =head1 SEE ALSO L, L =head1 SOURCE AVAILABILITY This module is in Github: git://github.com/briandfoy/test-file.git =head1 AUTHOR brian d foy, C<< >> =head1 CREDITS Shawn Sorichetti C<< >> provided some functions. Tom Metro helped me figure out some Windows capabilities. Dylan Martin added C and C. David Wheeler added C. Buddy Burden C<< >> provided C, C, C, and C. xmikew C<< >> provided the C stuff. =head1 COPYRIGHT AND LICENSE Copyright © 2002-2016, brian d foy . All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut "The quick brown fox jumped over the lazy dog"; PK!Ó¿¬  perl5/Test/Deep/ListMethods.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ListMethods; use base 'Test::Deep::Methods'; sub call_method { my $self = shift; return [$self->SUPER::call_method(@_)]; } sub render_stack { my $self = shift; my $var = $self->SUPER::render_stack(@_); return "[$var]"; } 1; PK!¬ÞÜi��perl5/Test/Deep/Cmp.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Cmp; use overload '&' => \&make_all, '|' => \&make_any, '""' => \&string, fallback => 1, ; use Scalar::Util (); sub import { my $pkg = shift; my $callpkg = caller(); if ($callpkg =~ /^Test::Deep::/) { no strict 'refs'; push @{$callpkg."::ISA"}, $pkg; } } sub new { my $pkg = shift; my $self = bless {}, $pkg; $self->init(@_); return $self; } sub init { } sub make_all { my ($e1, $e2) = @_; return Test::Deep::all($e1, $e2); } sub make_any { my ($e1, $e2) = @_; return Test::Deep::any($e1, $e2); } sub cmp { my ($a1, $a2, $rev) = @_; ($a1, $a2) = ($a2, $a1) if $rev; return (overload::StrVal($a1) cmp overload::StrVal($a2)); } sub string { my $self = shift; return overload::StrVal($self); } sub render_stack { my $self = shift; my $var = shift; return $var; } sub renderExp { my $self = shift; return $self->renderGot($self->{val}); } sub renderGot { my $self = shift; return Test::Deep::render_val(@_); } sub reset_arrow { return 1; } sub data { my $self = shift; return $Test::Deep::Stack->getLast; } 1; PK!bØwÑ perl5/Test/Deep/RegexpVersion.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::RegexpVersion; # Older versions of Perl treated Regexp refs as opaque scalars blessed # into the "Regexp" class. Several bits of code need this so we # centralise the test for that kind of version. our $OldStyle = ($] < 5.011); 1; PK!yž×€€ perl5/Test/Deep/ScalarRefOnly.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ScalarRefOnly; use Test::Deep::Cmp; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; return Test::Deep::descend($$got, $$exp); } sub render_stack { my $self = shift; my ($var, $data) = @_; return "\${$var}"; } 1; PK!·LÁperl5/Test/Deep/ArrayEach.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ArrayEach; use Test::Deep::Cmp; use Scalar::Util (); sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; return unless ref $got && Scalar::Util::reftype($got) eq 'ARRAY'; my $exp = [ ($self->{val}) x @$got ]; return Test::Deep::descend($got, $exp); } sub renderExp { my $self = shift; my $exp = shift; return '[ ' . $self->SUPER::renderExp($self->{val}) . ', ... ]'; } 1; PK! _™œººperl5/Test/Deep/Ignore.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Ignore; use Test::Deep::Cmp; my $Singleton = __PACKAGE__->SUPER::new; sub new { return $Singleton; } sub descend { return 1; } 1; PK!H)TšŒŒperl5/Test/Deep/Any.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Any; use Scalar::Util (); use Test::Deep::Cmp; sub init { my $self = shift; my @list = map { (Scalar::Util::blessed($_) && $_->isa('Test::Deep::Any')) ? @{ $_->{val} } : $_ } @_; $self->{val} = \@list; } sub descend { my $self = shift; my $got = shift; foreach my $cmp (@{$self->{val}}) { return 1 if Test::Deep::eq_deeply_cache($got, $cmp); } return 0; } sub renderExp { my $self = shift; my @expect = map {; Test::Deep::wrap($_) } @{ $self->{val} }; my $things = join(", ", map {$_->renderExp} @expect); return "Any of ( $things )"; } sub diagnostics { my $self = shift; my ($where, $last) = @_; my $got = $self->renderGot($last->{got}); my $exp = $self->renderExp; my $diag = <{val} = \%keys; $self->{keys} = [sort @_]; } sub descend { my $self = shift; my $hash = shift; my $data = $self->data; my $exp = $self->{val}; my %got; @got{keys %$hash} = (); my @missing; my @extra; while (my ($key, $value) = each %$exp) { if (exists $got{$key}) { delete $got{$key}; } else { push(@missing, $key); } } my @diags; if (@missing and (not $self->ignoreMissing)) { push(@diags, "Missing: ".nice_list(\@missing)); } if (%got and (not $self->ignoreExtra)) { push(@diags, "Extra: ".nice_list([keys %got])); } if (@diags) { $data->{diag} = join("\n", @diags); return 0; } return 1; } sub diagnostics { my $self = shift; my ($where, $last) = @_; my $type = $self->{IgnoreDupes} ? "Set" : "Bag"; my $error = $last->{diag}; my $diag = <{val} = \%keys; $self->{keys} = [sort @_]; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; return 0 unless $self->test_reftype($got, "HASH"); return Test::Deep::descend($got, $self->hashkeysonly($exp)); } sub hashkeysonly { require Test::Deep::HashKeysOnly; my $self = shift; my $exp = shift; return Test::Deep::HashKeysOnly->new(keys %$exp) } package Test::Deep::SuperHashKeys; use base 'Test::Deep::HashKeys'; sub hashkeysonly { require Test::Deep::HashKeysOnly; my $self = shift; my $exp = shift; return Test::Deep::SuperHashKeysOnly->new(keys %$exp) } package Test::Deep::SubHashKeys; use base 'Test::Deep::HashKeys'; sub hashkeysonly { require Test::Deep::HashKeysOnly; my $self = shift; my $exp = shift; return Test::Deep::SubHashKeysOnly->new(keys %$exp) } 1; PK!ÁlºCŽŽ"perl5/Test/Deep/ArrayLengthOnly.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ArrayLengthOnly; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $len = $self->{val}; return @$got == $len; } sub render_stack { my $self = shift; my ($var, $data) = @_; return "array length of $var"; } sub renderVal { my $self = shift; my $val = shift; return "array with $val element(s)" } sub renderGot { my $self = shift; my $got = shift; return $self->renderVal(@$got + 0); } sub renderExp { my $self = shift; return $self->renderVal($self->{val}); } 1; PK!©„Dm..perl5/Test/Deep/Boolean.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Boolean; use Test::Deep::Cmp; sub init { my $self = shift; $self->{val} = shift() ? 1 : 0; } sub descend { my $self = shift; my $got = shift; return !( $got xor $self->{val} ); } sub diag_message { my $self = shift; my $where = shift; return "Comparing $where as a boolean"; } sub renderExp { my $self = shift; $self->renderGot($self->{val}); } sub renderGot { my $self = shift; my $val = shift; return ($val ? "true" : "false")." (".Test::Deep::render_val($val).")"; } 1; PK!Ç0S[##perl5/Test/Deep/RefType.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::RefType; use Test::Deep::Cmp; use Scalar::Util qw( reftype ); sub init { my $self = shift; $self->{val} = shift; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; my $reftype = reftype($got); return Test::Deep::descend($reftype, Test::Deep::shallow($exp)); } sub render_stack { my $self = shift; my $var = shift; return "reftype($var)"; } sub renderGot { my $self = shift; my $got = shift; $self->SUPER::renderGot(reftype($got)); } 1; PK!Žð}°°perl5/Test/Deep/ScalarRef.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ScalarRef; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; return 0 unless $self->test_class($got); return 0 unless $self->test_reftype($got, Scalar::Util::reftype($exp)); return Test::Deep::descend($got, Test::Deep::scalarrefonly($exp)); } 1; PK!—j~qqperl5/Test/Deep/String.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::String; use Test::Deep::Cmp; sub init { my $self = shift; $self->{val} = shift; } sub descend { my $self = shift; my $got = shift().""; $self->data->{got} = $got; return $got eq $self->{val}; } sub diag_message { my $self = shift; my $where = shift; return "Comparing $where as a string"; } 1; PK!!`¾Œêêperl5/Test/Deep/Ref.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Ref; use Test::Deep::Cmp; use Scalar::Util qw( blessed ); sub test_class { my $self = shift; my $got = shift; my $exp = $self->{val}; if ($Test::Deep::Snobby) { return Test::Deep::descend($got, Test::Deep::blessed(blessed($exp))); } else { return 1; } } sub test_reftype { my $self = shift; my $got = shift; my $reftype = shift; return Test::Deep::descend($got, Test::Deep::reftype($reftype)); } 1; PK!„l„ óóperl5/Test/Deep/HashElements.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::HashElements; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; my $data = $self->data; my $master = $self->getMaster($got, $exp); foreach my $key (keys %$master) { $data->{index} = $key; my $got_elem = exists $got->{$key} ? $got->{$key} : $Test::Deep::DNE; my $exp_elem = exists $exp->{$key} ? $exp->{$key} : $Test::Deep::DNE; next if Test::Deep::descend($got_elem, $exp_elem); return 0; } return 1; } sub getMaster { my $self = shift; my ($got, $exp) = @_; return keys %$got > keys %$exp ? $got : $exp; } sub render_stack { my $self = shift; my ($var, $data) = @_; $var .= "->" unless $Test::Deep::Stack->incArrow; $var .= '{"'.quotemeta($data->{index}).'"}'; return $var; } sub reset_arrow { return 0; } package Test::Deep::SuperHashElements; use base 'Test::Deep::HashElements'; sub getMaster { my $self = shift; my ($got, $exp) = @_; return $exp; } package Test::Deep::SubHashElements; use base 'Test::Deep::HashElements'; sub getMaster { my $self = shift; my ($got, $exp) = @_; return $got; } 1; PK!×u~ppperl5/Test/Deep/Set.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Set; use Test::Deep::Cmp; sub init { my $self = shift; $self->{IgnoreDupes} = shift; $self->{SubSup} = shift; $self->{val} = []; $self->add(@_); } sub descend { my $self = shift; my $d1 = shift; my $d2 = $self->{val}; my $IgnoreDupes = $self->{IgnoreDupes}; my $data = $self->data; my $SubSup = $self->{SubSup}; my $type = $IgnoreDupes ? "Set" : "Bag"; my $diag; if (ref $d1 ne 'ARRAY') { my $got = Test::Deep::render_val($d1); $diag = <= 0; $i--) { if (Test::Deep::eq_deeply_cache($got[$i], $expect)) { $found = 1; push(@found, $expect); splice(@got, $i, 1); last unless $IgnoreDupes; } } push(@missing, $expect) unless $found; } my @diags; if (@missing and $SubSup ne "sub" && $SubSup ne "none") { push(@diags, "Missing: ".nice_list(\@missing)); } if (@got and $SubSup ne "sup" && $SubSup ne "none") { my $got = __PACKAGE__->new($IgnoreDupes, "", @got); push(@diags, "Extra: ".nice_list($got->{val})); } if (@found and $SubSup eq "none") { my $found = __PACKAGE__->new($IgnoreDupes, "", @found); push(@diags, "Extra: ".nice_list($found->{val})); } $diag = join("\n", @diags); } if ($diag) { $data->{diag} = $diag; return 0; } else { return 1; } } sub diagnostics { my $self = shift; my ($where, $last) = @_; my $type = $self->{IgnoreDupes} ? "Set" : "Bag"; $type = "Sub$type" if $self->{SubSup} eq "sub"; $type = "Super$type" if $self->{SubSup} eq "sup"; $type = "NoneOf" if $self->{SubSup} eq "none"; my $error = $last->{diag}; my $diag = <{IgnoreDupes}; my $already = $self->{val}; local $Test::Deep::Expects = 1; foreach my $new_elem (@array) { my $want_push = 1; my $push_this = $new_elem; foreach my $old_elem (@$already) { if (Test::Deep::eq_deeply($new_elem, $old_elem)) { $push_this = $old_elem; $want_push = ! $IgnoreDupes; last; } } push(@$already, $push_this) if $want_push; } # so we can compare 2 Test::Deep::Set objects using array comparison @$already = sort {(defined $a ? $a : "") cmp (defined $b ? $b : "")} @$already; } sub nice_list { my $list = shift; my @scalars = grep ! ref $_, @$list; my $refs = grep ref $_, @$list; my @ref_string = "$refs reference" if $refs; $ref_string[0] .= "s" if $refs > 1; # sort them so we can predict the diagnostic output return join(", ", (map {Test::Deep::render_val($_)} sort {(defined $a ? $a : "") cmp (defined $b ? $b : "")} @scalars), @ref_string ); } sub compare { my $self = shift; my $other = shift; return 0 if $self->{IgnoreDupes} != $other->{IgnoreDupes}; # this works (kind of) because the arrays are sorted return Test::Deep::descend($self->{val}, $other->{val}); } 1; PK!v앾¾perl5/Test/Deep/All.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::All; use Scalar::Util (); use Test::Deep::Cmp; sub init { my $self = shift; my @list = map { (Scalar::Util::blessed($_) && $_->isa('Test::Deep::All')) ? @{ $_->{val} } : $_ } @_; $self->{val} = \@list; } sub descend { my $self = shift; my $got = shift; my $data = $self->data; my $index = 1; foreach my $cmp (@{$self->{val}}) { $data->{index} = $index; $index++; next if Test::Deep::descend($got, $cmp); return 0 } return 1; } sub render_stack { my $self = shift; my $var = shift; my $data = shift; my $max = @{$self->{val}}; return "(Part $data->{index} of $max in $var)"; } 1; PK!@š‹ššperl5/Test/Deep/MM.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::MM; sub import { my $self = shift; my ($pkg) = caller(); my $mpkg = $pkg."::Methods"; foreach my $attr (@_) { if ($attr =~ /^[a-z]/) { no strict 'refs'; *{$mpkg."::$attr"} = \&{$attr}; } else { my $get_name = $mpkg."::get$attr"; my $set_name = $mpkg."::set$attr"; my $get_sub = sub { return $_[0]->{$attr}; }; my $set_sub = sub { return $_[0]->{$attr} = $_[1]; }; { no strict 'refs'; *$get_name = $get_sub; *$set_name = $set_sub; push(@{$pkg."::ISA"}, $mpkg); } } } } sub new { my $pkg = shift; my $self = bless {}, $pkg; $self->init(@_); return $self; } sub init { my $self = shift; while (@_) { my $name = shift || confess("No name"); my $method = "set$name"; $self->$method(shift); } } 1; PK!J 8ß@@perl5/Test/Deep/Number.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Number; use Test::Deep::Cmp; use Scalar::Util; sub init { my $self = shift; $self->{val} = shift(@_) + 0; $self->{tolerance} = shift; } sub descend { my $self = shift; my $got = shift; $self->data->{got_string} = $got; { no warnings 'numeric'; $got += 0; } $self->data->{got} = $got; if (defined(my $tolerance = $self->{tolerance})) { return abs($got - $self->{val}) <= $tolerance; } else { return $got == $self->{val}; } } sub diag_message { my $self = shift; my $where = shift; return "Comparing $where as a number"; } sub renderGot { my $self = shift; my $val = shift; my $got_string = $self->data->{got_string}; if ("$val" ne "$got_string") { $got_string = $self->SUPER::renderGot($got_string); return "$val ($got_string)" } else { return $val; } } sub renderExp { my $self = shift; my $exp = $self->{val}; if (defined(my $tolerance = $self->{tolerance})) { return "$exp +/- $tolerance"; } else { return $exp; } } 1; PK!r N344perl5/Test/Deep/Stack.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Stack; use Carp qw( confess ); use Scalar::Util; use Test::Deep::MM qw( new init Stack Arrow ); sub init { my $self = shift; $self->SUPER::init(@_); $self->setStack([]) unless $self->getStack; } sub push { my $self = shift; push(@{$self->getStack}, @_); } sub pop { my $self = shift; return pop @{$self->getStack}; } sub render { my $self = shift; my $var = shift; my $stack = $self->getStack; $self->setArrow(0); foreach my $data (@$stack) { my $exp = $data->{exp}; if (Scalar::Util::blessed($exp) and $exp->isa("Test::Deep::Cmp")) { $var = $exp->render_stack($var, $data); $self->setArrow(0) if $exp->reset_arrow; } else { confess "Don't know how to render '$exp'"; } } return $var; } sub getLast { my $self = shift; return $self->getStack->[-1]; } sub incArrow { my $self = shift; my $a = $self->getArrow; $self->setArrow($a + 1); return $a; } sub length { my $self = shift; return @{$self->getStack} + 0; } 1; PK!ïørperl5/Test/Deep/Cache.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Cache; use Test::Deep::Cache::Simple; sub new { my $pkg = shift; my $self = bless {}, $pkg; $self->{expects} = [Test::Deep::Cache::Simple->new]; $self->{normal} = [Test::Deep::Cache::Simple->new]; $self->local; return $self; } sub add { my $self = shift; my $type = $self->type; $self->{$type}->[-1]->add(@_); } sub cmp { # go through all the caches to see if we know this one my $self = shift; my $type = $self->type; foreach my $cache (@{$self->{$type}}) { return 1 if $cache->cmp(@_); } return 0 } sub local { my $self = shift; foreach my $type (qw( expects normal )) { push(@{$self->{$type}}, Test::Deep::Cache::Simple->new); } } sub finish { my $self = shift; my $keep = shift; foreach my $type (qw( expects normal )) { my $caches = $self->{$type}; my $last = pop @$caches; $caches->[-1]->absorb($last) if $keep; } } sub type { return $Test::Deep::Expects ? "expects" : "normal"; } 1; PK!Jƒb�UUperl5/Test/Deep/Shallow.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Shallow; use Test::Deep::Cmp; use Scalar::Util qw( refaddr ); sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; my $ok; if (!defined $got and !defined $exp) { $ok = 1; } elsif (defined $got xor defined $exp) { $ok = 0; } elsif (ref $got and ref $exp) { $ok = refaddr($got) == refaddr($exp); } elsif (ref $got xor ref $exp) { $ok = 0; } else { $ok = $got eq $exp; } return $ok; } 1; PK!AݤÝ44perl5/Test/Deep/Blessed.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Blessed; use Test::Deep::Cmp; use Scalar::Util qw( blessed ); sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; my $blessed = blessed($got); return Test::Deep::descend($blessed, Test::Deep::shallow($exp)); } sub render_stack { my $self = shift; my $var = shift; return "blessed($var)" } sub renderGot { my $self = shift; my $got = shift; $self->SUPER::renderGot(blessed($got)); } 1; PK!ëD‰perl5/Test/Deep/Isa.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Isa; use Test::Deep::Cmp; use Scalar::Util; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; return Scalar::Util::blessed($got) ? $got->isa($self->{val}) : ref($got) eq $self->{val}; } sub diag_message { my $self = shift; my $where = shift; return "Checking class of $where with isa()"; } sub renderExp { my $self = shift; return "blessed into or ref of type '$self->{val}'"; } 1; PK!8<`àkkperl5/Test/Deep/Class.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Class; use Test::Deep::Cmp; sub init { my $self = shift; my $snobby = shift; my $val = shift; $self->{snobby} = $snobby; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; local $Test::Deep::Snobby = $self->{snobby}; Test::Deep::wrap($self->{val})->descend($got); } 1; PK!n™¿Î€€perl5/Test/Deep/Regexp.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Regexp; use Test::Deep::Cmp; use Test::Deep::RegexpMatches; sub init { my $self = shift; my $val = shift; $val = ref $val ? $val : qr/$val/; $self->{val} = $val; if (my $matches = shift) { $self->{matches} = Test::Deep::regexpmatches($matches, $val); $self->{flags} = shift || ""; } } sub descend { my $self = shift; my $got = shift; my $re = $self->{val}; if (my $match_exp = $self->{matches}) { my $flags = $self->{flags}; my @match_got; if ($flags eq "g") { @match_got = $got =~ /$re/g; } else { @match_got = $got =~ /$re/; } if (@match_got) { return Test::Deep::descend(\@match_got, $match_exp); } else { return 0; } } else { return ($got =~ $re) ? 1 : 0; } } sub diag_message { my $self = shift; my $where = shift; return "Using Regexp on $where"; } sub render_stack1 { my $self = shift; my $stack = shift; return "($stack =~ $self->{regex})"; } sub renderExp { my $self = shift; return "$self->{val}"; } sub renderGot { my $self = shift; my $got = shift; if (defined (my $class = Scalar::Util::blessed($got))) { my $ostr = qq{$got}; if ($ostr ne overload::StrVal($got)) { return qq{'$ostr' (instance of $class)}; } } return Test::Deep::render_val($got); } 1; PK!=Ó?˜  perl5/Test/Deep/Methods.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Methods; use Test::Deep::Cmp; use Scalar::Util; sub init { my $self = shift; # get them all into [$name,@args] => $value format my @methods; while (@_) { my $name = shift; my $value = shift; push(@methods, [ ref($name) ? $name : [ $name ], $value ] ); } $self->{methods} = \@methods; } sub descend { my $self = shift; my $got = shift; my $data = $self->data; foreach my $method (@{$self->{methods}}) { $data->{method} = $method; my ($call, $exp_res) = @$method; my ($name, @args) = @$call; local $@; my $got_res; if (! eval { $got_res = $self->call_method($got, $call); 1 }) { die $@ unless $@ =~ /\ACan't locate object method "\Q$name"/; $got_res = $Test::Deep::DNE; } next if Test::Deep::descend($got_res, $exp_res); return 0; } return 1; } sub call_method { my $self = shift; my ($got, $call) = @_; my ($name, @args) = @$call; return $got->$name(@args); } sub render_stack { my $self = shift; my ($var, $data) = @_; my $method = $data->{method}; my ($call, $expect) = @$method; my ($name, @args) = @$call; my $args = @args ? "(".join(", ", @args).")" : ""; $var .= "->$name$args"; return $var; } 1; PK!Ç1×ÁÁperl5/Test/Deep/Code.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Code; use Test::Deep::Cmp; sub init { my $self = shift; my $code = shift || die "No coderef supplied"; $self->{code} = $code; } sub descend { my $self = shift; my $got = shift; my ($ok, $diag) = &{$self->{code}}($got); $self->data->{diag} = $diag; return $ok; } sub diagnostics { my $self = shift; my ($where, $last) = @_; my $error = $last->{diag}; my $data = Test::Deep::render_val($last->{got}); my $diag = <can("import"); # make the stack look like it should for use Test::Deep my $pkg = shift; unshift(@_, "Test::Deep"); push @_, '_notest'; goto &$import; } 1; =head1 NAME Test::Deep::NoTest - Use Test::Deep outside of the testing framework =head1 SYNOPSIS use Test::Deep::NoTest; if (eq_deeply($a, $b)) { print "they were deeply equal\n"; } =head1 DESCRIPTION This exports all the same things as Test::Deep but it does not load Test::Builder so it can be used in ordinary non-test situations. PK!÷‘½Ñµµperl5/Test/Deep/Cache/Simple.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Cache::Simple; use Carp qw( confess ); use Scalar::Util qw( refaddr ); BEGIN { if (grep /^weaken$/, @Scalar::Util::EXPORT_FAIL) { # we're running on a version of perl that has no weak refs, so we # just install a no-op sub for weaken instead of importing it *weaken = sub {}; } else { Scalar::Util->import('weaken'); } } sub new { my $pkg = shift; my $self = bless {}, $pkg; return $self; } sub add { my $self = shift; my ($d1, $d2) = @_; { local $SIG{__DIE__}; local $@; # cannot weaken read only refs, no harm if we can't as they never # disappear eval{weaken($d1)}; eval{weaken($d2)}; } $self->{fn_get_key(@_)} = [$d1, $d2]; } sub cmp { my $self = shift; my $key = fn_get_key(@_); my $pair = $self->{$key}; # are both weakened refs still valid, if not delete this entry if (ref($pair->[0]) and ref($pair->[1])) { return 1; } else { delete $self->{$key}; return 0; } } sub absorb { my $self = shift; my $other = shift; @{$self}{keys %$other} = values %$other; } sub fn_get_key { return join(",", sort (map {refaddr($_)} @_)); } 1; PK!ÝCï"vvperl5/Test/Deep/ArrayLength.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ArrayLength; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; return 0 unless $self->test_reftype($got, "ARRAY"); return Test::Deep::descend($got, Test::Deep::arraylengthonly($exp)); } 1; PK!ý©ÁÝ¥¥$perl5/Test/Deep/ArrayElementsOnly.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::ArrayElementsOnly; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; my $data = $self->data; for my $i (0..$#{$exp}) { $data->{index} = $i; my $got_elem = $got->[$i]; my $exp_elem = $exp->[$i]; return 0 unless Test::Deep::descend($got_elem, $exp_elem) } return 1; } sub render_stack { my $self = shift; my ($var, $data) = @_; $var .= "->" unless $Test::Deep::Stack->incArrow; $var .= "[$data->{index}]"; return $var; } sub reset_arrow { return 0; } 1; PK!x^6  perl5/Test/Deep/RegexpOnly.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::RegexpOnly; use Test::Deep::Cmp; use Scalar::Util qw( blessed ); sub init { my $self = shift; my $val = shift; $val = ref $val ? $val : qr/$val/; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $re = $self->{val}; return $got =~ $self->{val} ? 1 : 0; } sub diag_message { my $self = shift; my $where = shift; return "Using Regexp on $where"; } sub renderExp { my $self = shift; return "$self->{val}"; } 1; PK!j`˜……perl5/Test/Deep/Hash.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Hash; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; my $data = $self->data; return 0 unless Test::Deep::descend($got, $self->hash_keys($exp)); return 0 unless $self->test_class($got); return Test::Deep::descend($got, $self->hash_elements($exp)); } sub hash_elements { require Test::Deep::HashElements; my $self = shift; return Test::Deep::HashElements->new(@_); } sub hash_keys { require Test::Deep::HashKeys; my $self = shift; my $exp = shift; return Test::Deep::HashKeys->new(keys %$exp); } sub reset_arrow { return 0; } package Test::Deep::SuperHash; use base 'Test::Deep::Hash'; sub hash_elements { require Test::Deep::HashElements; my $self = shift; return Test::Deep::SuperHashElements->new(@_); } sub hash_keys { require Test::Deep::HashKeys; my $self = shift; my $exp = shift; return Test::Deep::SuperHashKeys->new(keys %$exp); } package Test::Deep::SubHash; use base 'Test::Deep::Hash'; sub hash_elements { require Test::Deep::HashElements; my $self = shift; return Test::Deep::SubHashElements->new(@_); } sub hash_keys { require Test::Deep::HashKeys; my $self = shift; my $exp = shift; return Test::Deep::SubHashKeys->new(keys %$exp); } 1; PK!ñ)ç§§ perl5/Test/Deep/RegexpRefOnly.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::RegexpRefOnly; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; return $got eq $exp; } sub render_stack { my $self = shift; my ($var, $data) = @_; return "m/$var/"; } sub renderGot { my $self = shift; return shift().""; } 1; PK!ïuÝÝperl5/Test/Deep/Array.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::Array; use Test::Deep::Ref; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; return 0 unless Test::Deep::descend($got, Test::Deep::arraylength(scalar @$exp)); return 0 unless $self->test_class($got); return Test::Deep::descend($got, Test::Deep::arrayelementsonly($exp)); } sub reset_arrow { return 0; } 1; PK!NNk#–– perl5/Test/Deep/RegexpMatches.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::RegexpMatches; use Test::Deep::Array; use base 'Test::Deep::Array'; use Scalar::Util qw( blessed ); sub init { my $self = shift; my $val = shift; $val = Test::Deep::array($val) unless blessed($val) and $val->isa("Test::Deep::Cmp"); $self->{val} = $val; $self->{regex} = shift; } sub descend { my $self = shift; my $got = shift; return Test::Deep::descend($got, $self->{val}); } sub render_stack { my $self = shift; my $stack = shift; $stack = "[$stack =~ $self->{regex}]"; return $stack; # return $self->SUPER::render_stack($stack); } sub reset_arrow { return 1; } 1; PK!®œÆˆperl5/Test/Deep/RegexpRef.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::RegexpRef; use Test::Deep::Ref; use Test::Deep::RegexpVersion; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my $exp = $self->{val}; if ($Test::Deep::RegexpVersion::OldStyle) { return 0 unless $self->test_class($got, "Regexp"); return 0 unless $self->test_reftype($got, "SCALAR"); } else { return 0 unless $self->test_reftype($got, "REGEXP"); } return Test::Deep::descend($got, Test::Deep::regexprefonly($exp)); } sub renderGot { my $self = shift; return shift().""; } 1; PK!Jµ‚[FFperl5/Test/Deep/HashEach.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::HashEach; use Test::Deep::Cmp; sub init { my $self = shift; my $val = shift; $self->{val} = $val; } sub descend { my $self = shift; my $got = shift; my %exp; @exp{keys %$got} = ($self->{val}) x (keys %$got); return Test::Deep::descend($got, \%exp); } 1; PK!¦ç[*eeperl5/Test/Deep/None.pmnuÏÃ6Ç$use strict; use warnings; package Test::Deep::None; use Test::Deep::Cmp; sub init { my $self = shift; my @list = map { eval { $_->isa('Test::Deep::None') } ? @{ $_->{val} } : $_ } @_; $self->{val} = \@list; } sub descend { my $self = shift; my $got = shift; foreach my $cmp (@{$self->{val}}) { return 0 if Test::Deep::eq_deeply_cache($got, $cmp); } return 1; } sub renderExp { my $self = shift; my @expect = map {; Test::Deep::wrap($_) } @{ $self->{val} }; my $things = join(", ", map {$_->renderExp} @expect); return "None of ( $things )"; } sub diagnostics { my $self = shift; my ($where, $last) = @_; my $got = $self->renderGot($last->{got}); my $exp = $self->renderExp; my $diag = <{val} = $val; } sub descend { my $self = shift; my $got = shift; return Scalar::Util::blessed($got) && $got->isa($self->{val}); } sub diag_message { my $self = shift; my $where = shift; return "Checking class of $where with isa()"; } sub renderExp { my $self = shift; return "blessed into '$self->{val}' or subclass of '$self->{val}'"; } 1; PK!’%ƒî::perl5/Test/Fatal.pmnuÏÃ6Ç$use strict; use warnings; package Test::Fatal; # ABSTRACT: incredibly simple helpers for testing code with exceptions $Test::Fatal::VERSION = '0.016'; #pod =head1 SYNOPSIS #pod #pod use Test::More; #pod use Test::Fatal; #pod #pod use System::Under::Test qw(might_die); #pod #pod is( #pod exception { might_die; }, #pod undef, #pod "the code lived", #pod ); #pod #pod like( #pod exception { might_die; }, #pod qr/turns out it died/, #pod "the code died as expected", #pod ); #pod #pod isa_ok( #pod exception { might_die; }, #pod 'Exception::Whatever', #pod 'the thrown exception', #pod ); #pod #pod =head1 DESCRIPTION #pod #pod Test::Fatal is an alternative to the popular L. It does much #pod less, but should allow greater flexibility in testing exception-throwing code #pod with about the same amount of typing. #pod #pod It exports one routine by default: C. #pod #pod B C intentionally does not manipulate the call stack. #pod User-written test functions that use C must be careful to avoid #pod false positives if exceptions use stack traces that show arguments. For a more #pod magical approach involving globally overriding C, see #pod L. #pod #pod =cut use Carp (); use Try::Tiny 0.07; use Exporter 5.57 'import'; our @EXPORT = qw(exception); our @EXPORT_OK = qw(exception success dies_ok lives_ok); #pod =func exception #pod #pod my $exception = exception { ... }; #pod #pod C takes a bare block of code and returns the exception thrown by #pod that block. If no exception was thrown, it returns undef. #pod #pod B If the block results in a I exception, such as 0 or the #pod empty string, Test::Fatal itself will die. Since either of these cases #pod indicates a serious problem with the system under testing, this behavior is #pod considered a I. If you must test for these conditions, you should use #pod L's try/catch mechanism. (Try::Tiny is the underlying exception #pod handling system of Test::Fatal.) #pod #pod Note that there is no TAP assert being performed. In other words, no "ok" or #pod "not ok" line is emitted. It's up to you to use the rest of C in an #pod existing test like C, C, C, et cetera. Or you may wish to use #pod the C and C wrappers, which do provide TAP output. #pod #pod C does I alter the stack presented to the called block, meaning #pod that if the exception returned has a stack trace, it will include some frames #pod between the code calling C and the thing throwing the exception. #pod This is considered a I because it avoids the occasionally twitchy #pod C mechanism. #pod #pod B This is not a great idea: #pod #pod sub exception_like(&$;$) { #pod my ($code, $pattern, $name) = @_; #pod like( &exception($code), $pattern, $name ); #pod } #pod #pod exception_like(sub { }, qr/foo/, 'foo appears in the exception'); #pod #pod If the code in the C<...> is going to throw a stack trace with the arguments to #pod each subroutine in its call stack (for example via C, #pod the test name, "foo appears in the exception" will itself be matched by the #pod regex. Instead, write this: #pod #pod like( exception { ... }, qr/foo/, 'foo appears in the exception' ); #pod #pod If you really want a test function that passes the test name, wrap the #pod arguments in an array reference to hide the literal text from a stack trace: #pod #pod sub exception_like(&$) { #pod my ($code, $args) = @_; #pod my ($pattern, $name) = @$args; #pod like( &exception($code), $pattern, $name ); #pod } #pod #pod exception_like(sub { }, [ qr/foo/, 'foo appears in the exception' ] ); #pod #pod To aid in avoiding the problem where the pattern is seen in the exception #pod because of the call stack, C<$Carp::MAxArgNums> is locally set to -1 when the #pod code block is called. If you really don't want that, set it back to whatever #pod value you like at the beginning of the code block. Obviously, this solution #pod doens't affect all possible ways that args of subroutines in the call stack #pod might taint the test. The intention here is to prevent some false passes from #pod people who didn't read the documentation. Your punishment for reading it is #pod that you must consider whether to do anything about this. #pod #pod B: One final bad idea: #pod #pod isnt( exception { ... }, undef, "my code died!"); #pod #pod It's true that this tests that your code died, but you should really test that #pod it died I. For example, if you make an unrelated mistake #pod in the block, like using the wrong dereference, your test will pass even though #pod the code to be tested isn't really run at all. If you're expecting an #pod inspectable exception with an identifier or class, test that. If you're #pod expecting a string exception, consider using C. #pod #pod =cut our ($REAL_TBL, $REAL_CALCULATED_TBL) = (1, 1); sub exception (&) { my $code = shift; return try { my $incremented = defined $Test::Builder::Level ? $Test::Builder::Level - $REAL_CALCULATED_TBL : 0; local $Test::Builder::Level = $REAL_CALCULATED_TBL; if ($incremented) { # each call to exception adds 5 stack frames $Test::Builder::Level += 5; for my $i (1..$incremented) { # -2 because we want to see it from the perspective of the call to # is() within the call to $code->() my $caller = caller($Test::Builder::Level - 2); if ($caller eq __PACKAGE__) { # each call to exception adds 5 stack frames $Test::Builder::Level = $Test::Builder::Level + 5; } else { $Test::Builder::Level = $Test::Builder::Level + 1; } } } local $REAL_CALCULATED_TBL = $Test::Builder::Level; local $Carp::MaxArgNums = -1; $code->(); return undef; } catch { return $_ if $_; my $problem = defined $_ ? 'false' : 'undef'; Carp::confess("$problem exception caught by Test::Fatal::exception"); }; } #pod =func success #pod #pod try { #pod should_live; #pod } catch { #pod fail("boo, we died"); #pod } success { #pod pass("hooray, we lived"); #pod }; #pod #pod C, exported only by request, is a L helper with semantics #pod identical to L|Try::Tiny/finally>, but the body of the block will #pod only be run if the C block ran without error. #pod #pod Although almost any needed exception tests can be performed with C, #pod success blocks may sometimes help organize complex testing. #pod #pod =cut sub success (&;@) { my $code = shift; return finally( sub { return if @_; # <-- only run on success $code->(); }, @_ ); } #pod =func dies_ok #pod #pod =func lives_ok #pod #pod Exported only by request, these two functions run a given block of code, and #pod provide TAP output indicating if it did, or did not throw an exception. #pod These provide an easy upgrade path for replacing existing unit tests based on #pod C. #pod #pod RJBS does not suggest using this except as a convenience while porting tests to #pod use Test::Fatal's C routine. #pod #pod use Test::More tests => 2; #pod use Test::Fatal qw(dies_ok lives_ok); #pod #pod dies_ok { die "I failed" } 'code that fails'; #pod #pod lives_ok { return "I'm still alive" } 'code that does not fail'; #pod #pod =cut my $Tester; # Signature should match that of Test::Exception sub dies_ok (&;$) { my $code = shift; my $name = shift; require Test::Builder; $Tester ||= Test::Builder->new; my $tap_pos = $Tester->current_test; my $exception = exception( \&$code ); $name ||= $tap_pos != $Tester->current_test ? "...and code should throw an exception" : "code should throw an exception"; my $ok = $Tester->ok( $exception, $name ); $ok or $Tester->diag( "expected an exception but none was raised" ); return $ok; } sub lives_ok (&;$) { my $code = shift; my $name = shift; require Test::Builder; $Tester ||= Test::Builder->new; my $tap_pos = $Tester->current_test; my $exception = exception( \&$code ); $name ||= $tap_pos != $Tester->current_test ? "...and code should not throw an exception" : "code should not throw an exception"; my $ok = $Tester->ok( ! $exception, $name ); $ok or $Tester->diag( "expected return but an exception was raised" ); return $ok; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Fatal - incredibly simple helpers for testing code with exceptions =head1 VERSION version 0.016 =head1 SYNOPSIS use Test::More; use Test::Fatal; use System::Under::Test qw(might_die); is( exception { might_die; }, undef, "the code lived", ); like( exception { might_die; }, qr/turns out it died/, "the code died as expected", ); isa_ok( exception { might_die; }, 'Exception::Whatever', 'the thrown exception', ); =head1 DESCRIPTION Test::Fatal is an alternative to the popular L. It does much less, but should allow greater flexibility in testing exception-throwing code with about the same amount of typing. It exports one routine by default: C. B C intentionally does not manipulate the call stack. User-written test functions that use C must be careful to avoid false positives if exceptions use stack traces that show arguments. For a more magical approach involving globally overriding C, see L. =head1 FUNCTIONS =head2 exception my $exception = exception { ... }; C takes a bare block of code and returns the exception thrown by that block. If no exception was thrown, it returns undef. B If the block results in a I exception, such as 0 or the empty string, Test::Fatal itself will die. Since either of these cases indicates a serious problem with the system under testing, this behavior is considered a I. If you must test for these conditions, you should use L's try/catch mechanism. (Try::Tiny is the underlying exception handling system of Test::Fatal.) Note that there is no TAP assert being performed. In other words, no "ok" or "not ok" line is emitted. It's up to you to use the rest of C in an existing test like C, C, C, et cetera. Or you may wish to use the C and C wrappers, which do provide TAP output. C does I alter the stack presented to the called block, meaning that if the exception returned has a stack trace, it will include some frames between the code calling C and the thing throwing the exception. This is considered a I because it avoids the occasionally twitchy C mechanism. B This is not a great idea: sub exception_like(&$;$) { my ($code, $pattern, $name) = @_; like( &exception($code), $pattern, $name ); } exception_like(sub { }, qr/foo/, 'foo appears in the exception'); If the code in the C<...> is going to throw a stack trace with the arguments to each subroutine in its call stack (for example via C, the test name, "foo appears in the exception" will itself be matched by the regex. Instead, write this: like( exception { ... }, qr/foo/, 'foo appears in the exception' ); If you really want a test function that passes the test name, wrap the arguments in an array reference to hide the literal text from a stack trace: sub exception_like(&$) { my ($code, $args) = @_; my ($pattern, $name) = @$args; like( &exception($code), $pattern, $name ); } exception_like(sub { }, [ qr/foo/, 'foo appears in the exception' ] ); To aid in avoiding the problem where the pattern is seen in the exception because of the call stack, C<$Carp::MAxArgNums> is locally set to -1 when the code block is called. If you really don't want that, set it back to whatever value you like at the beginning of the code block. Obviously, this solution doens't affect all possible ways that args of subroutines in the call stack might taint the test. The intention here is to prevent some false passes from people who didn't read the documentation. Your punishment for reading it is that you must consider whether to do anything about this. B: One final bad idea: isnt( exception { ... }, undef, "my code died!"); It's true that this tests that your code died, but you should really test that it died I. For example, if you make an unrelated mistake in the block, like using the wrong dereference, your test will pass even though the code to be tested isn't really run at all. If you're expecting an inspectable exception with an identifier or class, test that. If you're expecting a string exception, consider using C. =head2 success try { should_live; } catch { fail("boo, we died"); } success { pass("hooray, we lived"); }; C, exported only by request, is a L helper with semantics identical to L|Try::Tiny/finally>, but the body of the block will only be run if the C block ran without error. Although almost any needed exception tests can be performed with C, success blocks may sometimes help organize complex testing. =head2 dies_ok =head2 lives_ok Exported only by request, these two functions run a given block of code, and provide TAP output indicating if it did, or did not throw an exception. These provide an easy upgrade path for replacing existing unit tests based on C. RJBS does not suggest using this except as a convenience while porting tests to use Test::Fatal's C routine. use Test::More tests => 2; use Test::Fatal qw(dies_ok lives_ok); dies_ok { die "I failed" } 'code that fails'; lives_ok { return "I'm still alive" } 'code that does not fail'; =head1 AUTHOR Ricardo Signes =head1 CONTRIBUTORS =for stopwords David Golden Graham Knop Jesse Luehrs Joel Bernstein Karen Etheridge =over 4 =item * David Golden =item * Graham Knop =item * Jesse Luehrs =item * Joel Bernstein =item * Karen Etheridge =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by Ricardo Signes. 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 PK! ]&Cøtøtperl5/Test/Alien.pmnuÏÃ6Ç$package Test::Alien; use strict; use warnings; use 5.008004; use Env qw( @PATH ); use File::Which 1.10 qw( which ); use Capture::Tiny qw( capture capture_merged ); use Alien::Build::Temp; use File::Copy qw( move ); use Text::ParseWords qw( shellwords ); use Test2::API qw( context run_subtest ); use Exporter qw( import ); use Path::Tiny qw( path ); use Alien::Build::Util qw( _dump ); use Config; our @EXPORT = qw( alien_ok run_ok xs_ok ffi_ok with_subtest synthetic helper_ok interpolate_template_is interpolate_run_ok plugin_ok ); # ABSTRACT: Testing tools for Alien modules our $VERSION = '2.83'; # VERSION our @aliens; sub alien_ok ($;$) { my($alien, $message) = @_; my $name = ref $alien ? ref($alien) . '[instance]' : $alien; $name = 'undef' unless defined $name; my @methods = qw( cflags libs dynamic_libs bin_dir ); $message ||= "$name responds to: @methods"; my $ok; my @diag; if(defined $alien) { my @missing = grep { ! $alien->can($_) } @methods; $ok = !@missing; push @diag, map { " missing method $_" } @missing; if($ok) { push @aliens, $alien; if($^O eq 'MSWin32' && $alien->isa('Alien::MSYS')) { unshift @PATH, Alien::MSYS::msys_path(); } else { unshift @PATH, $alien->bin_dir; } } if($alien->can('alien_helper')) { my($intr) = _interpolator(); my $help = eval { $alien->alien_helper }; if(my $error = $@) { $ok = 0; push @diag, " error getting helpers: $error"; } foreach my $name (keys %$help) { my $code = $help->{$name}; $intr->replace_helper($name, $code); } } } else { $ok = 0; push @diag, " undefined alien"; } my $ctx = context(); $ctx->ok($ok, $message); $ctx->diag($_) for @diag; $ctx->release; $ok; } sub synthetic { my($opt) = @_; $opt ||= {}; my %alien = %$opt; require Test::Alien::Synthetic; bless \%alien, 'Test::Alien::Synthetic', } sub run_ok { my($command, $message) = @_; my(@command) = ref $command ? @$command : (do { my $command = $command; # make a copy # Double the backslashes so that when they are unescaped by shellwords(), # they become a single backslash. This should be fine on Windows since # backslashes are not used to escape metacharacters in cmd.exe. $command =~ s/\\/\\\\/g if $^O eq 'MSWin32'; shellwords $command; }); $message ||= ref $command ? "run @command" : "run $command"; require Test::Alien::Run; my $run = bless { out => '', err => '', exit => 0, sig => 0, cmd => [@command], }, 'Test::Alien::Run'; my $ctx = context(); my $exe = which $command[0]; if(defined $exe) { if(ref $command) { shift @command; $run->{cmd} = [$exe, @command]; } else { $run->{cmd} = [$command]; } my @diag; my $ok = 1; my($exit, $errno); ($run->{out}, $run->{err}, $exit, $errno) = capture { if(ref $command) { system $exe, @command; } else { system $command; } ($?,$!); }; if($exit == -1) { $ok = 0; $run->{fail} = "failed to execute: $errno"; push @diag, " failed to execute: $errno"; } elsif($exit & 127) { $ok = 0; push @diag, " killed with signal: @{[ $exit & 127 ]}"; $run->{sig} = $exit & 127; } else { $run->{exit} = $exit >> 8; } $ctx->ok($ok, $message); $ok ? $ctx->note(" using $exe") : $ctx->diag(" using $exe"); $ctx->diag(@diag) for @diag; } else { $ctx->ok(0, $message); $ctx->diag(" command not found"); $run->{fail} = 'command not found'; } unless(@aliens || $ENV{TEST_ALIEN_ALIENS_MISSING}) { $ctx->diag("run_ok called without any aliens, you may want to call alien_ok"); } $ctx->release; $run; } sub _flags { my($class, $method) = @_; my $static = "${method}_static"; $class->can($static) && $class->can('install_type') && $class->install_type eq 'share' && (!$class->can('xs_load')) ? $class->$static : $class->$method; } sub xs_ok { my $cb; $cb = pop if defined $_[-1] && ref $_[-1] eq 'CODE'; my($xs, $message) = @_; $message ||= 'xs'; $xs = { xs => $xs } unless ref $xs; # make sure this is a copy because we may # modify it. $xs->{xs} = "@{[ $xs->{xs} ]}"; $xs->{pxs} ||= {}; $xs->{cbuilder_check} ||= 'have_compiler'; $xs->{cbuilder_config} ||= {}; $xs->{cbuilder_compile} ||= {}; $xs->{cbuilder_link} ||= {}; require ExtUtils::CBuilder; my $skip = do { my $have_compiler = $xs->{cbuilder_check}; my %config = %{ $xs->{cbuilder_config} }; !ExtUtils::CBuilder->new( config => \%config )->$have_compiler; }; if($skip) { my $ctx = context(); $ctx->skip($message, 'test requires a compiler'); $ctx->skip("$message subtest", 'test requires a compiler') if $cb; $ctx->release; return; } if($xs->{cpp} || $xs->{'C++'}) { my $ctx = context(); $ctx->bail("The cpp and C++ options have been removed from xs_ok"); } else { $xs->{c_ext} ||= 'c'; } my $verbose = $xs->{verbose} || 0; my $ok = 1; my @diag; my $dir = Alien::Build::Temp->newdir( TEMPLATE => 'test-alien-XXXXXX', CLEANUP => $^O =~ /^(MSWin32|cygwin|msys)$/ ? 0 : 1, ); my $xs_filename = path($dir)->child('test.xs')->stringify; my $c_filename = path($dir)->child("test.@{[ $xs->{c_ext} ]}")->stringify; my $ctx = context(); my $module; if($ENV{TEST_ALIEN_ALWAYS_KEEP}) { $dir->unlink_on_destroy(0); $ctx->note("keeping XS temporary directory $dir at user request"); } if($xs->{xs} =~ /\bTA_MODULE\b/) { our $count; $count = 0 unless defined $count; my $name = sprintf "Test::Alien::XS::Mod%s%s", $count, chr(65 + $count % 26 ) x 4; $count++; my $code = $xs->{xs}; $code =~ s{\bTA_MODULE\b}{$name}g; $xs->{xs} = $code; } # this regex copied shamefully from ExtUtils::ParseXS # in part because we need the module name to do the bootstrap # and also because if this regex doesn't match then ParseXS # does an exit() which we don't want. if($xs->{xs} =~ /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/m) { $module = $1; $ctx->note("detect module name $module") if $verbose; } else { $ok = 0; push @diag, ' XS does not have a module decleration that we could find'; } if($ok) { open my $fh, '>', $xs_filename; print $fh $xs->{xs}; close $fh; require ExtUtils::ParseXS; my $pxs = ExtUtils::ParseXS->new; my($out, $err) = capture_merged { eval { $pxs->process_file( filename => $xs_filename, output => $c_filename, versioncheck => 0, prototypes => 0, %{ $xs->{pxs} }, ); }; $@; }; $ctx->note("parse xs $xs_filename => $c_filename") if $verbose; $ctx->note($out) if $verbose; $ctx->note("error: $err") if $verbose && $err; unless($pxs->report_error_count == 0) { $ok = 0; push @diag, ' ExtUtils::ParseXS failed:'; push @diag, " $err" if $err; push @diag, " $_" for split /\r?\n/, $out; } } push @diag, "xs_ok called without any aliens, you may want to call alien_ok" unless @aliens || $ENV{TEST_ALIEN_ALIENS_MISSING}; if($ok) { my $cb = ExtUtils::CBuilder->new( config => do { my %config = %{ $xs->{cbuilder_config} }; my $lddlflags = join(' ', grep !/^-l/, shellwords map { _flags $_, 'libs' } @aliens) . " $Config{lddlflags}"; $config{lddlflags} = defined $config{lddlflags} ? "$lddlflags $config{lddlflags}" : $lddlflags; \%config; }, ); my %compile_options = ( source => $c_filename, %{ $xs->{cbuilder_compile} }, ); if(defined $compile_options{extra_compiler_flags} && ref($compile_options{extra_compiler_flags}) eq '') { $compile_options{extra_compiler_flags} = [ shellwords $compile_options{extra_compiler_flags} ]; } push @{ $compile_options{extra_compiler_flags} }, shellwords map { _flags $_, 'cflags' } @aliens; my($out, $obj, $err) = capture_merged { my $obj = eval { $cb->compile(%compile_options); }; ($obj, $@); }; $ctx->note("compile $c_filename") if $verbose; $ctx->note($out) if $verbose; $ctx->note($err) if $verbose && $err; if($verbose > 1) { $ctx->note(_dump({ compile_options => \%compile_options })); } unless($obj) { $ok = 0; push @diag, ' ExtUtils::CBuilder->compile failed'; push @diag, " $err" if $err; push @diag, " $_" for split /\r?\n/, $out; } if($ok) { my %link_options = ( objects => [$obj], module_name => $module, %{ $xs->{cbuilder_link} }, ); if(defined $link_options{extra_linker_flags} && ref($link_options{extra_linker_flags}) eq '') { $link_options{extra_linker_flags} = [ shellwords $link_options{extra_linker_flags} ]; } unshift @{ $link_options{extra_linker_flags} }, grep /^-l/, shellwords map { _flags $_, 'libs' } @aliens; my($out, $lib, $err) = capture_merged { my $lib = eval { $cb->link(%link_options); }; ($lib, $@); }; $ctx->note("link $obj") if $verbose; $ctx->note($out) if $verbose; $ctx->note($err) if $verbose && $err; if($verbose > 1) { $ctx->note(_dump({ link_options => \%link_options })); } if($lib && -f $lib) { $ctx->note("created lib $lib") if $xs->{verbose}; } else { $ok = 0; push @diag, ' ExtUtils::CBuilder->link failed'; push @diag, " $err" if $err; push @diag, " $_" for split /\r?\n/, $out; } if($ok) { my @modparts = split(/::/,$module); my $dl_dlext = $Config{dlext}; my $modfname = $modparts[-1]; my $libpath = path($dir)->child('auto', @modparts, "$modfname.$dl_dlext"); $libpath->parent->mkpath; move($lib, "$libpath") || die "unable to copy $lib => $libpath $!"; pop @modparts; my $pmpath = path($dir)->child(@modparts, "$modfname.pm"); $pmpath->parent->mkpath; open my $fh, '>', "$pmpath"; my($alien_with_xs_load, @rest) = grep { $_->can('xs_load') } @aliens; if($alien_with_xs_load) { { no strict 'refs'; @{join '::', $module, 'rest'} = @rest; ${join '::', $module, 'alien_with_xs_load'} = $alien_with_xs_load; } print $fh '# line '. __LINE__ . ' "' . __FILE__ . qq("\n) . qq{ package $module; use strict; use warnings; our \$VERSION = '0.01'; our \@rest; our \$alien_with_xs_load; \$alien_with_xs_load->xs_load('$module', \$VERSION, \@rest); 1; }; } else { print $fh '# line '. __LINE__ . ' "' . __FILE__ . qq("\n) . qq{ package $module; use strict; use warnings; require XSLoader; our \$VERSION = '0.01'; XSLoader::load('$module',\$VERSION); 1; }; } close $fh; { local @INC = @INC; unshift @INC, "$dir"; ## no critic eval '# line '. __LINE__ . ' "' . __FILE__ . qq("\n) . qq{ use $module; }; ## use critic } if(my $error = $@) { $ok = 0; push @diag, ' XSLoader failed'; push @diag, " $error"; } } } } $ctx->ok($ok, $message); $ctx->diag($_) for @diag; $ctx->release; unless($ok || defined $ENV{TEST_ALIEN_ALWAYS_KEEP}) { $ctx->note("keeping XS temporary directory $dir due to failure"); $dir->unlink_on_destroy(0); } if($cb) { $cb = sub { my $ctx = context(); $ctx->plan(0, 'SKIP', "subtest requires xs success"); $ctx->release; } unless $ok; @_ = ("$message subtest", $cb, 1, $module); goto \&Test2::API::run_subtest; } $ok; } sub with_subtest (&) { my($code) = @_; # it may be possible to catch a segmentation fault, # but not with signal handlers apparently. See: # https://feepingcreature.github.io/handling.html return $code if $^O eq 'MSWin32'; # try to catch a segmentation fault and bail out # with a useful diagnostic. prove test to swallow # the diagnostic on such failures. sub { local $SIG{SEGV} = sub { my $ctx = context(); $ctx->bail("Segmentation fault"); }; $code->(@_); } } sub ffi_ok { my $cb; $cb = pop if defined $_[-1] && ref $_[-1] eq 'CODE'; my($opt, $message) = @_; $message ||= 'ffi'; my $ok = 1; my $skip; my $ffi; my @diag; { my $min = '0.12'; # the first CPAN release $min = '0.15' if $opt->{ignore_not_found}; $min = '0.18' if $opt->{lang}; $min = '0.99' if defined $opt->{api} && $opt->{api} > 0; unless(eval { require FFI::Platypus; FFI::Platypus->VERSION($min) }) { $ok = 0; $skip = "Test requires FFI::Platypus $min"; } } if($ok && $opt->{lang}) { my $class = "FFI::Platypus::Lang::@{[ $opt->{lang} ]}"; { my $pm = "$class.pm"; $pm =~ s/::/\//g; eval { require $pm }; } if($@) { $ok = 0; $skip = "Test requires FFI::Platypus::Lang::@{[ $opt->{lang} ]}"; } } unless(@aliens || $ENV{TEST_ALIEN_ALIENS_MISSING}) { push @diag, 'ffi_ok called without any aliens, you may want to call alien_ok'; } if($ok) { $ffi = FFI::Platypus->new( do { my @args = ( lib => [map { $_->dynamic_libs } @aliens], ignore_not_found => $opt->{ignore_not_found}, lang => $opt->{lang}, ); push @args, api => $opt->{api} if defined $opt->{api}; @args; } ); foreach my $symbol (@{ $opt->{symbols} || [] }) { unless($ffi->find_symbol($symbol)) { $ok = 0; push @diag, " $symbol not found" } } } my $ctx = context(); if($skip) { $ctx->skip($message, $skip); } else { $ctx->ok($ok, $message); } $ctx->diag($_) for @diag; $ctx->release; if($cb) { $cb = sub { my $ctx = context(); $ctx->plan(0, 'SKIP', "subtest requires ffi success"); $ctx->release; } unless $ok; @_ = ("$message subtest", $cb, 1, $ffi); goto \&Test2::API::run_subtest; } $ok; } { my @ret; sub _interpolator { return @ret if @ret; require Alien::Build::Interpolate::Default; my $intr = Alien::Build::Interpolate::Default->new; require Alien::Build; my $build = Alien::Build->new; $build->meta->interpolator($intr); @ret = ($intr, $build); } } sub helper_ok { my($name, $message) = @_; $message ||= "helper $name exists"; my($intr) = _interpolator; my $code = $intr->has_helper($name); my $ok = defined $code; my $ctx = context(); $ctx->ok($ok, $message); $ctx->diag("helper_ok called without any aliens, you may want to call alien_ok") unless @aliens || $ENV{TEST_ALIEN_ALIENS_MISSING}; $ctx->release; $ok; } sub plugin_ok { my($name, $message) = @_; my @args; ($name, @args) = @$name if ref $name; $message ||= "plugin $name"; my($intr, $build) = _interpolator; my $class = "Alien::Build::Plugin::$name"; my $pm = "$class.pm"; $pm =~ s/::/\//g; my $ctx = context(); my $plugin = eval { require $pm unless $class->can('new'); $class->new(@args); }; if(my $error = $@) { $ctx->ok(0, $message, ['unable to create $name plugin', $error]); $ctx->release; return 0; } eval { $plugin->init($build->meta); }; if($^O eq 'MSWin32' && ($plugin->isa('Alien::Build::Plugin::Build::MSYS') || $plugin->isa('Alien::Build::Plugin::Build::Autoconf'))) { require Alien::MSYS; unshift @PATH, Alien::MSYS::msys_path(); } if(my $error = $@) { $ctx->ok(0, $message, ['unable to initiate $name plugin', $error]); $ctx->release; return 0; } else { $ctx->ok(1, $message); $ctx->release; return 1; } } sub interpolate_template_is { my($template, $pattern, $message) = @_; $message ||= "template matches"; my($intr) = _interpolator; my $value = eval { $intr->interpolate($template) }; my $error = $@; my @diag; my $ok; if($error) { $ok = 0; push @diag, "error in evaluation:"; push @diag, " $error"; } elsif(ref($pattern) eq 'Regexp') { $ok = $value =~ $pattern; push @diag, "value '$value' does not match $pattern'" unless $ok; } else { $ok = $value eq "$pattern"; push @diag, "value '$value' does not equal '$pattern'" unless $ok; } my $ctx = context(); $ctx->ok($ok, $message, [@diag]); $ctx->diag('interpolate_template_is called without any aliens, you may want to call alien_ok') unless @aliens || $ENV{TEST_ALIEN_ALIENS_MISSING}; $ctx->release; $ok; } sub interpolate_run_ok { my($template, $message) = @_; my(@template) = ref $template ? @$template : ($template); my($intr) = _interpolator; my $ok = 1; my @diag; my @command; foreach my $template (@template) { my $command = eval { $intr->interpolate($template) }; if(my $error = $@) { $ok = 0; push @diag, "error in evaluation:"; push @diag, " $error"; } else { push @command, $command; } } my $ctx = context(); if($ok) { my $command = ref $template ? \@command : $command[0]; $ok = run_ok($command, $message); } else { $message ||= "run @template"; $ctx->ok($ok, $message, [@diag]); $ctx->diag('interpolate_run_ok called without any aliens, you may want to call alien_ok') unless @aliens || $ENV{TEST_ALIEN_ALIENS_MISSING}; } $ctx->release; $ok; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien - Testing tools for Alien modules =head1 VERSION version 2.83 =head1 SYNOPSIS Test commands that come with your Alien: use Test2::V0; use Test::Alien; use Alien::patch; alien_ok 'Alien::patch'; run_ok([ 'patch', '--version' ]) ->success # we only accept the version written # by Larry ... ->out_like(qr{Larry Wall}); done_testing; Test that your library works with C: use Test2::V0; use Test::Alien; use Alien::Editline; alien_ok 'Alien::Editline'; my $xs = do { local $/; }; xs_ok $xs, with_subtest { my($module) = @_; ok $module->version; }; done_testing; __DATA__ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include const char * version(const char *class) { return rl_library_version; } MODULE = TA_MODULE PACKAGE = TA_MODULE const char *version(class); const char *class; Test that your library works with L: use Test2::V0; use Test::Alien; use Alien::LibYAML; alien_ok 'Alien::LibYAML'; ffi_ok { symbols => ['yaml_get_version'] }, with_subtest { my($ffi) = @_; my $get_version = $ffi->function(yaml_get_version => ['int*','int*','int*'] => 'void'); $get_version->call(\my $major, \my $minor, \my $patch); like $major, qr{[0-9]+}; like $minor, qr{[0-9]+}; like $patch, qr{[0-9]+}; }; done_testing; =head1 DESCRIPTION This module provides tools for testing L modules. It has hooks to work easily with L based modules, but can also be used via the synthetic interface to test non L based L modules. It has very modest prerequisites. Prior to this module the best way to test a L module was via L. The main downside to that module is that it is heavily influenced by and uses L, which is a tool for checking at install time various things about your compiler. It was also written before L became as stable as it is today. In particular, L does its testing by creating an executable and running it. Unfortunately Perl uses extensions by creating dynamic libraries and linking them into the Perl process, which is different in subtle and error prone ways. This module attempts to test the libraries in the way that they will actually be used, via either C or L. It also provides a mechanism for testing binaries that are provided by the various L modules (for example L and L). L modules can actually be useable without a compiler, or without L (for example, if the library is provided by the system, and you are using L, or if you are building from source and you are using C), so tests with missing prerequisites are automatically skipped. For example, L will automatically skip itself if a compiler is not found, and L will automatically skip itself if L is not installed. =head1 FUNCTIONS =head2 alien_ok alien_ok $alien, $message; alien_ok $alien; Load the given L instance or class. Checks that the instance or class conforms to the same interface as L. Will be used by subsequent tests. The C<$alien> module only needs to provide these methods in order to conform to the L interface: =over 4 =item cflags String containing the compiler flags =item libs String containing the linker and library flags =item dynamic_libs List of dynamic libraries. Returns empty list if the L module does not provide this. =item bin_dir Directory containing tool binaries. Returns empty list if the L module does not provide this. =back If your L module does not conform to this interface then you can create a synthetic L module using the L function. =head2 synthetic my $alien = synthetic \%config; Create a synthetic L module which can be passed into L. C<\%config> can contain these keys (all of which are optional): =over 4 =item cflags String containing the compiler flags. =item cflags_static String containing the static compiler flags (optional). =item libs String containing the linker and library flags. =item libs_static String containing the static linker flags (optional). =item dynamic_libs List reference containing the dynamic libraries. =item bin_dir Tool binary directory. =item runtime_prop Runtime properties. =back See L for more details. =head2 run_ok my $run = run_ok $command; my $run = run_ok $command, $message; Runs the given command, falling back on any C methods provided by L modules specified with L. C<$command> can be either a string or an array reference. Only fails if the command cannot be found, or if it is killed by a signal! Returns a L object, which you can use to test the exit status, output and standard error. Always returns an instance of L, even if the command could not be found. =head2 xs_ok xs_ok $xs; xs_ok $xs, $message; Compiles, links the given C code and attaches to Perl. If you use the special module name C in your C code, it will be replaced by an automatically generated package name. This can be useful if you want to pass the same C code to multiple calls to C without subsequent calls replacing previous ones. C<$xs> may be either a string containing the C code, or a hash reference with these keys: =over 4 =item xs The XS code. This is the only required element. =item pxs Extra L arguments passed in as a hash reference. =item cbuilder_check The compile check that should be done prior to attempting to build. Should be one of C or C. Defaults to C. =item cbuilder_config Hash to override values normally provided by C. =item cbuilder_compile Extra The L arguments passed in as a hash reference. =item cbuilder_link Extra The L arguments passed in as a hash reference. =item verbose Spew copious debug information via test note. =back You can use the C keyword to conditionally run a subtest if the C call succeeds. If C does not work, then the subtest will automatically be skipped. Example: xs_ok $xs, with_subtest { # skipped if $xs fails for some reason my($module) = @_; is $module->foo, 1; }; The module name detected during the XS parsing phase will be passed in to the subtest. This is helpful when you are using a generated module name. If you need to test XS C++ interfaces, see L. Caveats: C uses L, which may call C under certain error conditions. While this is not really good thing to happen in the middle of a test, it usually indicates a real failure condition, and it should return a failure condition so the test should still fail overall. [version 2.53] As of version 2.53, C will only remove temporary generated files if the test is successful by default. You can force either always or never removing the temporary generated files using the C environment variable (see L below). =head2 ffi_ok ffi_ok; ffi_ok \%opt; ffi_ok \%opt, $message; Test that L works. C<\%opt> is a hash reference with these keys (all optional): =over 4 =item symbols List references of symbols that must be found for the test to succeed. =item ignore_not_found Ignores symbols that aren't found. This affects functions accessed via L and L methods, and does not influence the C key above. =item lang Set the language. Used primarily for language specific native types. =item api Set the API. C requires FFI::Platypus 0.99 or later. This option was added with Test::Alien version 1.90, so your use line should include this version as a safeguard to make sure it works: use Test::Alien 1.90; ... ffi_ok ...; =back As with L above, you can use the C keyword to specify a subtest to be run if C succeeds (it will skip otherwise). The L instance is passed into the subtest as the first argument. For example: ffi_ok with_subtest { my($ffi) = @_; is $ffi->function(foo => [] => 'void')->call, 42; }; =head2 helper_ok helper_ok $name; helper_ok $name, $message; Tests that the given helper has been defined. =head2 plugin_ok [version 2.52] plugin_ok $plugin_name, $message; plugin_ok [$plugin_name, @args], $message; This applies an L to the interpolator used by L, L and L so that you can test with any helpers that plugin provides. Useful, for example for getting C<%{configure}> from L. =head2 interpolate_template_is interpolate_template_is $template, $string; interpolate_template_is $template, $string, $message; interpolate_template_is $template, $regex; interpolate_template_is $template, $regex, $message; Tests that the given template when evaluated with the appropriate helpers will match either the given string or regular expression. =head2 interpolate_run_ok [version 2.52] my $run = interpolate_run_ok $command; my $run = interpolate_run_ok $command, $message; This is the same as L except it runs the command through the interpolator first. =head1 ENVIRONMENT =over 4 =item C If this is defined then it will override the built in logic that decides if the temporary files generated by L should be kept when the test file terminates. If set to true the generated files will always be kept. If set to false, then they will always be removed. =item C By default, this module will warn you if some tools are used without first invoking L. This is usually a mistake, but if you really do want to use one of these tools with no aliens loaded, you can set this environment variable to false. =back =head1 SEE ALSO =over 4 =item L =item L =item L =item L =item L =item L =item L =item L =item L =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!/p5«’K’Kperl5/Test/Tutorial.podnuÏÃ6Ç$=head1 NAME Test::Tutorial - A tutorial about writing really basic tests =head1 DESCRIPTION I I<*sob*> I Is this you? Is writing tests right up there with writing documentation and having your fingernails pulled out? Did you open up a test and read ######## We start with some black magic and decide that's quite enough for you? It's ok. That's all gone now. We've done all the black magic for you. And here are the tricks... =head2 Nuts and bolts of testing. Here's the most basic test program. #!/usr/bin/perl -w print "1..1\n"; print 1 + 1 == 2 ? "ok 1\n" : "not ok 1\n"; Because 1 + 1 is 2, it prints: 1..1 ok 1 What this says is: C<1..1> "I'm going to run one test." [1] C "The first test passed". And that's about all magic there is to testing. Your basic unit of testing is the I. For each thing you test, an C is printed. Simple. L interprets your test results to determine if you succeeded or failed (more on that later). Writing all these print statements rapidly gets tedious. Fortunately, there's L. It has one function, C. #!/usr/bin/perl -w use Test::Simple tests => 1; ok( 1 + 1 == 2 ); That does the same thing as the previous code. C is the backbone of Perl testing, and we'll be using it instead of roll-your-own from here on. If C gets a true value, the test passes. False, it fails. #!/usr/bin/perl -w use Test::Simple tests => 2; ok( 1 + 1 == 2 ); ok( 2 + 2 == 5 ); From that comes: 1..2 ok 1 not ok 2 # Failed test (test.pl at line 5) # Looks like you failed 1 tests of 2. C<1..2> "I'm going to run two tests." This number is a I. It helps to ensure your test program ran all the way through and didn't die or skip some tests. C "The first test passed." C "The second test failed". Test::Simple helpfully prints out some extra commentary about your tests. It's not scary. Come, hold my hand. We're going to give an example of testing a module. For our example, we'll be testing a date library, L. It's on CPAN, so download a copy and follow along. [2] =head2 Where to start? This is the hardest part of testing, where do you start? People often get overwhelmed at the apparent enormity of the task of testing a whole module. The best place to start is at the beginning. L is an object-oriented module, and that means you start by making an object. Test C. #!/usr/bin/perl -w # assume these two lines are in all subsequent examples use strict; use warnings; use Test::Simple tests => 2; use Date::ICal; my $ical = Date::ICal->new; # create an object ok( defined $ical ); # check that we got something ok( $ical->isa('Date::ICal') ); # and it's the right class Run that and you should get: 1..2 ok 1 ok 2 Congratulations! You've written your first useful test. =head2 Names That output isn't terribly descriptive, is it? When you have two tests you can figure out which one is #2, but what if you have 102 tests? Each test can be given a little descriptive name as the second argument to C. use Test::Simple tests => 2; ok( defined $ical, 'new() returned something' ); ok( $ical->isa('Date::ICal'), " and it's the right class" ); Now you'll see: 1..2 ok 1 - new() returned something ok 2 - and it's the right class =head2 Test the manual The simplest way to build up a decent testing suite is to just test what the manual says it does. [3] Let's pull something out of the L and test that all its bits work. #!/usr/bin/perl -w use Test::Simple tests => 8; use Date::ICal; $ical = Date::ICal->new( year => 1964, month => 10, day => 16, hour => 16, min => 12, sec => 47, tz => '0530' ); ok( defined $ical, 'new() returned something' ); ok( $ical->isa('Date::ICal'), " and it's the right class" ); ok( $ical->sec == 47, ' sec()' ); ok( $ical->min == 12, ' min()' ); ok( $ical->hour == 16, ' hour()' ); ok( $ical->day == 17, ' day()' ); ok( $ical->month == 10, ' month()' ); ok( $ical->year == 1964, ' year()' ); Run that and you get: 1..8 ok 1 - new() returned something ok 2 - and it's the right class ok 3 - sec() ok 4 - min() ok 5 - hour() not ok 6 - day() # Failed test (- at line 16) ok 7 - month() ok 8 - year() # Looks like you failed 1 tests of 8. Whoops, a failure! [4] L helpfully lets us know on what line the failure occurred, but not much else. We were supposed to get 17, but we didn't. What did we get?? Dunno. You could re-run the test in the debugger or throw in some print statements to find out. Instead, switch from L to L. L does everything L does, and more! In fact, L does things I the way L does. You can literally swap L out and put L in its place. That's just what we're going to do. L does more than L. The most important difference at this point is it provides more informative ways to say "ok". Although you can write almost any test with a generic C, it can't tell you what went wrong. The C function lets us declare that something is supposed to be the same as something else: use Test::More tests => 8; use Date::ICal; $ical = Date::ICal->new( year => 1964, month => 10, day => 16, hour => 16, min => 12, sec => 47, tz => '0530' ); ok( defined $ical, 'new() returned something' ); ok( $ical->isa('Date::ICal'), " and it's the right class" ); is( $ical->sec, 47, ' sec()' ); is( $ical->min, 12, ' min()' ); is( $ical->hour, 16, ' hour()' ); is( $ical->day, 17, ' day()' ); is( $ical->month, 10, ' month()' ); is( $ical->year, 1964, ' year()' ); "Is C<< $ical->sec >> 47?" "Is C<< $ical->min >> 12?" With C in place, you get more information: 1..8 ok 1 - new() returned something ok 2 - and it's the right class ok 3 - sec() ok 4 - min() ok 5 - hour() not ok 6 - day() # Failed test (- at line 16) # got: '16' # expected: '17' ok 7 - month() ok 8 - year() # Looks like you failed 1 tests of 8. Aha. C<< $ical->day >> returned 16, but we expected 17. A quick check shows that the code is working fine, we made a mistake when writing the tests. Change it to: is( $ical->day, 16, ' day()' ); ... and everything works. Any time you're doing a "this equals that" sort of test, use C. It even works on arrays. The test is always in scalar context, so you can test how many elements are in an array this way. [5] is( @foo, 5, 'foo has 5 elements' ); =head2 Sometimes the tests are wrong This brings up a very important lesson. Code has bugs. Tests are code. Ergo, tests have bugs. A failing test could mean a bug in the code, but don't discount the possibility that the test is wrong. On the flip side, don't be tempted to prematurely declare a test incorrect just because you're having trouble finding the bug. Invalidating a test isn't something to be taken lightly, and don't use it as a cop out to avoid work. =head2 Testing lots of values We're going to be wanting to test a lot of dates here, trying to trick the code with lots of different edge cases. Does it work before 1970? After 2038? Before 1904? Do years after 10,000 give it trouble? Does it get leap years right? We could keep repeating the code above, or we could set up a little try/expect loop. use Test::More tests => 32; use Date::ICal; my %ICal_Dates = ( # An ICal string And the year, month, day # hour, minute and second we expect. '19971024T120000' => # from the docs. [ 1997, 10, 24, 12, 0, 0 ], '20390123T232832' => # after the Unix epoch [ 2039, 1, 23, 23, 28, 32 ], '19671225T000000' => # before the Unix epoch [ 1967, 12, 25, 0, 0, 0 ], '18990505T232323' => # before the MacOS epoch [ 1899, 5, 5, 23, 23, 23 ], ); while( my($ical_str, $expect) = each %ICal_Dates ) { my $ical = Date::ICal->new( ical => $ical_str ); ok( defined $ical, "new(ical => '$ical_str')" ); ok( $ical->isa('Date::ICal'), " and it's the right class" ); is( $ical->year, $expect->[0], ' year()' ); is( $ical->month, $expect->[1], ' month()' ); is( $ical->day, $expect->[2], ' day()' ); is( $ical->hour, $expect->[3], ' hour()' ); is( $ical->min, $expect->[4], ' min()' ); is( $ical->sec, $expect->[5], ' sec()' ); } Now we can test bunches of dates by just adding them to C<%ICal_Dates>. Now that it's less work to test with more dates, you'll be inclined to just throw more in as you think of them. Only problem is, every time we add to that we have to keep adjusting the C<< use Test::More tests => ## >> line. That can rapidly get annoying. There are ways to make this work better. First, we can calculate the plan dynamically using the C function. use Test::More; use Date::ICal; my %ICal_Dates = ( ...same as before... ); # For each key in the hash we're running 8 tests. plan tests => keys(%ICal_Dates) * 8; ...and then your tests... To be even more flexible, use C. This means we're just running some tests, don't know how many. [6] use Test::More; # instead of tests => 32 ... # tests here done_testing(); # reached the end safely If you don't specify a plan, L expects to see C before your program exits. It will warn you if you forget it. You can give C an optional number of tests you expected to run, and if the number ran differs, L will give you another kind of warning. =head2 Informative names Take a look at the line: ok( defined $ical, "new(ical => '$ical_str')" ); We've added more detail about what we're testing and the ICal string itself we're trying out to the name. So you get results like: ok 25 - new(ical => '19971024T120000') ok 26 - and it's the right class ok 27 - year() ok 28 - month() ok 29 - day() ok 30 - hour() ok 31 - min() ok 32 - sec() If something in there fails, you'll know which one it was and that will make tracking down the problem easier. Try to put a bit of debugging information into the test names. Describe what the tests test, to make debugging a failed test easier for you or for the next person who runs your test. =head2 Skipping tests Poking around in the existing L tests, I found this in F [7] #!/usr/bin/perl -w use Test::More tests => 7; use Date::ICal; # Make sure epoch time is being handled sanely. my $t1 = Date::ICal->new( epoch => 0 ); is( $t1->epoch, 0, "Epoch time of 0" ); # XXX This will only work on unix systems. is( $t1->ical, '19700101Z', " epoch to ical" ); is( $t1->year, 1970, " year()" ); is( $t1->month, 1, " month()" ); is( $t1->day, 1, " day()" ); # like the tests above, but starting with ical instead of epoch my $t2 = Date::ICal->new( ical => '19700101Z' ); is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" ); is( $t2->epoch, 0, " and back to ICal" ); The beginning of the epoch is different on most non-Unix operating systems [8]. Even though Perl smooths out the differences for the most part, certain ports do it differently. MacPerl is one off the top of my head. [9] Rather than putting a comment in the test and hoping someone will read the test while debugging the failure, we can explicitly say it's never going to work and skip the test. use Test::More tests => 7; use Date::ICal; # Make sure epoch time is being handled sanely. my $t1 = Date::ICal->new( epoch => 0 ); is( $t1->epoch, 0, "Epoch time of 0" ); SKIP: { skip('epoch to ICal not working on Mac OS', 6) if $^O eq 'MacOS'; is( $t1->ical, '19700101Z', " epoch to ical" ); is( $t1->year, 1970, " year()" ); is( $t1->month, 1, " month()" ); is( $t1->day, 1, " day()" ); # like the tests above, but starting with ical instead of epoch my $t2 = Date::ICal->new( ical => '19700101Z' ); is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" ); is( $t2->epoch, 0, " and back to ICal" ); } A little bit of magic happens here. When running on anything but MacOS, all the tests run normally. But when on MacOS, C causes the entire contents of the SKIP block to be jumped over. It never runs. Instead, C prints special output that tells L that the tests have been skipped. 1..7 ok 1 - Epoch time of 0 ok 2 # skip epoch to ICal not working on MacOS ok 3 # skip epoch to ICal not working on MacOS ok 4 # skip epoch to ICal not working on MacOS ok 5 # skip epoch to ICal not working on MacOS ok 6 # skip epoch to ICal not working on MacOS ok 7 # skip epoch to ICal not working on MacOS This means your tests won't fail on MacOS. This means fewer emails from MacPerl users telling you about failing tests that you know will never work. You've got to be careful with skip tests. These are for tests which don't work and I. It is not for skipping genuine bugs (we'll get to that in a moment). The tests are wholly and completely skipped. [10] This will work. SKIP: { skip("I don't wanna die!"); die, die, die, die, die; } =head2 Todo tests While thumbing through the L man page, I came across this: ical $ical_string = $ical->ical; Retrieves, or sets, the date on the object, using any valid ICal date/time string. "Retrieves or sets". Hmmm. I didn't see a test for using C to set the date in the Date::ICal test suite. So I wrote one: use Test::More tests => 1; use Date::ICal; my $ical = Date::ICal->new; $ical->ical('20201231Z'); is( $ical->ical, '20201231Z', 'Setting via ical()' ); Run that. I saw: 1..1 not ok 1 - Setting via ical() # Failed test (- at line 6) # got: '20010814T233649Z' # expected: '20201231Z' # Looks like you failed 1 tests of 1. Whoops! Looks like it's unimplemented. Assume you don't have the time to fix this. [11] Normally, you'd just comment out the test and put a note in a todo list somewhere. Instead, explicitly state "this test will fail" by wrapping it in a C block: use Test::More tests => 1; TODO: { local $TODO = 'ical($ical) not yet implemented'; my $ical = Date::ICal->new; $ical->ical('20201231Z'); is( $ical->ical, '20201231Z', 'Setting via ical()' ); } Now when you run, it's a little different: 1..1 not ok 1 - Setting via ical() # TODO ical($ical) not yet implemented # got: '20010822T201551Z' # expected: '20201231Z' L doesn't say "Looks like you failed 1 tests of 1". That '# TODO' tells L "this is supposed to fail" and it treats a failure as a successful test. You can write tests even before you've fixed the underlying code. If a TODO test passes, L will report it "UNEXPECTEDLY SUCCEEDED". When that happens, remove the TODO block with C and turn it into a real test. =head2 Testing with taint mode. Taint mode is a funny thing. It's the globalest of all global features. Once you turn it on, it affects I code in your program and I modules used (and all the modules they use). If a single piece of code isn't taint clean, the whole thing explodes. With that in mind, it's very important to ensure your module works under taint mode. It's very simple to have your tests run under taint mode. Just throw a C<-T> into the C<#!> line. L will read the switches in C<#!> and use them to run your tests. #!/usr/bin/perl -Tw ...test normally here... When you say C it will run with taint mode on. =head1 FOOTNOTES =over 4 =item 1 The first number doesn't really mean anything, but it has to be 1. It's the second number that's important. =item 2 For those following along at home, I'm using version 1.31. It has some bugs, which is good -- we'll uncover them with our tests. =item 3 You can actually take this one step further and test the manual itself. Have a look at L (formerly L). =item 4 Yes, there's a mistake in the test suite. What! Me, contrived? =item 5 We'll get to testing the contents of lists later. =item 6 But what happens if your test program dies halfway through?! Since we didn't say how many tests we're going to run, how can we know it failed? No problem, L employs some magic to catch that death and turn the test into a failure, even if every test passed up to that point. =item 7 I cleaned it up a little. =item 8 Most Operating Systems record time as the number of seconds since a certain date. This date is the beginning of the epoch. Unix's starts at midnight January 1st, 1970 GMT. =item 9 MacOS's epoch is midnight January 1st, 1904. VMS's is midnight, November 17th, 1858, but vmsperl emulates the Unix epoch so it's not a problem. =item 10 As long as the code inside the SKIP block at least compiles. Please don't ask how. No, it's not a filter. =item 11 Do NOT be tempted to use TODO tests as a way to avoid fixing simple bugs! =back =head1 AUTHORS Michael G Schwern Eschwern@pobox.comE and the perl-qa dancers! =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2001 by Michael G Schwern Eschwern@pobox.comE. This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in these files are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. =cut PK!vB~Óööperl5/Test/Pod.pmnuÏÃ6Ç$package Test::Pod; use strict; use warnings; =head1 NAME Test::Pod - check for POD errors in files =head1 VERSION Version 1.52 =cut our $VERSION = '1.52'; =head1 SYNOPSIS C lets you check the validity of a POD file, and report its results in standard C fashion. use Test::Pod tests => $num_tests; pod_file_ok( $file, "Valid POD file" ); Module authors can include the following in a F file and have C automatically find and check all POD files in a module distribution: use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); You can also specify a list of files to check, using the C function supplied: use strict; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; my @poddirs = qw( blib script ); all_pod_files_ok( all_pod_files( @poddirs ) ); Or even (if you're running under L): use strict; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; my @poddirs = qw( blib script ); use File::Spec::Functions qw( catdir updir ); all_pod_files_ok( all_pod_files( map { catdir updir, $_ } @poddirs ) ); =head1 DESCRIPTION Check POD files for errors or warnings in a test file, using C to do the heavy lifting. =cut use Test::Builder; use Pod::Simple; our %ignore_dirs = ( '.bzr' => 'Bazaar', '.git' => 'Git', '.hg' => 'Mercurial', '.pc' => 'quilt', '.svn' => 'Subversion', CVS => 'CVS', RCS => 'RCS', SCCS => 'SCCS', _darcs => 'darcs', _sgbak => 'Vault/Fortress', ); my $Test = Test::Builder->new; sub import { my $self = shift; my $caller = caller; for my $func ( qw( pod_file_ok all_pod_files all_pod_files_ok ) ) { no strict 'refs'; *{$caller."::".$func} = \&$func; } $Test->exported_to($caller); $Test->plan(@_); } sub _additional_test_pod_specific_checks { my ($ok, $errata, $file) = @_; return $ok; } =head1 FUNCTIONS =head2 pod_file_ok( FILENAME[, TESTNAME ] ) C will okay the test if the POD parses correctly. Certain conditions are not reported yet, such as a file with no pod in it at all. When it fails, C will show any pod checking errors as diagnostics. The optional second argument TESTNAME is the name of the test. If it is omitted, C chooses a default test name "POD test for FILENAME". =cut sub pod_file_ok { my $file = shift; my $name = @_ ? shift : "POD test for $file"; if ( !-f $file ) { $Test->ok( 0, $name ); $Test->diag( "$file does not exist" ); return; } my $checker = Pod::Simple->new; $checker->output_string( \my $trash ); # Ignore any output $checker->parse_file( $file ); my $ok = !$checker->any_errata_seen; $ok = _additional_test_pod_specific_checks( $ok, ($checker->{errata}||={}), $file ); $name .= ' (no pod)' if !$checker->content_seen; $Test->ok( $ok, $name ); if ( !$ok ) { my $lines = $checker->{errata}; for my $line ( sort { $a<=>$b } keys %$lines ) { my $errors = $lines->{$line}; $Test->diag( "$file ($line): $_" ) for @$errors; } } return $ok; } # pod_file_ok =head2 all_pod_files_ok( [@entries] ) Checks all the files under C<@entries> for valid POD. It runs L on directories and assumes everything else to be a file to be tested. It calls the C function for you (one test for each file), so you can't have already called C. If C<@entries> is empty or not passed, the function finds all POD files in files in the F directory if it exists, or the F directory if not. A POD file matches the conditions specified below in L. If you're testing a module, just make a F: use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); Returns true if all pod files are ok, or false if any fail. =cut sub all_pod_files_ok { my @args = @_ ? @_ : _starting_points(); my @files = map { -d $_ ? all_pod_files($_) : $_ } @args; unless (@files) { $Test->skip_all( "No files found in (@args)\n" ); return 1; } $Test->plan( tests => scalar @files ); my $ok = 1; foreach my $file ( @files ) { pod_file_ok( $file ) or undef $ok; } return $ok; } =head2 all_pod_files( [@dirs] ) X Returns a list of all the POD files in I<@dirs> and in directories below. If no directories are passed, it defaults to F if F exists, or else F if not. Skips any files in F, F<.svn>, F<.git> and similar directories. See C<%Test::Pod::ignore_dirs> for a list of them. A POD file is: =over 4 =item * Any file that ends in F<.pl>, F<.PL>, F<.pm>, F<.pod>, F<.psgi> or F<.t>. =item * Any file that has a first line with a shebang and "perl" on it. =item * Any file that ends in F<.bat> and has a first line with "--*-Perl-*--" on it. =back The order of the files returned is machine-dependent. If you want them sorted, you'll have to sort them yourself. =cut sub all_pod_files { my @pod; require File::Find; File::Find::find({ preprocess => sub { grep { !exists $ignore_dirs{$_} || !-d File::Spec->catfile($File::Find::dir, $_) } @_ }, wanted => sub { -f $_ && _is_perl($_) && push @pod, $File::Find::name }, no_chdir => 1, }, @_ ? @_ : _starting_points()); return @pod; } sub _starting_points { return 'blib' if -e 'blib'; return 'lib'; } sub _is_perl { my $file = shift; # accept as a Perl file everything that ends with a well known Perl suffix ... return 1 if $file =~ /[.](?:PL|p(?:[lm]|od|sgi)|t)$/; open my $fh, '<', $file or return; my $first = <$fh>; close $fh; return unless $first; # ... or that has a she-bang as first line ... return 1 if $first =~ /^#!.*perl/; # ... or that is a .bat ad has a Perl comment line first return 1 if $file =~ /[.]bat$/i && $first =~ /--[*]-Perl-[*]--/; return; } =head1 SUPPORT This module is managed in an open L. Feel free to fork and contribute, or to clone L and send patches! Found a bug? Please L or L a report! =head1 AUTHORS =over =item David E. Wheeler Current maintainer. =item Andy Lester C<< >> Maintainer emeritus. =item brian d foy Original author. =back =head1 ACKNOWLEDGEMENTS Thanks brian d foy for the original code, and to these folks for contributions: =over =item * Andy Lester =item * David E. Wheeler =item * Paul Miller =item * Peter Edwards =item * Luca Ferrari =back =head1 COPYRIGHT AND LICENSE Copyright 2006-2010, Andy Lester; 2010-2015 David E. Wheeler. Some Rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK!¨eâò�G�Gperl5/Test/Tester.pmnuÏÃ6Ç$use strict; package Test::Tester; BEGIN { if (*Test::Builder::new{CODE}) { warn "You should load Test::Tester before Test::Builder (or anything that loads Test::Builder)" } } use Test::Builder; use Test::Tester::CaptureRunner; use Test::Tester::Delegate; require Exporter; use vars qw( @ISA @EXPORT ); our $VERSION = '1.302183'; @EXPORT = qw( run_tests check_tests check_test cmp_results show_space ); @ISA = qw( Exporter ); my $Test = Test::Builder->new; my $Capture = Test::Tester::Capture->new; my $Delegator = Test::Tester::Delegate->new; $Delegator->{Object} = $Test; my $runner = Test::Tester::CaptureRunner->new; my $want_space = $ENV{TESTTESTERSPACE}; sub show_space { $want_space = 1; } my $colour = ''; my $reset = ''; if (my $want_colour = $ENV{TESTTESTERCOLOUR} || $ENV{TESTTESTERCOLOR}) { if (eval { require Term::ANSIColor; 1 }) { eval { require Win32::Console::ANSI } if 'MSWin32' eq $^O; # support color on windows platforms my ($f, $b) = split(",", $want_colour); $colour = Term::ANSIColor::color($f).Term::ANSIColor::color("on_$b"); $reset = Term::ANSIColor::color("reset"); } } sub new_new { return $Delegator; } sub capture { return Test::Tester::Capture->new; } sub fh { # experiment with capturing output, I don't like it $runner = Test::Tester::FHRunner->new; return $Test; } sub find_run_tests { my $d = 1; my $found = 0; while ((not $found) and (my ($sub) = (caller($d))[3]) ) { # print "$d: $sub\n"; $found = ($sub eq "Test::Tester::run_tests"); $d++; } # die "Didn't find 'run_tests' in caller stack" unless $found; return $d; } sub run_tests { local($Delegator->{Object}) = $Capture; $runner->run_tests(@_); return ($runner->get_premature, $runner->get_results); } sub check_test { my $test = shift; my $expect = shift; my $name = shift; $name = "" unless defined($name); @_ = ($test, [$expect], $name); goto &check_tests; } sub check_tests { my $test = shift; my $expects = shift; my $name = shift; $name = "" unless defined($name); my ($prem, @results) = eval { run_tests($test, $name) }; $Test->ok(! $@, "Test '$name' completed") || $Test->diag($@); $Test->ok(! length($prem), "Test '$name' no premature diagnostication") || $Test->diag("Before any testing anything, your tests said\n$prem"); local $Test::Builder::Level = $Test::Builder::Level + 1; cmp_results(\@results, $expects, $name); return ($prem, @results); } sub cmp_field { my ($result, $expect, $field, $desc) = @_; if (defined $expect->{$field}) { $Test->is_eq($result->{$field}, $expect->{$field}, "$desc compare $field"); } } sub cmp_result { my ($result, $expect, $name) = @_; my $sub_name = $result->{name}; $sub_name = "" unless defined($name); my $desc = "subtest '$sub_name' of '$name'"; { local $Test::Builder::Level = $Test::Builder::Level + 1; cmp_field($result, $expect, "ok", $desc); cmp_field($result, $expect, "actual_ok", $desc); cmp_field($result, $expect, "type", $desc); cmp_field($result, $expect, "reason", $desc); cmp_field($result, $expect, "name", $desc); } # if we got no depth then default to 1 my $depth = 1; if (exists $expect->{depth}) { $depth = $expect->{depth}; } # if depth was explicitly undef then don't test it if (defined $depth) { $Test->is_eq($result->{depth}, $depth, "checking depth") || $Test->diag('You need to change $Test::Builder::Level'); } if (defined(my $exp = $expect->{diag})) { my $got = ''; if (ref $exp eq 'Regexp') { if (not $Test->like($result->{diag}, $exp, "subtest '$sub_name' of '$name' compare diag")) { $got = $result->{diag}; } } else { # if there actually is some diag then put a \n on the end if it's not # there already $exp .= "\n" if (length($exp) and $exp !~ /\n$/); if (not $Test->ok($result->{diag} eq $exp, "subtest '$sub_name' of '$name' compare diag")) { $got = $result->{diag}; } } if ($got) { my $glen = length($got); my $elen = length($exp); for ($got, $exp) { my @lines = split("\n", $_); $_ = join("\n", map { if ($want_space) { $_ = $colour.escape($_).$reset; } else { "'$colour$_$reset'" } } @lines); } $Test->diag(<32 and $c<125) or $c == 10) { $res .= $char; } else { $res .= sprintf('\x{%x}', $c) } } return $res; } sub cmp_results { my ($results, $expects, $name) = @_; $Test->is_num(scalar @$results, scalar @$expects, "Test '$name' result count"); for (my $i = 0; $i < @$expects; $i++) { my $expect = $expects->[$i]; my $result = $results->[$i]; local $Test::Builder::Level = $Test::Builder::Level + 1; cmp_result($result, $expect, $name); } } ######## nicked from Test::More sub plan { my(@plan) = @_; my $caller = caller; $Test->exported_to($caller); my @imports = (); foreach my $idx (0..$#plan) { if( $plan[$idx] eq 'import' ) { my($tag, $imports) = splice @plan, $idx, 2; @imports = @$imports; last; } } $Test->plan(@plan); __PACKAGE__->_export_to_level(1, __PACKAGE__, @imports); } sub import { my($class) = shift; { no warnings 'redefine'; *Test::Builder::new = \&new_new; } goto &plan; } sub _export_to_level { my $pkg = shift; my $level = shift; (undef) = shift; # redundant arg my $callpkg = caller($level); $pkg->export($callpkg, @_); } ############ 1; __END__ =head1 NAME Test::Tester - Ease testing test modules built with Test::Builder =head1 SYNOPSIS use Test::Tester tests => 6; use Test::MyStyle; check_test( sub { is_mystyle_eq("this", "that", "not eq"); }, { ok => 0, # expect this to fail name => "not eq", diag => "Expected: 'this'\nGot: 'that'", } ); or use Test::Tester tests => 6; use Test::MyStyle; check_test( sub { is_mystyle_qr("this", "that", "not matching"); }, { ok => 0, # expect this to fail name => "not matching", diag => qr/Expected: 'this'\s+Got: 'that'/, } ); or use Test::Tester; use Test::More tests => 3; use Test::MyStyle; my ($premature, @results) = run_tests( sub { is_database_alive("dbname"); } ); # now use Test::More::like to check the diagnostic output like($results[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag"); =head1 DESCRIPTION If you have written a test module based on Test::Builder then Test::Tester allows you to test it with the minimum of effort. =head1 HOW TO USE (THE EASY WAY) From version 0.08 Test::Tester no longer requires you to included anything special in your test modules. All you need to do is use Test::Tester; in your test script B any other Test::Builder based modules and away you go. Other modules based on Test::Builder can be used to help with the testing. In fact you can even use functions from your module to test other functions from the same module (while this is possible it is probably not a good idea, if your module has bugs, then using it to test itself may give the wrong answers). The easiest way to test is to do something like check_test( sub { is_mystyle_eq("this", "that", "not eq") }, { ok => 0, # we expect the test to fail name => "not eq", diag => "Expected: 'this'\nGot: 'that'", } ); this will execute the is_mystyle_eq test, capturing its results and checking that they are what was expected. You may need to examine the test results in a more flexible way, for example, the diagnostic output may be quite long or complex or it may involve something that you cannot predict in advance like a timestamp. In this case you can get direct access to the test results: my ($premature, @results) = run_tests( sub { is_database_alive("dbname"); } ); like($result[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag"); or check_test( sub { is_mystyle_qr("this", "that", "not matching") }, { ok => 0, # we expect the test to fail name => "not matching", diag => qr/Expected: 'this'\s+Got: 'that'/, } ); We cannot predict how long the database ping will take so we use Test::More's like() test to check that the diagnostic string is of the right form. =head1 HOW TO USE (THE HARD WAY) I Make your module use the Test::Tester::Capture object instead of the Test::Builder one. How to do this depends on your module but assuming that your module holds the Test::Builder object in $Test and that all your test routines access it through $Test then providing a function something like this sub set_builder { $Test = shift; } should allow your test scripts to do Test::YourModule::set_builder(Test::Tester->capture); and after that any tests inside your module will captured. =head1 TEST RESULTS The result of each test is captured in a hash. These hashes are the same as the hashes returned by Test::Builder->details but with a couple of extra fields. These fields are documented in L in the details() function =over 2 =item ok Did the test pass? =item actual_ok Did the test really pass? That is, did the pass come from Test::Builder->ok() or did it pass because it was a TODO test? =item name The name supplied for the test. =item type What kind of test? Possibilities include, skip, todo etc. See L for more details. =item reason The reason for the skip, todo etc. See L for more details. =back These fields are exclusive to Test::Tester. =over 2 =item diag Any diagnostics that were output for the test. This only includes diagnostics output B the test result is declared. Note that Test::Builder ensures that any diagnostics end in a \n and it in earlier versions of Test::Tester it was essential that you have the final \n in your expected diagnostics. From version 0.10 onward, Test::Tester will add the \n if you forgot it. It will not add a \n if you are expecting no diagnostics. See below for help tracking down hard to find space and tab related problems. =item depth This allows you to check that your test module is setting the correct value for $Test::Builder::Level and thus giving the correct file and line number when a test fails. It is calculated by looking at caller() and $Test::Builder::Level. It should count how many subroutines there are before jumping into the function you are testing. So for example in run_tests( sub { my_test_function("a", "b") } ); the depth should be 1 and in sub deeper { my_test_function("a", "b") } run_tests(sub { deeper() }); depth should be 2, that is 1 for the sub {} and one for deeper(). This might seem a little complex but if your tests look like the simple examples in this doc then you don't need to worry as the depth will always be 1 and that's what Test::Tester expects by default. B: if you do not specify a value for depth in check_test() then it automatically compares it against 1, if you really want to skip the depth test then pass in undef. B: depth will not be correctly calculated for tests that run from a signal handler or an END block or anywhere else that hides the call stack. =back Some of Test::Tester's functions return arrays of these hashes, just like Test::Builder->details. That is, the hash for the first test will be array element 1 (not 0). Element 0 will not be a hash it will be a string which contains any diagnostic output that came before the first test. This should usually be empty, if it's not, it means something output diagnostics before any test results showed up. =head1 SPACES AND TABS Appearances can be deceptive, especially when it comes to emptiness. If you are scratching your head trying to work out why Test::Tester is saying that your diagnostics are wrong when they look perfectly right then the answer is probably whitespace. From version 0.10 on, Test::Tester surrounds the expected and got diag values with single quotes to make it easier to spot trailing whitespace. So in this example # Got diag (5 bytes): # 'abcd ' # Expected diag (4 bytes): # 'abcd' it is quite clear that there is a space at the end of the first string. Another way to solve this problem is to use colour and inverse video on an ANSI terminal, see below COLOUR below if you want this. Unfortunately this is sometimes not enough, neither colour nor quotes will help you with problems involving tabs, other non-printing characters and certain kinds of problems inherent in Unicode. To deal with this, you can switch Test::Tester into a mode whereby all "tricky" characters are shown as \{xx}. Tricky characters are those with ASCII code less than 33 or higher than 126. This makes the output more difficult to read but much easier to find subtle differences between strings. To turn on this mode either call C in your test script or set the C environment variable to be a true value. The example above would then look like # Got diag (5 bytes): # abcd\x{20} # Expected diag (4 bytes): # abcd =head1 COLOUR If you prefer to use colour as a means of finding tricky whitespace characters then you can set the C environment variable to a comma separated pair of colours, the first for the foreground, the second for the background. For example "white,red" will print white text on a red background. This requires the Term::ANSIColor module. You can specify any colour that would be acceptable to the Term::ANSIColor::color function. If you spell colour differently, that's no problem. The C variable also works (if both are set then the British spelling wins out). =head1 EXPORTED FUNCTIONS =head3 ($premature, @results) = run_tests(\&test_sub) \&test_sub is a reference to a subroutine. run_tests runs the subroutine in $test_sub and captures the results of any tests inside it. You can run more than 1 test inside this subroutine if you like. $premature is a string containing any diagnostic output from before the first test. @results is an array of test result hashes. =head3 cmp_result(\%result, \%expect, $name) \%result is a ref to a test result hash. \%expect is a ref to a hash of expected values for the test result. cmp_result compares the result with the expected values. If any differences are found it outputs diagnostics. You may leave out any field from the expected result and cmp_result will not do the comparison of that field. =head3 cmp_results(\@results, \@expects, $name) \@results is a ref to an array of test results. \@expects is a ref to an array of hash refs. cmp_results checks that the results match the expected results and if any differences are found it outputs diagnostics. It first checks that the number of elements in \@results and \@expects is the same. Then it goes through each result checking it against the expected result as in cmp_result() above. =head3 ($premature, @results) = check_tests(\&test_sub, \@expects, $name) \&test_sub is a reference to a subroutine. \@expect is a ref to an array of hash refs which are expected test results. check_tests combines run_tests and cmp_tests into a single call. It also checks if the tests died at any stage. It returns the same values as run_tests, so you can further examine the test results if you need to. =head3 ($premature, @results) = check_test(\&test_sub, \%expect, $name) \&test_sub is a reference to a subroutine. \%expect is a ref to an hash of expected values for the test result. check_test is a wrapper around check_tests. It combines run_tests and cmp_tests into a single call, checking if the test died. It assumes that only a single test is run inside \&test_sub and include a test to make sure this is true. It returns the same values as run_tests, so you can further examine the test results if you need to. =head3 show_space() Turn on the escaping of characters as described in the SPACES AND TABS section. =head1 HOW IT WORKS Normally, a test module (let's call it Test:MyStyle) calls Test::Builder->new to get the Test::Builder object. Test::MyStyle calls methods on this object to record information about test results. When Test::Tester is loaded, it replaces Test::Builder's new() method with one which returns a Test::Tester::Delegate object. Most of the time this object behaves as the real Test::Builder object. Any methods that are called are delegated to the real Test::Builder object so everything works perfectly. However once we go into test mode, the method calls are no longer passed to the real Test::Builder object, instead they go to the Test::Tester::Capture object. This object seems exactly like the real Test::Builder object, except, instead of outputting test results and diagnostics, it just records all the information for later analysis. =head1 CAVEATS Support for calling Test::Builder->note is minimal. It's implemented as an empty stub, so modules that use it will not crash but the calls are not recorded for testing purposes like the others. Patches welcome. =head1 SEE ALSO L the source of testing goodness. L for an alternative approach to the problem tackled by Test::Tester - captures the strings output by Test::Builder. This means you cannot get separate access to the individual pieces of information and you must predict B what your test will output. =head1 AUTHOR This module is copyright 2005 Fergal Daly , some parts are based on other people's work. Plan handling lifted from Test::More. written by Michael G Schwern . Test::Tester::Capture is a cut down and hacked up version of Test::Builder. Test::Builder was written by chromatic and Michael G Schwern . =head1 LICENSE Under the same license as Perl itself See http://www.perl.com/perl/misc/Artistic.html =cut PK!Tm�¯ÙÍÙÍperl5/Test/More.pmnuÏÃ6Ç$package Test::More; use 5.006; use strict; use warnings; #---- perlcritic exemptions. ----# # We use a lot of subroutine prototypes ## no critic (Subroutines::ProhibitSubroutinePrototypes) # Can't use Carp because it might cause C to accidentally succeed # even though the module being used forgot to use Carp. Yes, this # actually happened. sub _carp { my( $file, $line ) = ( caller(1) )[ 1, 2 ]; return warn @_, " at $file line $line\n"; } our $VERSION = '1.302183'; use Test::Builder::Module; our @ISA = qw(Test::Builder::Module); our @EXPORT = qw(ok use_ok require_ok is isnt like unlike is_deeply cmp_ok skip todo todo_skip pass fail eq_array eq_hash eq_set $TODO plan done_testing can_ok isa_ok new_ok diag note explain subtest BAIL_OUT ); =head1 NAME Test::More - yet another framework for writing test scripts =head1 SYNOPSIS use Test::More tests => 23; # or use Test::More skip_all => $reason; # or use Test::More; # see done_testing() require_ok( 'Some::Module' ); # Various ways to say "ok" ok($got eq $expected, $test_name); is ($got, $expected, $test_name); isnt($got, $expected, $test_name); # Rather than print STDERR "# here's what went wrong\n" diag("here's what went wrong"); like ($got, qr/expected/, $test_name); unlike($got, qr/expected/, $test_name); cmp_ok($got, '==', $expected, $test_name); is_deeply($got_complex_structure, $expected_complex_structure, $test_name); SKIP: { skip $why, $how_many unless $have_some_feature; ok( foo(), $test_name ); is( foo(42), 23, $test_name ); }; TODO: { local $TODO = $why; ok( foo(), $test_name ); is( foo(42), 23, $test_name ); }; can_ok($module, @methods); isa_ok($object, $class); pass($test_name); fail($test_name); BAIL_OUT($why); # UNIMPLEMENTED!!! my @status = Test::More::status; =head1 DESCRIPTION B If you're just getting started writing tests, have a look at L first. This is a drop in replacement for Test::Simple which you can switch to once you get the hang of basic testing. The purpose of this module is to provide a wide range of testing utilities. Various ways to say "ok" with better diagnostics, facilities to skip tests, test future features and compare complicated data structures. While you can do almost anything with a simple C function, it doesn't provide good diagnostic output. =head2 I love it when a plan comes together Before anything else, you need a testing plan. This basically declares how many tests your script is going to run to protect against premature failure. The preferred way to do this is to declare a plan when you C. use Test::More tests => 23; There are cases when you will not know beforehand how many tests your script is going to run. In this case, you can declare your tests at the end. use Test::More; ... run your tests ... done_testing( $number_of_tests_run ); B C should never be called in an C block. Sometimes you really don't know how many tests were run, or it's too difficult to calculate. In which case you can leave off $number_of_tests_run. In some cases, you'll want to completely skip an entire testing script. use Test::More skip_all => $skip_reason; Your script will declare a skip with the reason why you skipped and exit immediately with a zero (success). See L for details. If you want to control what functions Test::More will export, you have to use the 'import' option. For example, to import everything but 'fail', you'd do: use Test::More tests => 23, import => ['!fail']; Alternatively, you can use the C function. Useful for when you have to calculate the number of tests. use Test::More; plan tests => keys %Stuff * 3; or for deciding between running the tests at all: use Test::More; if( $^O eq 'MacOS' ) { plan skip_all => 'Test irrelevant on MacOS'; } else { plan tests => 42; } =cut sub plan { my $tb = Test::More->builder; return $tb->plan(@_); } # This implements "use Test::More 'no_diag'" but the behavior is # deprecated. sub import_extra { my $class = shift; my $list = shift; my @other = (); my $idx = 0; my $import; while( $idx <= $#{$list} ) { my $item = $list->[$idx]; if( defined $item and $item eq 'no_diag' ) { $class->builder->no_diag(1); } elsif( defined $item and $item eq 'import' ) { if ($import) { push @$import, @{$list->[ ++$idx ]}; } else { $import = $list->[ ++$idx ]; push @other, $item, $import; } } else { push @other, $item; } $idx++; } @$list = @other; if ($class eq __PACKAGE__ && (!$import || grep $_ eq '$TODO', @$import)) { my $to = $class->builder->exported_to; no strict 'refs'; *{"$to\::TODO"} = \our $TODO; if ($import) { @$import = grep $_ ne '$TODO', @$import; } else { push @$list, import => [grep $_ ne '$TODO', @EXPORT]; } } return; } =over 4 =item B done_testing(); done_testing($number_of_tests); If you don't know how many tests you're going to run, you can issue the plan when you're done running tests. $number_of_tests is the same as C, it's the number of tests you expected to run. You can omit this, in which case the number of tests you ran doesn't matter, just the fact that your tests ran to conclusion. This is safer than and replaces the "no_plan" plan. B You must never put C inside an C block. The plan is there to ensure your test does not exit before testing has completed. If you use an END block you completely bypass this protection. =back =cut sub done_testing { my $tb = Test::More->builder; $tb->done_testing(@_); } =head2 Test names By convention, each test is assigned a number in order. This is largely done automatically for you. However, it's often very useful to assign a name to each test. Which would you rather see: ok 4 not ok 5 ok 6 or ok 4 - basic multi-variable not ok 5 - simple exponential ok 6 - force == mass * acceleration The later gives you some idea of what failed. It also makes it easier to find the test in your script, simply search for "simple exponential". All test functions take a name argument. It's optional, but highly suggested that you use it. =head2 I'm ok, you're not ok. The basic purpose of this module is to print out either "ok #" or "not ok #" depending on if a given test succeeded or failed. Everything else is just gravy. All of the following print "ok" or "not ok" depending on if the test succeeded or failed. They all also return true or false, respectively. =over 4 =item B ok($got eq $expected, $test_name); This simply evaluates any expression (C<$got eq $expected> is just a simple example) and uses that to determine if the test succeeded or failed. A true expression passes, a false one fails. Very simple. For example: ok( $exp{9} == 81, 'simple exponential' ); ok( Film->can('db_Main'), 'set_db()' ); ok( $p->tests == 4, 'saw tests' ); ok( !grep(!defined $_, @items), 'all items defined' ); (Mnemonic: "This is ok.") $test_name is a very short description of the test that will be printed out. It makes it very easy to find a test in your script when it fails and gives others an idea of your intentions. $test_name is optional, but we B strongly encourage its use. Should an C fail, it will produce some diagnostics: not ok 18 - sufficient mucus # Failed test 'sufficient mucus' # in foo.t at line 42. This is the same as L's C routine. =cut sub ok ($;$) { my( $test, $name ) = @_; my $tb = Test::More->builder; return $tb->ok( $test, $name ); } =item B =item B is ( $got, $expected, $test_name ); isnt( $got, $expected, $test_name ); Similar to C, C and C compare their two arguments with C and C respectively and use the result of that to determine if the test succeeded or failed. So these: # Is the ultimate answer 42? is( ultimate_answer(), 42, "Meaning of Life" ); # $foo isn't empty isnt( $foo, '', "Got some foo" ); are similar to these: ok( ultimate_answer() eq 42, "Meaning of Life" ); ok( $foo ne '', "Got some foo" ); C will only ever match C. So you can test a value against C like this: is($not_defined, undef, "undefined as expected"); (Mnemonic: "This is that." "This isn't that.") So why use these? They produce better diagnostics on failure. C cannot know what you are testing for (beyond the name), but C and C know what the test was and why it failed. For example this test: my $foo = 'waffle'; my $bar = 'yarblokos'; is( $foo, $bar, 'Is foo the same as bar?' ); Will produce something like this: not ok 17 - Is foo the same as bar? # Failed test 'Is foo the same as bar?' # in foo.t at line 139. # got: 'waffle' # expected: 'yarblokos' So you can figure out what went wrong without rerunning the test. You are encouraged to use C and C over C where possible, however do not be tempted to use them to find out if something is true or false! # XXX BAD! is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' ); This does not check if C is true, it checks if it returns 1. Very different. Similar caveats exist for false and 0. In these cases, use C. ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' ); A simple call to C usually does not provide a strong test but there are cases when you cannot say much more about a value than that it is different from some other value: new_ok $obj, "Foo"; my $clone = $obj->clone; isa_ok $obj, "Foo", "Foo->clone"; isnt $obj, $clone, "clone() produces a different object"; For those grammatical pedants out there, there's an C function which is an alias of C. =cut sub is ($$;$) { my $tb = Test::More->builder; return $tb->is_eq(@_); } sub isnt ($$;$) { my $tb = Test::More->builder; return $tb->isnt_eq(@_); } *isn't = \&isnt; # ' to unconfuse syntax higlighters =item B like( $got, qr/expected/, $test_name ); Similar to C, C matches $got against the regex C. So this: like($got, qr/expected/, 'this is like that'); is similar to: ok( $got =~ m/expected/, 'this is like that'); (Mnemonic "This is like that".) The second argument is a regular expression. It may be given as a regex reference (i.e. C) or (for better compatibility with older perls) as a string that looks like a regex (alternative delimiters are currently not supported): like( $got, '/expected/', 'this is like that' ); Regex options may be placed on the end (C<'/expected/i'>). Its advantages over C are similar to that of C and C. Better diagnostics on failure. =cut sub like ($$;$) { my $tb = Test::More->builder; return $tb->like(@_); } =item B unlike( $got, qr/expected/, $test_name ); Works exactly as C, only it checks if $got B match the given pattern. =cut sub unlike ($$;$) { my $tb = Test::More->builder; return $tb->unlike(@_); } =item B cmp_ok( $got, $op, $expected, $test_name ); Halfway between C and C lies C. This allows you to compare two arguments using any binary perl operator. The test passes if the comparison is true and fails otherwise. # ok( $got eq $expected ); cmp_ok( $got, 'eq', $expected, 'this eq that' ); # ok( $got == $expected ); cmp_ok( $got, '==', $expected, 'this == that' ); # ok( $got && $expected ); cmp_ok( $got, '&&', $expected, 'this && that' ); ...etc... Its advantage over C is when the test fails you'll know what $got and $expected were: not ok 1 # Failed test in foo.t at line 12. # '23' # && # undef It's also useful in those cases where you are comparing numbers and C's use of C will interfere: cmp_ok( $big_hairy_number, '==', $another_big_hairy_number ); It's especially useful when comparing greater-than or smaller-than relation between values: cmp_ok( $some_value, '<=', $upper_limit ); =cut sub cmp_ok($$$;$) { my $tb = Test::More->builder; return $tb->cmp_ok(@_); } =item B can_ok($module, @methods); can_ok($object, @methods); Checks to make sure the $module or $object can do these @methods (works with functions, too). can_ok('Foo', qw(this that whatever)); is almost exactly like saying: ok( Foo->can('this') && Foo->can('that') && Foo->can('whatever') ); only without all the typing and with a better interface. Handy for quickly testing an interface. No matter how many @methods you check, a single C call counts as one test. If you desire otherwise, use: foreach my $meth (@methods) { can_ok('Foo', $meth); } =cut sub can_ok ($@) { my( $proto, @methods ) = @_; my $class = ref $proto || $proto; my $tb = Test::More->builder; unless($class) { my $ok = $tb->ok( 0, "->can(...)" ); $tb->diag(' can_ok() called with empty class or reference'); return $ok; } unless(@methods) { my $ok = $tb->ok( 0, "$class->can(...)" ); $tb->diag(' can_ok() called with no methods'); return $ok; } my @nok = (); foreach my $method (@methods) { $tb->_try( sub { $proto->can($method) } ) or push @nok, $method; } my $name = (@methods == 1) ? "$class->can('$methods[0]')" : "$class->can(...)" ; my $ok = $tb->ok( !@nok, $name ); $tb->diag( map " $class->can('$_') failed\n", @nok ); return $ok; } =item B isa_ok($object, $class, $object_name); isa_ok($subclass, $class, $object_name); isa_ok($ref, $type, $ref_name); Checks to see if the given C<< $object->isa($class) >>. Also checks to make sure the object was defined in the first place. Handy for this sort of thing: my $obj = Some::Module->new; isa_ok( $obj, 'Some::Module' ); where you'd otherwise have to write my $obj = Some::Module->new; ok( defined $obj && $obj->isa('Some::Module') ); to safeguard against your test script blowing up. You can also test a class, to make sure that it has the right ancestor: isa_ok( 'Vole', 'Rodent' ); It works on references, too: isa_ok( $array_ref, 'ARRAY' ); The diagnostics of this test normally just refer to 'the object'. If you'd like them to be more specific, you can supply an $object_name (for example 'Test customer'). =cut sub isa_ok ($$;$) { my( $thing, $class, $thing_name ) = @_; my $tb = Test::More->builder; my $whatami; if( !defined $thing ) { $whatami = 'undef'; } elsif( ref $thing ) { $whatami = 'reference'; local($@,$!); require Scalar::Util; if( Scalar::Util::blessed($thing) ) { $whatami = 'object'; } } else { $whatami = 'class'; } # We can't use UNIVERSAL::isa because we want to honor isa() overrides my( $rslt, $error ) = $tb->_try( sub { $thing->isa($class) } ); if($error) { die <isa on your $whatami and got some weird error. Here's the error. $error WHOA } # Special case for isa_ok( [], "ARRAY" ) and like if( $whatami eq 'reference' ) { $rslt = UNIVERSAL::isa($thing, $class); } my($diag, $name); if( defined $thing_name ) { $name = "'$thing_name' isa '$class'"; $diag = defined $thing ? "'$thing_name' isn't a '$class'" : "'$thing_name' isn't defined"; } elsif( $whatami eq 'object' ) { my $my_class = ref $thing; $thing_name = qq[An object of class '$my_class']; $name = "$thing_name isa '$class'"; $diag = "The object of class '$my_class' isn't a '$class'"; } elsif( $whatami eq 'reference' ) { my $type = ref $thing; $thing_name = qq[A reference of type '$type']; $name = "$thing_name isa '$class'"; $diag = "The reference of type '$type' isn't a '$class'"; } elsif( $whatami eq 'undef' ) { $thing_name = 'undef'; $name = "$thing_name isa '$class'"; $diag = "$thing_name isn't defined"; } elsif( $whatami eq 'class' ) { $thing_name = qq[The class (or class-like) '$thing']; $name = "$thing_name isa '$class'"; $diag = "$thing_name isn't a '$class'"; } else { die; } my $ok; if($rslt) { $ok = $tb->ok( 1, $name ); } else { $ok = $tb->ok( 0, $name ); $tb->diag(" $diag\n"); } return $ok; } =item B my $obj = new_ok( $class ); my $obj = new_ok( $class => \@args ); my $obj = new_ok( $class => \@args, $object_name ); A convenience function which combines creating an object and calling C on that object. It is basically equivalent to: my $obj = $class->new(@args); isa_ok $obj, $class, $object_name; If @args is not given, an empty list will be used. This function only works on C and it assumes C will return just a single object which isa C<$class>. =cut sub new_ok { my $tb = Test::More->builder; $tb->croak("new_ok() must be given at least a class") unless @_; my( $class, $args, $object_name ) = @_; $args ||= []; my $obj; my( $success, $error ) = $tb->_try( sub { $obj = $class->new(@$args); 1 } ); if($success) { local $Test::Builder::Level = $Test::Builder::Level + 1; isa_ok $obj, $class, $object_name; } else { $class = 'undef' if !defined $class; $tb->ok( 0, "$class->new() died" ); $tb->diag(" Error was: $error"); } return $obj; } =item B subtest $name => \&code, @args; C runs the &code as its own little test with its own plan and its own result. The main test counts this as a single test using the result of the whole subtest to determine if its ok or not ok. For example... use Test::More tests => 3; pass("First test"); subtest 'An example subtest' => sub { plan tests => 2; pass("This is a subtest"); pass("So is this"); }; pass("Third test"); This would produce. 1..3 ok 1 - First test # Subtest: An example subtest 1..2 ok 1 - This is a subtest ok 2 - So is this ok 2 - An example subtest ok 3 - Third test A subtest may call C. No tests will be run, but the subtest is considered a skip. subtest 'skippy' => sub { plan skip_all => 'cuz I said so'; pass('this test will never be run'); }; Returns true if the subtest passed, false otherwise. Due to how subtests work, you may omit a plan if you desire. This adds an implicit C to the end of your subtest. The following two subtests are equivalent: subtest 'subtest with implicit done_testing()', sub { ok 1, 'subtests with an implicit done testing should work'; ok 1, '... and support more than one test'; ok 1, '... no matter how many tests are run'; }; subtest 'subtest with explicit done_testing()', sub { ok 1, 'subtests with an explicit done testing should work'; ok 1, '... and support more than one test'; ok 1, '... no matter how many tests are run'; done_testing(); }; Extra arguments given to C are passed to the callback. For example: sub my_subtest { my $range = shift; ... } for my $range (1, 10, 100, 1000) { subtest "testing range $range", \&my_subtest, $range; } =cut sub subtest { my $tb = Test::More->builder; return $tb->subtest(@_); } =item B =item B pass($test_name); fail($test_name); Sometimes you just want to say that the tests have passed. Usually the case is you've got some complicated condition that is difficult to wedge into an C. In this case, you can simply use C (to declare the test ok) or fail (for not ok). They are synonyms for C and C. Use these very, very, very sparingly. =cut sub pass (;$) { my $tb = Test::More->builder; return $tb->ok( 1, @_ ); } sub fail (;$) { my $tb = Test::More->builder; return $tb->ok( 0, @_ ); } =back =head2 Module tests Sometimes you want to test if a module, or a list of modules, can successfully load. For example, you'll often want a first test which simply loads all the modules in the distribution to make sure they work before going on to do more complicated testing. For such purposes we have C and C. =over 4 =item B require_ok($module); require_ok($file); Tries to C the given $module or $file. If it loads successfully, the test will pass. Otherwise it fails and displays the load error. C will guess whether the input is a module name or a filename. No exception will be thrown if the load fails. # require Some::Module require_ok "Some::Module"; # require "Some/File.pl"; require_ok "Some/File.pl"; # stop testing if any of your modules will not load for my $module (@module) { require_ok $module or BAIL_OUT "Can't load $module"; } =cut sub require_ok ($) { my($module) = shift; my $tb = Test::More->builder; my $pack = caller; # Try to determine if we've been given a module name or file. # Module names must be barewords, files not. $module = qq['$module'] unless _is_module_name($module); my $code = <ok( $eval_result, "require $module;" ); unless($ok) { chomp $eval_error; $tb->diag(< BEGIN { use_ok($module); } BEGIN { use_ok($module, @imports); } Like C, but it will C the $module in question and only loads modules, not files. If you just want to test a module can be loaded, use C. If you just want to load a module in a test, we recommend simply using C directly. It will cause the test to stop. It's recommended that you run C inside a BEGIN block so its functions are exported at compile-time and prototypes are properly honored. If @imports are given, they are passed through to the use. So this: BEGIN { use_ok('Some::Module', qw(foo bar)) } is like doing this: use Some::Module qw(foo bar); Version numbers can be checked like so: # Just like "use Some::Module 1.02" BEGIN { use_ok('Some::Module', 1.02) } Don't try to do this: BEGIN { use_ok('Some::Module'); ...some code that depends on the use... ...happening at compile time... } because the notion of "compile-time" is relative. Instead, you want: BEGIN { use_ok('Some::Module') } BEGIN { ...some code that depends on the use... } If you want the equivalent of C, use a module but not import anything, use C. BEGIN { require_ok "Foo" } =cut sub use_ok ($;@) { my( $module, @imports ) = @_; @imports = () unless @imports; my $tb = Test::More->builder; my %caller; @caller{qw/pack file line sub args want eval req strict warn/} = caller(0); my ($pack, $filename, $line, $warn) = @caller{qw/pack file line warn/}; $filename =~ y/\n\r/_/; # so it doesn't run off the "#line $line $f" line my $code; if( @imports == 1 and $imports[0] =~ /^\d+(?:\.\d+)?$/ ) { # probably a version check. Perl needs to see the bare number # for it to work with non-Exporter based modules. $code = <ok( $eval_result, "use $module;" ); unless($ok) { chomp $eval_error; $@ =~ s{^BEGIN failed--compilation aborted at .*$} {BEGIN failed--compilation aborted at $filename line $line.}m; $tb->diag(< I'm not quite sure what will happen with filehandles. =over 4 =item B is_deeply( $got, $expected, $test_name ); Similar to C, except that if $got and $expected are references, it does a deep comparison walking each data structure to see if they are equivalent. If the two structures are different, it will display the place where they start differing. C compares the dereferenced values of references, the references themselves (except for their type) are ignored. This means aspects such as blessing and ties are not considered "different". C currently has very limited handling of function reference and globs. It merely checks if they have the same referent. This may improve in the future. L and L provide more in-depth functionality along these lines. B is_deeply() has limitations when it comes to comparing strings and refs: my $path = path('.'); my $hash = {}; is_deeply( $path, "$path" ); # ok is_deeply( $hash, "$hash" ); # fail This happens because is_deeply will unoverload all arguments unconditionally. It is probably best not to use is_deeply with overloading. For legacy reasons this is not likely to ever be fixed. If you would like a much better tool for this you should see L Specifically L has an C function that works like C with many improvements. =cut our( @Data_Stack, %Refs_Seen ); my $DNE = bless [], 'Does::Not::Exist'; sub _dne { return ref $_[0] eq ref $DNE; } ## no critic (Subroutines::RequireArgUnpacking) sub is_deeply { my $tb = Test::More->builder; unless( @_ == 2 or @_ == 3 ) { my $msg = <<'WARNING'; is_deeply() takes two or three args, you gave %d. This usually means you passed an array or hash instead of a reference to it WARNING chop $msg; # clip off newline so carp() will put in line/file _carp sprintf $msg, scalar @_; return $tb->ok(0); } my( $got, $expected, $name ) = @_; $tb->_unoverload_str( \$expected, \$got ); my $ok; if( !ref $got and !ref $expected ) { # neither is a reference $ok = $tb->is_eq( $got, $expected, $name ); } elsif( !ref $got xor !ref $expected ) { # one's a reference, one isn't $ok = $tb->ok( 0, $name ); $tb->diag( _format_stack({ vals => [ $got, $expected ] }) ); } else { # both references local @Data_Stack = (); if( _deep_check( $got, $expected ) ) { $ok = $tb->ok( 1, $name ); } else { $ok = $tb->ok( 0, $name ); $tb->diag( _format_stack(@Data_Stack) ); } } return $ok; } sub _format_stack { my(@Stack) = @_; my $var = '$FOO'; my $did_arrow = 0; foreach my $entry (@Stack) { my $type = $entry->{type} || ''; my $idx = $entry->{'idx'}; if( $type eq 'HASH' ) { $var .= "->" unless $did_arrow++; $var .= "{$idx}"; } elsif( $type eq 'ARRAY' ) { $var .= "->" unless $did_arrow++; $var .= "[$idx]"; } elsif( $type eq 'REF' ) { $var = "\${$var}"; } } my @vals = @{ $Stack[-1]{vals} }[ 0, 1 ]; my @vars = (); ( $vars[0] = $var ) =~ s/\$FOO/ \$got/; ( $vars[1] = $var ) =~ s/\$FOO/\$expected/; my $out = "Structures begin differing at:\n"; foreach my $idx ( 0 .. $#vals ) { my $val = $vals[$idx]; $vals[$idx] = !defined $val ? 'undef' : _dne($val) ? "Does not exist" : ref $val ? "$val" : "'$val'"; } $out .= "$vars[0] = $vals[0]\n"; $out .= "$vars[1] = $vals[1]\n"; $out =~ s/^/ /msg; return $out; } sub _type { my $thing = shift; return '' if !ref $thing; for my $type (qw(Regexp ARRAY HASH REF SCALAR GLOB CODE VSTRING)) { return $type if UNIVERSAL::isa( $thing, $type ); } return ''; } =back =head2 Diagnostics If you pick the right test function, you'll usually get a good idea of what went wrong when it failed. But sometimes it doesn't work out that way. So here we have ways for you to write your own diagnostic messages which are safer than just C. =over 4 =item B diag(@diagnostic_message); Prints a diagnostic message which is guaranteed not to interfere with test output. Like C @diagnostic_message is simply concatenated together. Returns false, so as to preserve failure. Handy for this sort of thing: ok( grep(/foo/, @users), "There's a foo user" ) or diag("Since there's no foo, check that /etc/bar is set up right"); which would produce: not ok 42 - There's a foo user # Failed test 'There's a foo user' # in foo.t at line 52. # Since there's no foo, check that /etc/bar is set up right. You might remember C with the mnemonic C. B The exact formatting of the diagnostic output is still changing, but it is guaranteed that whatever you throw at it won't interfere with the test. =item B note(@diagnostic_message); Like C, except the message will not be seen when the test is run in a harness. It will only be visible in the verbose TAP stream. Handy for putting in notes which might be useful for debugging, but don't indicate a problem. note("Tempfile is $tempfile"); =cut sub diag { return Test::More->builder->diag(@_); } sub note { return Test::More->builder->note(@_); } =item B my @dump = explain @diagnostic_message; Will dump the contents of any references in a human readable format. Usually you want to pass this into C or C. Handy for things like... is_deeply($have, $want) || diag explain $have; or note explain \%args; Some::Class->method(%args); =cut sub explain { return Test::More->builder->explain(@_); } =back =head2 Conditional tests Sometimes running a test under certain conditions will cause the test script to die. A certain function or method isn't implemented (such as C on MacOS), some resource isn't available (like a net connection) or a module isn't available. In these cases it's necessary to skip tests, or declare that they are supposed to fail but will work in the future (a todo test). For more details on the mechanics of skip and todo tests see L. The way Test::More handles this is with a named block. Basically, a block of tests which can be skipped over or made todo. It's best if I just show you... =over 4 =item B SKIP: { skip $why, $how_many if $condition; ...normal testing code goes here... } This declares a block of tests that might be skipped, $how_many tests there are, $why and under what $condition to skip them. An example is the easiest way to illustrate: SKIP: { eval { require HTML::Lint }; skip "HTML::Lint not installed", 2 if $@; my $lint = new HTML::Lint; isa_ok( $lint, "HTML::Lint" ); $lint->parse( $html ); is( $lint->errors, 0, "No errors found in HTML" ); } If the user does not have HTML::Lint installed, the whole block of code I. Test::More will output special ok's which Test::Harness interprets as skipped, but passing, tests. It's important that $how_many accurately reflects the number of tests in the SKIP block so the # of tests run will match up with your plan. If your plan is C $how_many is optional and will default to 1. It's perfectly safe to nest SKIP blocks. Each SKIP block must have the label C, or Test::More can't work its magic. You don't skip tests which are failing because there's a bug in your program, or for which you don't yet have code written. For that you use TODO. Read on. =cut ## no critic (Subroutines::RequireFinalReturn) sub skip { my( $why, $how_many ) = @_; my $tb = Test::More->builder; # If the plan is set, and is static, then skip needs a count. If the plan # is 'no_plan' we are fine. As well if plan is undefined then we are # waiting for done_testing. unless (defined $how_many) { my $plan = $tb->has_plan; _carp "skip() needs to know \$how_many tests are in the block" if $plan && $plan =~ m/^\d+$/; $how_many = 1; } if( defined $how_many and $how_many =~ /\D/ ) { _carp "skip() was passed a non-numeric number of tests. Did you get the arguments backwards?"; $how_many = 1; } for( 1 .. $how_many ) { $tb->skip($why); } no warnings 'exiting'; last SKIP; } =item B TODO: { local $TODO = $why if $condition; ...normal testing code goes here... } Declares a block of tests you expect to fail and $why. Perhaps it's because you haven't fixed a bug or haven't finished a new feature: TODO: { local $TODO = "URI::Geller not finished"; my $card = "Eight of clubs"; is( URI::Geller->your_card, $card, 'Is THIS your card?' ); my $spoon; URI::Geller->bend_spoon; is( $spoon, 'bent', "Spoon bending, that's original" ); } With a todo block, the tests inside are expected to fail. Test::More will run the tests normally, but print out special flags indicating they are "todo". L will interpret failures as being ok. Should anything succeed, it will report it as an unexpected success. You then know the thing you had todo is done and can remove the TODO flag. The nice part about todo tests, as opposed to simply commenting out a block of tests, is that it is like having a programmatic todo list. You know how much work is left to be done, you're aware of what bugs there are, and you'll know immediately when they're fixed. Once a todo test starts succeeding, simply move it outside the block. When the block is empty, delete it. =item B TODO: { todo_skip $why, $how_many if $condition; ...normal testing code... } With todo tests, it's best to have the tests actually run. That way you'll know when they start passing. Sometimes this isn't possible. Often a failing test will cause the whole program to die or hang, even inside an C with and using C. In these extreme cases you have no choice but to skip over the broken tests entirely. The syntax and behavior is similar to a C except the tests will be marked as failing but todo. L will interpret them as passing. =cut sub todo_skip { my( $why, $how_many ) = @_; my $tb = Test::More->builder; unless( defined $how_many ) { # $how_many can only be avoided when no_plan is in use. _carp "todo_skip() needs to know \$how_many tests are in the block" unless $tb->has_plan eq 'no_plan'; $how_many = 1; } for( 1 .. $how_many ) { $tb->todo_skip($why); } no warnings 'exiting'; last TODO; } =item When do I use SKIP vs. TODO? B, use SKIP. This includes optional modules that aren't installed, running under an OS that doesn't have some feature (like C or symlinks), or maybe you need an Internet connection and one isn't available. B, use TODO. This is for any code you haven't written yet, or bugs you have yet to fix, but want to put tests in your testing script (always a good idea). =back =head2 Test control =over 4 =item B BAIL_OUT($reason); Indicates to the harness that things are going so badly all testing should terminate. This includes the running of any additional test scripts. This is typically used when testing cannot continue such as a critical module failing to compile or a necessary external utility not being available such as a database connection failing. The test will exit with 255. For even better control look at L. =cut sub BAIL_OUT { my $reason = shift; my $tb = Test::More->builder; $tb->BAIL_OUT($reason); } =back =head2 Discouraged comparison functions The use of the following functions is discouraged as they are not actually testing functions and produce no diagnostics to help figure out what went wrong. They were written before C existed because I couldn't figure out how to display a useful diff of two arbitrary data structures. These functions are usually used inside an C. ok( eq_array(\@got, \@expected) ); C can do that better and with diagnostics. is_deeply( \@got, \@expected ); They may be deprecated in future versions. =over 4 =item B my $is_eq = eq_array(\@got, \@expected); Checks if two arrays are equivalent. This is a deep check, so multi-level structures are handled correctly. =cut #'# sub eq_array { local @Data_Stack = (); _deep_check(@_); } sub _eq_array { my( $a1, $a2 ) = @_; if( grep _type($_) ne 'ARRAY', $a1, $a2 ) { warn "eq_array passed a non-array ref"; return 0; } return 1 if $a1 eq $a2; my $ok = 1; my $max = $#$a1 > $#$a2 ? $#$a1 : $#$a2; for( 0 .. $max ) { my $e1 = $_ > $#$a1 ? $DNE : $a1->[$_]; my $e2 = $_ > $#$a2 ? $DNE : $a2->[$_]; next if _equal_nonrefs($e1, $e2); push @Data_Stack, { type => 'ARRAY', idx => $_, vals => [ $e1, $e2 ] }; $ok = _deep_check( $e1, $e2 ); pop @Data_Stack if $ok; last unless $ok; } return $ok; } sub _equal_nonrefs { my( $e1, $e2 ) = @_; return if ref $e1 or ref $e2; if ( defined $e1 ) { return 1 if defined $e2 and $e1 eq $e2; } else { return 1 if !defined $e2; } return; } sub _deep_check { my( $e1, $e2 ) = @_; my $tb = Test::More->builder; my $ok = 0; # Effectively turn %Refs_Seen into a stack. This avoids picking up # the same referenced used twice (such as [\$a, \$a]) to be considered # circular. local %Refs_Seen = %Refs_Seen; { $tb->_unoverload_str( \$e1, \$e2 ); # Either they're both references or both not. my $same_ref = !( !ref $e1 xor !ref $e2 ); my $not_ref = ( !ref $e1 and !ref $e2 ); if( defined $e1 xor defined $e2 ) { $ok = 0; } elsif( !defined $e1 and !defined $e2 ) { # Shortcut if they're both undefined. $ok = 1; } elsif( _dne($e1) xor _dne($e2) ) { $ok = 0; } elsif( $same_ref and( $e1 eq $e2 ) ) { $ok = 1; } elsif($not_ref) { push @Data_Stack, { type => '', vals => [ $e1, $e2 ] }; $ok = 0; } else { if( $Refs_Seen{$e1} ) { return $Refs_Seen{$e1} eq $e2; } else { $Refs_Seen{$e1} = "$e2"; } my $type = _type($e1); $type = 'DIFFERENT' unless _type($e2) eq $type; if( $type eq 'DIFFERENT' ) { push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] }; $ok = 0; } elsif( $type eq 'ARRAY' ) { $ok = _eq_array( $e1, $e2 ); } elsif( $type eq 'HASH' ) { $ok = _eq_hash( $e1, $e2 ); } elsif( $type eq 'REF' ) { push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] }; $ok = _deep_check( $$e1, $$e2 ); pop @Data_Stack if $ok; } elsif( $type eq 'SCALAR' ) { push @Data_Stack, { type => 'REF', vals => [ $e1, $e2 ] }; $ok = _deep_check( $$e1, $$e2 ); pop @Data_Stack if $ok; } elsif($type) { push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] }; $ok = 0; } else { _whoa( 1, "No type in _deep_check" ); } } } return $ok; } sub _whoa { my( $check, $desc ) = @_; if($check) { die <<"WHOA"; WHOA! $desc This should never happen! Please contact the author immediately! WHOA } } =item B my $is_eq = eq_hash(\%got, \%expected); Determines if the two hashes contain the same keys and values. This is a deep check. =cut sub eq_hash { local @Data_Stack = (); return _deep_check(@_); } sub _eq_hash { my( $a1, $a2 ) = @_; if( grep _type($_) ne 'HASH', $a1, $a2 ) { warn "eq_hash passed a non-hash ref"; return 0; } return 1 if $a1 eq $a2; my $ok = 1; my $bigger = keys %$a1 > keys %$a2 ? $a1 : $a2; foreach my $k ( keys %$bigger ) { my $e1 = exists $a1->{$k} ? $a1->{$k} : $DNE; my $e2 = exists $a2->{$k} ? $a2->{$k} : $DNE; next if _equal_nonrefs($e1, $e2); push @Data_Stack, { type => 'HASH', idx => $k, vals => [ $e1, $e2 ] }; $ok = _deep_check( $e1, $e2 ); pop @Data_Stack if $ok; last unless $ok; } return $ok; } =item B my $is_eq = eq_set(\@got, \@expected); Similar to C, except the order of the elements is B important. This is a deep check, but the irrelevancy of order only applies to the top level. ok( eq_set(\@got, \@expected) ); Is better written: is_deeply( [sort @got], [sort @expected] ); B By historical accident, this is not a true set comparison. While the order of elements does not matter, duplicate elements do. B C does not know how to deal with references at the top level. The following is an example of a comparison which might not work: eq_set([\1, \2], [\2, \1]); L contains much better set comparison functions. =cut sub eq_set { my( $a1, $a2 ) = @_; return 0 unless @$a1 == @$a2; no warnings 'uninitialized'; # It really doesn't matter how we sort them, as long as both arrays are # sorted with the same algorithm. # # Ensure that references are not accidentally treated the same as a # string containing the reference. # # Have to inline the sort routine due to a threading/sort bug. # See [rt.cpan.org 6782] # # I don't know how references would be sorted so we just don't sort # them. This means eq_set doesn't really work with refs. return eq_array( [ grep( ref, @$a1 ), sort( grep( !ref, @$a1 ) ) ], [ grep( ref, @$a2 ), sort( grep( !ref, @$a2 ) ) ], ); } =back =head2 Extending and Embedding Test::More Sometimes the Test::More interface isn't quite enough. Fortunately, Test::More is built on top of L which provides a single, unified backend for any test library to use. This means two test libraries which both use B be used together in the same program>. If you simply want to do a little tweaking of how the tests behave, you can access the underlying L object like so: =over 4 =item B my $test_builder = Test::More->builder; Returns the L object underlying Test::More for you to play with. =back =head1 EXIT CODES If all your tests passed, L will exit with zero (which is normal). If anything failed it will exit with how many failed. If you run less (or more) tests than you planned, the missing (or extras) will be considered failures. If no tests were ever run L will throw a warning and exit with 255. If the test died, even after having successfully completed all its tests, it will still be considered a failure and will exit with 255. So the exit codes are... 0 all tests successful 255 test died or all passed but wrong # of tests run any other number how many failed (including missing or extras) If you fail more than 254 tests, it will be reported as 254. B This behavior may go away in future versions. =head1 COMPATIBILITY Test::More works with Perls as old as 5.8.1. Thread support is not very reliable before 5.10.1, but that's because threads are not very reliable before 5.10.1. Although Test::More has been a core module in versions of Perl since 5.6.2, Test::More has evolved since then, and not all of the features you're used to will be present in the shipped version of Test::More. If you are writing a module, don't forget to indicate in your package metadata the minimum version of Test::More that you require. For instance, if you want to use C but want your test script to run on Perl 5.10.0, you will need to explicitly require Test::More > 0.88. Key feature milestones include: =over 4 =item subtests Subtests were released in Test::More 0.94, which came with Perl 5.12.0. Subtests did not implicitly call C until 0.96; the first Perl with that fix was Perl 5.14.0 with 0.98. =item C This was released in Test::More 0.88 and first shipped with Perl in 5.10.1 as part of Test::More 0.92. =item C Although C was introduced in 0.40, 0.86 fixed an important bug to make it safe for overloaded objects; the fixed first shipped with Perl in 5.10.1 as part of Test::More 0.92. =item C C and C These were was released in Test::More 0.82, and first shipped with Perl in 5.10.1 as part of Test::More 0.92. =back There is a full version history in the Changes file, and the Test::More versions included as core can be found using L: $ corelist -a Test::More =head1 CAVEATS and NOTES =over 4 =item utf8 / "Wide character in print" If you use utf8 or other non-ASCII characters with Test::More you might get a "Wide character in print" warning. Using C<< binmode STDOUT, ":utf8" >> will not fix it. L (which powers Test::More) duplicates STDOUT and STDERR. So any changes to them, including changing their output disciplines, will not be seen by Test::More. One work around is to apply encodings to STDOUT and STDERR as early as possible and before Test::More (or any other Test module) loads. use open ':std', ':encoding(utf8)'; use Test::More; A more direct work around is to change the filehandles used by L. my $builder = Test::More->builder; binmode $builder->output, ":encoding(utf8)"; binmode $builder->failure_output, ":encoding(utf8)"; binmode $builder->todo_output, ":encoding(utf8)"; =item Overloaded objects String overloaded objects are compared B (or in C's case, strings or numbers as appropriate to the comparison op). This prevents Test::More from piercing an object's interface allowing better blackbox testing. So if a function starts returning overloaded objects instead of bare strings your tests won't notice the difference. This is good. However, it does mean that functions like C cannot be used to test the internals of string overloaded objects. In this case I would suggest L which contains more flexible testing functions for complex data structures. =item Threads Test::More will only be aware of threads if C has been done I Test::More is loaded. This is ok: use threads; use Test::More; This may cause problems: use Test::More use threads; 5.8.1 and above are supported. Anything below that has too many bugs. =back =head1 HISTORY This is a case of convergent evolution with Joshua Pritikin's L module. I was largely unaware of its existence when I'd first written my own C routines. This module exists because I can't figure out how to easily wedge test names into Test's interface (along with a few other problems). The goal here is to have a testing utility that's simple to learn, quick to use and difficult to trip yourself up with while still providing more flexibility than the existing Test.pm. As such, the names of the most common routines are kept tiny, special cases and magic side-effects are kept to a minimum. WYSIWYG. =head1 SEE ALSO =head2 =head2 ALTERNATIVES L is the most recent and modern set of tools for testing. L if all this confuses you and you just want to write some tests. You can upgrade to Test::More later (it's forward compatible). L tests written with Test.pm, the original testing module, do not play well with other testing libraries. Test::Legacy emulates the Test.pm interface and does play well with others. =head2 ADDITIONAL LIBRARIES L for more ways to test complex data structures. And it plays well with Test::More. L is like xUnit but more perlish. L gives you more powerful complex data structure testing. L shows the idea of embedded testing. L The ultimate mocking library. Easily spawn objects defined on the fly. Can also override, block, or reimplement packages as needed. L Quickly define fixture data for unit tests. =head2 OTHER COMPONENTS L is the test runner and output interpreter for Perl. It's the thing that powers C and where the C utility comes from. =head2 BUNDLES L Most commonly needed test functions and features. =head1 AUTHORS Michael G Schwern Eschwern@pobox.comE with much inspiration from Joshua Pritikin's Test module and lots of help from Barrie Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and the perl-qa gang. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 BUGS See F to report and view bugs. =head1 SOURCE The source code repository for Test::More can be found at F. =head1 COPYRIGHT Copyright 2001-2008 by Michael G Schwern Eschwern@pobox.comE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut 1; PK! ð+¿ïïperl5/Test/Builder/Module.pmnuÏÃ6Ç$package Test::Builder::Module; use strict; use Test::Builder; require Exporter; our @ISA = qw(Exporter); our $VERSION = '1.302183'; =head1 NAME Test::Builder::Module - Base class for test modules =head1 SYNOPSIS # Emulates Test::Simple package Your::Module; my $CLASS = __PACKAGE__; use parent 'Test::Builder::Module'; @EXPORT = qw(ok); sub ok ($;$) { my $tb = $CLASS->builder; return $tb->ok(@_); } 1; =head1 DESCRIPTION This is a superclass for L-based modules. It provides a handful of common functionality and a method of getting at the underlying L object. =head2 Importing Test::Builder::Module is a subclass of L which means your module is also a subclass of Exporter. @EXPORT, @EXPORT_OK, etc... all act normally. A few methods are provided to do the C<< use Your::Module tests => 23 >> part for you. =head3 import Test::Builder::Module provides an C method which acts in the same basic way as L's, setting the plan and controlling exporting of functions and variables. This allows your module to set the plan independent of L. All arguments passed to C are passed onto C<< Your::Module->builder->plan() >> with the exception of C<< import =>[qw(things to import)] >>. use Your::Module import => [qw(this that)], tests => 23; says to import the functions C and C as well as set the plan to be 23 tests. C also sets the C attribute of your builder to be the caller of the C function. Additional behaviors can be added to your C method by overriding C. =cut sub import { my($class) = shift; Test2::API::test2_load() unless Test2::API::test2_in_preload(); # Don't run all this when loading ourself. return 1 if $class eq 'Test::Builder::Module'; my $test = $class->builder; my $caller = caller; $test->exported_to($caller); $class->import_extra( \@_ ); my(@imports) = $class->_strip_imports( \@_ ); $test->plan(@_); local $Exporter::ExportLevel = $Exporter::ExportLevel + 1; $class->Exporter::import(@imports); } sub _strip_imports { my $class = shift; my $list = shift; my @imports = (); my @other = (); my $idx = 0; while( $idx <= $#{$list} ) { my $item = $list->[$idx]; if( defined $item and $item eq 'import' ) { push @imports, @{ $list->[ $idx + 1 ] }; $idx++; } else { push @other, $item; } $idx++; } @$list = @other; return @imports; } =head3 import_extra Your::Module->import_extra(\@import_args); C is called by C. It provides an opportunity for you to add behaviors to your module based on its import list. Any extra arguments which shouldn't be passed on to C should be stripped off by this method. See L for an example of its use. B This mechanism is I as it feels like a bit of an ugly hack in its current form. =cut sub import_extra { } =head2 Builder Test::Builder::Module provides some methods of getting at the underlying Test::Builder object. =head3 builder my $builder = Your::Class->builder; This method returns the L object associated with Your::Class. It is not a constructor so you can call it as often as you like. This is the preferred way to get the L object. You should I get it via C<< Test::Builder->new >> as was previously recommended. The object returned by C may change at runtime so you should call C inside each function rather than store it in a global. sub ok { my $builder = Your::Class->builder; return $builder->ok(@_); } =cut sub builder { return Test::Builder->new; } =head1 SEE ALSO L<< Test2::Manual::Tooling::TestBuilder >> describes the improved options for writing testing modules provided by L<< Test2 >>. =cut 1; PK!‰•u¡99perl5/Test/Builder/TodoDiag.pmnuÏÃ6Ç$package Test::Builder::TodoDiag; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event::Diag; our @ISA = qw(Test2::Event::Diag) } sub diagnostics { 0 } sub facet_data { my $self = shift; my $out = $self->SUPER::facet_data(); $out->{info}->[0]->{debug} = 0; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Builder::TodoDiag - Test::Builder subclass of Test2::Event::Diag =head1 DESCRIPTION This is used to encapsulate diag messages created inside TODO. =head1 SYNOPSIS You do not need to use this directly. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!„+wÍÍ"perl5/Test/Builder/Tester/Color.pmnuÏÃ6Ç$package Test::Builder::Tester::Color; use strict; our $VERSION = '1.302183'; require Test::Builder::Tester; =head1 NAME Test::Builder::Tester::Color - turn on colour in Test::Builder::Tester =head1 SYNOPSIS When running a test script perl -MTest::Builder::Tester::Color test.t =head1 DESCRIPTION Importing this module causes the subroutine color in Test::Builder::Tester to be called with a true value causing colour highlighting to be turned on in debug output. The sole purpose of this module is to enable colour highlighting from the command line. =cut sub import { Test::Builder::Tester::color(1); } =head1 AUTHOR Copyright Mark Fowler Emark@twoshortplanks.comE 2002. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 BUGS This module will have no effect unless Term::ANSIColor is installed. =head1 SEE ALSO L, L =cut 1; PK!ÌiöJJperl5/Test/Builder/Formatter.pmnuÏÃ6Ç$package Test::Builder::Formatter; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Formatter::TAP; our @ISA = qw(Test2::Formatter::TAP) } use Test2::Util::HashBase qw/no_header no_diag/; BEGIN { *OUT_STD = Test2::Formatter::TAP->can('OUT_STD'); *OUT_ERR = Test2::Formatter::TAP->can('OUT_ERR'); my $todo = OUT_ERR() + 1; *OUT_TODO = sub() { $todo }; } sub init { my $self = shift; $self->SUPER::init(@_); $self->{+HANDLES}->[OUT_TODO] = $self->{+HANDLES}->[OUT_STD]; } sub plan_tap { my ($self, $f) = @_; return if $self->{+NO_HEADER}; return $self->SUPER::plan_tap($f); } sub debug_tap { my ($self, $f, $num) = @_; return if $self->{+NO_DIAG}; my @out = $self->SUPER::debug_tap($f, $num); $self->redirect(\@out) if @out && ref $f->{about} && defined $f->{about}->{package} && $f->{about}->{package} eq 'Test::Builder::TodoDiag'; return @out; } sub info_tap { my ($self, $f) = @_; return if $self->{+NO_DIAG}; my @out = $self->SUPER::info_tap($f); $self->redirect(\@out) if @out && ref $f->{about} && defined $f->{about}->{package} && $f->{about}->{package} eq 'Test::Builder::TodoDiag'; return @out; } sub redirect { my ($self, $out) = @_; $_->[0] = OUT_TODO for @$out; } sub no_subtest_space { 1 } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Builder::Formatter - Test::Builder subclass of Test2::Formatter::TAP =head1 DESCRIPTION This is what takes events and turns them into TAP. =head1 SYNOPSIS use Test::Builder; # Loads Test::Builder::Formatter for you =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!Iz2sFsFperl5/Test/Builder/Tester.pmnuÏÃ6Ç$package Test::Builder::Tester; use strict; our $VERSION = '1.302183'; use Test::Builder; use Symbol; use Carp; =head1 NAME Test::Builder::Tester - test testsuites that have been built with Test::Builder =head1 SYNOPSIS use Test::Builder::Tester tests => 1; use Test::More; test_out("not ok 1 - foo"); test_fail(+1); fail("foo"); test_test("fail works"); =head1 DESCRIPTION A module that helps you test testing modules that are built with L. The testing system is designed to be used by performing a three step process for each test you wish to test. This process starts with using C and C in advance to declare what the testsuite you are testing will output with L to stdout and stderr. You then can run the test(s) from your test suite that call L. At this point the output of L is safely captured by L rather than being interpreted as real test output. The final stage is to call C that will simply compare what you predeclared to what L actually outputted, and report the results back with a "ok" or "not ok" (with debugging) to the normal output. =cut #### # set up testing #### my $t = Test::Builder->new; ### # make us an exporter ### use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(test_out test_err test_fail test_diag test_test line_num); sub import { my $class = shift; my(@plan) = @_; my $caller = caller; $t->exported_to($caller); $t->plan(@plan); my @imports = (); foreach my $idx ( 0 .. $#plan ) { if( $plan[$idx] eq 'import' ) { @imports = @{ $plan[ $idx + 1 ] }; last; } } __PACKAGE__->export_to_level( 1, __PACKAGE__, @imports ); } ### # set up file handles ### # create some private file handles my $output_handle = gensym; my $error_handle = gensym; # and tie them to this package my $out = tie *$output_handle, "Test::Builder::Tester::Tie", "STDOUT"; my $err = tie *$error_handle, "Test::Builder::Tester::Tie", "STDERR"; #### # exported functions #### # for remembering that we're testing and where we're testing at my $testing = 0; my $testing_num; my $original_is_passing; # remembering where the file handles were originally connected my $original_output_handle; my $original_failure_handle; my $original_todo_handle; my $original_formatter; my $original_harness_env; # function that starts testing and redirects the filehandles for now sub _start_testing { # Hack for things that conditioned on Test-Stream being loaded $INC{'Test/Stream.pm'} ||= 'fake' if $INC{'Test/Moose/More.pm'}; # even if we're running under Test::Harness pretend we're not # for now. This needed so Test::Builder doesn't add extra spaces $original_harness_env = $ENV{HARNESS_ACTIVE} || 0; $ENV{HARNESS_ACTIVE} = 0; my $hub = $t->{Hub} || ($t->{Stack} ? $t->{Stack}->top : Test2::API::test2_stack->top); $original_formatter = $hub->format; unless ($original_formatter && $original_formatter->isa('Test::Builder::Formatter')) { my $fmt = Test::Builder::Formatter->new; $hub->format($fmt); } # remember what the handles were set to $original_output_handle = $t->output(); $original_failure_handle = $t->failure_output(); $original_todo_handle = $t->todo_output(); # switch out to our own handles $t->output($output_handle); $t->failure_output($error_handle); $t->todo_output($output_handle); # clear the expected list $out->reset(); $err->reset(); # remember that we're testing $testing = 1; $testing_num = $t->current_test; $t->current_test(0); $original_is_passing = $t->is_passing; $t->is_passing(1); # look, we shouldn't do the ending stuff $t->no_ending(1); } =head2 Functions These are the six methods that are exported as default. =over 4 =item test_out =item test_err Procedures for predeclaring the output that your test suite is expected to produce until C is called. These procedures automatically assume that each line terminates with "\n". So test_out("ok 1","ok 2"); is the same as test_out("ok 1\nok 2"); which is even the same as test_out("ok 1"); test_out("ok 2"); Once C or C (or C or C) have been called, all further output from L will be captured by L. This means that you will not be able perform further tests to the normal output in the normal way until you call C (well, unless you manually meddle with the output filehandles) =cut sub test_out { # do we need to do any setup? _start_testing() unless $testing; $out->expect(@_); } sub test_err { # do we need to do any setup? _start_testing() unless $testing; $err->expect(@_); } =item test_fail Because the standard failure message that L produces whenever a test fails will be a common occurrence in your test error output, and because it has changed between Test::Builder versions, rather than forcing you to call C with the string all the time like so test_err("# Failed test ($0 at line ".line_num(+1).")"); C exists as a convenience function that can be called instead. It takes one argument, the offset from the current line that the line that causes the fail is on. test_fail(+1); This means that the example in the synopsis could be rewritten more simply as: test_out("not ok 1 - foo"); test_fail(+1); fail("foo"); test_test("fail works"); =cut sub test_fail { # do we need to do any setup? _start_testing() unless $testing; # work out what line we should be on my( $package, $filename, $line ) = caller; $line = $line + ( shift() || 0 ); # prevent warnings # expect that on stderr $err->expect("# Failed test ($filename at line $line)"); } =item test_diag As most of the remaining expected output to the error stream will be created by L's C function, L provides a convenience function C that you can use instead of C. The C function prepends comment hashes and spacing to the start and newlines to the end of the expected output passed to it and adds it to the list of expected error output. So, instead of writing test_err("# Couldn't open file"); you can write test_diag("Couldn't open file"); Remember that L's diag function will not add newlines to the end of output and test_diag will. So to check Test::Builder->new->diag("foo\n","bar\n"); You would do test_diag("foo","bar") without the newlines. =cut sub test_diag { # do we need to do any setup? _start_testing() unless $testing; # expect the same thing, but prepended with "# " local $_; $err->expect( map { "# $_" } @_ ); } =item test_test Actually performs the output check testing the tests, comparing the data (with C) that we have captured from L against what was declared with C and C. This takes name/value pairs that effect how the test is run. =over =item title (synonym 'name', 'label') The name of the test that will be displayed after the C or C. =item skip_out Setting this to a true value will cause the test to ignore if the output sent by the test to the output stream does not match that declared with C. =item skip_err Setting this to a true value will cause the test to ignore if the output sent by the test to the error stream does not match that declared with C. =back As a convenience, if only one argument is passed then this argument is assumed to be the name of the test (as in the above examples.) Once C has been run test output will be redirected back to the original filehandles that L was connected to (probably STDOUT and STDERR,) meaning any further tests you run will function normally and cause success/errors for L. =cut sub test_test { # END the hack delete $INC{'Test/Stream.pm'} if $INC{'Test/Stream.pm'} && $INC{'Test/Stream.pm'} eq 'fake'; # decode the arguments as described in the pod my $mess; my %args; if( @_ == 1 ) { $mess = shift } else { %args = @_; $mess = $args{name} if exists( $args{name} ); $mess = $args{title} if exists( $args{title} ); $mess = $args{label} if exists( $args{label} ); } # er, are we testing? croak "Not testing. You must declare output with a test function first." unless $testing; my $hub = $t->{Hub} || Test2::API::test2_stack->top; $hub->format($original_formatter); # okay, reconnect the test suite back to the saved handles $t->output($original_output_handle); $t->failure_output($original_failure_handle); $t->todo_output($original_todo_handle); # restore the test no, etc, back to the original point $t->current_test($testing_num); $testing = 0; $t->is_passing($original_is_passing); # re-enable the original setting of the harness $ENV{HARNESS_ACTIVE} = $original_harness_env; # check the output we've stashed unless( $t->ok( ( $args{skip_out} || $out->check ) && ( $args{skip_err} || $err->check ), $mess ) ) { # print out the diagnostic information about why this # test failed local $_; $t->diag( map { "$_\n" } $out->complaint ) unless $args{skip_out} || $out->check; $t->diag( map { "$_\n" } $err->complaint ) unless $args{skip_err} || $err->check; } } =item line_num A utility function that returns the line number that the function was called on. You can pass it an offset which will be added to the result. This is very useful for working out the correct text of diagnostic functions that contain line numbers. Essentially this is the same as the C<__LINE__> macro, but the C idiom is arguably nicer. =cut sub line_num { my( $package, $filename, $line ) = caller; return $line + ( shift() || 0 ); # prevent warnings } =back In addition to the six exported functions there exists one function that can only be accessed with a fully qualified function call. =over 4 =item color When C is called and the output that your tests generate does not match that which you declared, C will print out debug information showing the two conflicting versions. As this output itself is debug information it can be confusing which part of the output is from C and which was the original output from your original tests. Also, it may be hard to spot things like extraneous whitespace at the end of lines that may cause your test to fail even though the output looks similar. To assist you C can colour the background of the debug information to disambiguate the different types of output. The debug output will have its background coloured green and red. The green part represents the text which is the same between the executed and actual output, the red shows which part differs. The C function determines if colouring should occur or not. Passing it a true or false value will enable or disable colouring respectively, and the function called with no argument will return the current setting. To enable colouring from the command line, you can use the L module like so: perl -Mlib=Text::Builder::Tester::Color test.t Or by including the L module directly in the PERL5LIB. =cut my $color; sub color { $color = shift if @_; $color; } =back =head1 BUGS Test::Builder::Tester does not handle plans well. It has never done anything special with plans. This means that plans from outside Test::Builder::Tester will effect Test::Builder::Tester, worse plans when using Test::Builder::Tester will effect overall testing. At this point there are no plans to fix this bug as people have come to depend on it, and Test::Builder::Tester is now discouraged in favor of C. See L Calls C<< Test::Builder->no_ending >> turning off the ending tests. This is needed as otherwise it will trip out because we've run more tests than we strictly should have and it'll register any failures we had that we were testing for as real failures. The color function doesn't work unless L is compatible with your terminal. Additionally, L must be installed on windows platforms for color output. Bugs (and requests for new features) can be reported to the author though GitHub: L =head1 AUTHOR Copyright Mark Fowler Emark@twoshortplanks.comE 2002, 2004. Some code taken from L and L, written by Michael G Schwern Eschwern@pobox.comE. Hence, those parts Copyright Micheal G Schwern 2001. Used and distributed with permission. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 NOTES Thanks to Richard Clamp Erichardc@unixbeard.netE for letting me use his testing system to try this module out on. =head1 SEE ALSO L, L, L. =cut 1; #################################################################### # Helper class that is used to remember expected and received data package Test::Builder::Tester::Tie; ## # add line(s) to be expected sub expect { my $self = shift; my @checks = @_; foreach my $check (@checks) { $check = $self->_account_for_subtest($check); $check = $self->_translate_Failed_check($check); push @{ $self->{wanted} }, ref $check ? $check : "$check\n"; } } sub _account_for_subtest { my( $self, $check ) = @_; my $hub = $t->{Stack}->top; my $nesting = $hub->isa('Test2::Hub::Subtest') ? $hub->nested : 0; return ref($check) ? $check : (' ' x $nesting) . $check; } sub _translate_Failed_check { my( $self, $check ) = @_; if( $check =~ /\A(.*)# (Failed .*test) \((.*?) at line (\d+)\)\Z(?!\n)/ ) { $check = "/\Q$1\E#\\s+\Q$2\E.*?\\n?.*?\Qat $3\E line \Q$4\E.*\\n?/"; } return $check; } ## # return true iff the expected data matches the got data sub check { my $self = shift; # turn off warnings as these might be undef local $^W = 0; my @checks = @{ $self->{wanted} }; my $got = $self->{got}; foreach my $check (@checks) { $check = "\Q$check\E" unless( $check =~ s,^/(.*)/$,$1, or ref $check ); return 0 unless $got =~ s/^$check//; } return length $got == 0; } ## # a complaint message about the inputs not matching (to be # used for debugging messages) sub complaint { my $self = shift; my $type = $self->type; my $got = $self->got; my $wanted = join '', @{ $self->wanted }; # are we running in colour mode? if(Test::Builder::Tester::color) { # get color eval { require Term::ANSIColor }; unless($@) { eval { require Win32::Console::ANSI } if 'MSWin32' eq $^O; # support color on windows platforms # colours my $green = Term::ANSIColor::color("black") . Term::ANSIColor::color("on_green"); my $red = Term::ANSIColor::color("black") . Term::ANSIColor::color("on_red"); my $reset = Term::ANSIColor::color("reset"); # work out where the two strings start to differ my $char = 0; $char++ while substr( $got, $char, 1 ) eq substr( $wanted, $char, 1 ); # get the start string and the two end strings my $start = $green . substr( $wanted, 0, $char ); my $gotend = $red . substr( $got, $char ) . $reset; my $wantedend = $red . substr( $wanted, $char ) . $reset; # make the start turn green on and off $start =~ s/\n/$reset\n$green/g; # make the ends turn red on and off $gotend =~ s/\n/$reset\n$red/g; $wantedend =~ s/\n/$reset\n$red/g; # rebuild the strings $got = $start . $gotend; $wanted = $start . $wantedend; } } my @got = split "\n", $got; my @wanted = split "\n", $wanted; $got = ""; $wanted = ""; while (@got || @wanted) { my $g = shift @got || ""; my $w = shift @wanted || ""; if ($g ne $w) { if($g =~ s/(\s+)$/ |> /g) { $g .= ($_ eq ' ' ? '_' : '\t') for split '', $1; } if($w =~ s/(\s+)$/ |> /g) { $w .= ($_ eq ' ' ? '_' : '\t') for split '', $1; } $g = "> $g"; $w = "> $w"; } else { $g = " $g"; $w = " $w"; } $got = $got ? "$got\n$g" : $g; $wanted = $wanted ? "$wanted\n$w" : $w; } return "$type is:\n" . "$got\nnot:\n$wanted\nas expected"; } ## # forget all expected and got data sub reset { my $self = shift; %$self = ( type => $self->{type}, got => '', wanted => [], ); } sub got { my $self = shift; return $self->{got}; } sub wanted { my $self = shift; return $self->{wanted}; } sub type { my $self = shift; return $self->{type}; } ### # tie interface ### sub PRINT { my $self = shift; $self->{got} .= join '', @_; } sub TIEHANDLE { my( $class, $type ) = @_; my $self = bless { type => $type }, $class; $self->reset; return $self; } sub READ { } sub READLINE { } sub GETC { } sub FILENO { } 1; PK!è�êH5H5perl5/Test/Builder/IO/Scalar.pmnuÏÃ6Ç$package Test::Builder::IO::Scalar; =head1 NAME Test::Builder::IO::Scalar - A copy of IO::Scalar for Test::Builder =head1 DESCRIPTION This is a copy of L which ships with L to support scalar references as filehandles on Perl 5.6. Newer versions of Perl simply use C's built in support. L can not have dependencies on other modules without careful consideration, so its simply been copied into the distribution. =head1 COPYRIGHT and LICENSE This file came from the "IO-stringy" Perl5 toolkit. Copyright (c) 1996 by Eryq. All rights reserved. Copyright (c) 1999,2001 by ZeeGee Software Inc. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut # This is copied code, I don't care. ##no critic use Carp; use strict; use vars qw($VERSION @ISA); use IO::Handle; use 5.005; ### The package version, both in 1.23 style *and* usable by MakeMaker: $VERSION = "2.114"; ### Inheritance: @ISA = qw(IO::Handle); #============================== =head2 Construction =over 4 =cut #------------------------------ =item new [ARGS...] I Return a new, unattached scalar handle. If any arguments are given, they're sent to open(). =cut sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = bless \do { local *FH }, $class; tie *$self, $class, $self; $self->open(@_); ### open on anonymous by default $self; } sub DESTROY { shift->close; } #------------------------------ =item open [SCALARREF] I Open the scalar handle on a new scalar, pointed to by SCALARREF. If no SCALARREF is given, a "private" scalar is created to hold the file data. Returns the self object on success, undefined on error. =cut sub open { my ($self, $sref) = @_; ### Sanity: defined($sref) or do {my $s = ''; $sref = \$s}; (ref($sref) eq "SCALAR") or croak "open() needs a ref to a scalar"; ### Setup: *$self->{Pos} = 0; ### seek position *$self->{SR} = $sref; ### scalar reference $self; } #------------------------------ =item opened I Is the scalar handle opened on something? =cut sub opened { *{shift()}->{SR}; } #------------------------------ =item close I Disassociate the scalar handle from its underlying scalar. Done automatically on destroy. =cut sub close { my $self = shift; %{*$self} = (); 1; } =back =cut #============================== =head2 Input and output =over 4 =cut #------------------------------ =item flush I No-op, provided for OO compatibility. =cut sub flush { "0 but true" } #------------------------------ =item getc I Return the next character, or undef if none remain. =cut sub getc { my $self = shift; ### Return undef right away if at EOF; else, move pos forward: return undef if $self->eof; substr(${*$self->{SR}}, *$self->{Pos}++, 1); } #------------------------------ =item getline I Return the next line, or undef on end of string. Can safely be called in an array context. Currently, lines are delimited by "\n". =cut sub getline { my $self = shift; ### Return undef right away if at EOF: return undef if $self->eof; ### Get next line: my $sr = *$self->{SR}; my $i = *$self->{Pos}; ### Start matching at this point. ### Minimal impact implementation! ### We do the fast fast thing (no regexps) if using the ### classic input record separator. ### Case 1: $/ is undef: slurp all... if (!defined($/)) { *$self->{Pos} = length $$sr; return substr($$sr, $i); } ### Case 2: $/ is "\n": zoom zoom zoom... elsif ($/ eq "\012") { ### Seek ahead for "\n"... yes, this really is faster than regexps. my $len = length($$sr); for (; $i < $len; ++$i) { last if ord (substr ($$sr, $i, 1)) == 10; } ### Extract the line: my $line; if ($i < $len) { ### We found a "\n": $line = substr ($$sr, *$self->{Pos}, $i - *$self->{Pos} + 1); *$self->{Pos} = $i+1; ### Remember where we finished up. } else { ### No "\n"; slurp the remainder: $line = substr ($$sr, *$self->{Pos}, $i - *$self->{Pos}); *$self->{Pos} = $len; } return $line; } ### Case 3: $/ is ref to int. Do fixed-size records. ### (Thanks to Dominique Quatravaux.) elsif (ref($/)) { my $len = length($$sr); my $i = ${$/} + 0; my $line = substr ($$sr, *$self->{Pos}, $i); *$self->{Pos} += $i; *$self->{Pos} = $len if (*$self->{Pos} > $len); return $line; } ### Case 4: $/ is either "" (paragraphs) or something weird... ### This is Graham's general-purpose stuff, which might be ### a tad slower than Case 2 for typical data, because ### of the regexps. else { pos($$sr) = $i; ### If in paragraph mode, skip leading lines (and update i!): length($/) or (($$sr =~ m/\G\n*/g) and ($i = pos($$sr))); ### If we see the separator in the buffer ahead... if (length($/) ? $$sr =~ m,\Q$/\E,g ### (ordinary sep) TBD: precomp! : $$sr =~ m,\n\n,g ### (a paragraph) ) { *$self->{Pos} = pos $$sr; return substr($$sr, $i, *$self->{Pos}-$i); } ### Else if no separator remains, just slurp the rest: else { *$self->{Pos} = length $$sr; return substr($$sr, $i); } } } #------------------------------ =item getlines I Get all remaining lines. It will croak() if accidentally called in a scalar context. =cut sub getlines { my $self = shift; wantarray or croak("can't call getlines in scalar context!"); my ($line, @lines); push @lines, $line while (defined($line = $self->getline)); @lines; } #------------------------------ =item print ARGS... I Print ARGS to the underlying scalar. B this continues to always cause a seek to the end of the string, but if you perform seek()s and tell()s, it is still safer to explicitly seek-to-end before subsequent print()s. =cut sub print { my $self = shift; *$self->{Pos} = length(${*$self->{SR}} .= join('', @_) . (defined($\) ? $\ : "")); 1; } sub _unsafe_print { my $self = shift; my $append = join('', @_) . $\; ${*$self->{SR}} .= $append; *$self->{Pos} += length($append); 1; } sub _old_print { my $self = shift; ${*$self->{SR}} .= join('', @_) . $\; *$self->{Pos} = length(${*$self->{SR}}); 1; } #------------------------------ =item read BUF, NBYTES, [OFFSET] I Read some bytes from the scalar. Returns the number of bytes actually read, 0 on end-of-file, undef on error. =cut sub read { my $self = $_[0]; my $n = $_[2]; my $off = $_[3] || 0; my $read = substr(${*$self->{SR}}, *$self->{Pos}, $n); $n = length($read); *$self->{Pos} += $n; ($off ? substr($_[1], $off) : $_[1]) = $read; return $n; } #------------------------------ =item write BUF, NBYTES, [OFFSET] I Write some bytes to the scalar. =cut sub write { my $self = $_[0]; my $n = $_[2]; my $off = $_[3] || 0; my $data = substr($_[1], $off, $n); $n = length($data); $self->print($data); return $n; } #------------------------------ =item sysread BUF, LEN, [OFFSET] I Read some bytes from the scalar. Returns the number of bytes actually read, 0 on end-of-file, undef on error. =cut sub sysread { my $self = shift; $self->read(@_); } #------------------------------ =item syswrite BUF, NBYTES, [OFFSET] I Write some bytes to the scalar. =cut sub syswrite { my $self = shift; $self->write(@_); } =back =cut #============================== =head2 Seeking/telling and other attributes =over 4 =cut #------------------------------ =item autoflush I No-op, provided for OO compatibility. =cut sub autoflush {} #------------------------------ =item binmode I No-op, provided for OO compatibility. =cut sub binmode {} #------------------------------ =item clearerr I Clear the error and EOF flags. A no-op. =cut sub clearerr { 1 } #------------------------------ =item eof I Are we at end of file? =cut sub eof { my $self = shift; (*$self->{Pos} >= length(${*$self->{SR}})); } #------------------------------ =item seek OFFSET, WHENCE I Seek to a given position in the stream. =cut sub seek { my ($self, $pos, $whence) = @_; my $eofpos = length(${*$self->{SR}}); ### Seek: if ($whence == 0) { *$self->{Pos} = $pos } ### SEEK_SET elsif ($whence == 1) { *$self->{Pos} += $pos } ### SEEK_CUR elsif ($whence == 2) { *$self->{Pos} = $eofpos + $pos} ### SEEK_END else { croak "bad seek whence ($whence)" } ### Fixup: if (*$self->{Pos} < 0) { *$self->{Pos} = 0 } if (*$self->{Pos} > $eofpos) { *$self->{Pos} = $eofpos } return 1; } #------------------------------ =item sysseek OFFSET, WHENCE I Identical to C, I =cut sub sysseek { my $self = shift; $self->seek (@_); } #------------------------------ =item tell I Return the current position in the stream, as a numeric offset. =cut sub tell { *{shift()}->{Pos} } #------------------------------ =item use_RS [YESNO] I B Obey the current setting of $/, like IO::Handle does? Default is false in 1.x, but cold-welded true in 2.x and later. =cut sub use_RS { my ($self, $yesno) = @_; carp "use_RS is deprecated and ignored; \$/ is always consulted\n"; } #------------------------------ =item setpos POS I Set the current position, using the opaque value returned by C. =cut sub setpos { shift->seek($_[0],0) } #------------------------------ =item getpos I Return the current position in the string, as an opaque object. =cut *getpos = \&tell; #------------------------------ =item sref I Return a reference to the underlying scalar. =cut sub sref { *{shift()}->{SR} } #------------------------------ # Tied handle methods... #------------------------------ # Conventional tiehandle interface: sub TIEHANDLE { ((defined($_[1]) && UNIVERSAL::isa($_[1], __PACKAGE__)) ? $_[1] : shift->new(@_)); } sub GETC { shift->getc(@_) } sub PRINT { shift->print(@_) } sub PRINTF { shift->print(sprintf(shift, @_)) } sub READ { shift->read(@_) } sub READLINE { wantarray ? shift->getlines(@_) : shift->getline(@_) } sub WRITE { shift->write(@_); } sub CLOSE { shift->close(@_); } sub SEEK { shift->seek(@_); } sub TELL { shift->tell(@_); } sub EOF { shift->eof(@_); } sub FILENO { -1 } #------------------------------------------------------------ 1; __END__ =back =cut =head1 WARNINGS Perl's TIEHANDLE spec was incomplete prior to 5.005_57; it was missing support for C, C, and C. Attempting to use these functions with an IO::Scalar will not work prior to 5.005_57. IO::Scalar will not have the relevant methods invoked; and even worse, this kind of bug can lie dormant for a while. If you turn warnings on (via C<$^W> or C), and you see something like this... attempt to seek on unopened filehandle ...then you are probably trying to use one of these functions on an IO::Scalar with an old Perl. The remedy is to simply use the OO version; e.g.: $SH->seek(0,0); ### GOOD: will work on any 5.005 seek($SH,0,0); ### WARNING: will only work on 5.005_57 and beyond =head1 VERSION $Id: Scalar.pm,v 1.6 2005/02/10 21:21:53 dfs Exp $ =head1 AUTHORS =head2 Primary Maintainer David F. Skoll (F). =head2 Principal author Eryq (F). President, ZeeGee Software Inc (F). =head2 Other contributors The full set of contributors always includes the folks mentioned in L. But just the same, special thanks to the following individuals for their invaluable contributions (if I've forgotten or misspelled your name, please email me!): I for contributing C. I for suggesting C. I for finding and fixing the bug in C. I for his offset-using read() and write() implementations. I for his patches to massively improve the performance of C and add C and C. I for stringification and inheritance improvements, and sundry good ideas. I for the IO::Handle inheritance and automatic tie-ing. =head1 SEE ALSO L, which is quite similar but which was designed more-recently and with an IO::Handle-like interface in mind, so you could mix OO- and native-filehandle usage without using tied(). I as of version 2.x, these classes all work like their IO::Handle counterparts, so we have comparable functionality to IO::String. =cut PK!uBµ‡,9,9perl5/Test/Warnings.pmnuÏÃ6Ç$use strict; use warnings; package Test::Warnings; # git description: v0.029-2-g97d1c9f # vim: set ts=8 sts=4 sw=4 tw=115 et : # ABSTRACT: Test for warnings and the lack of them # KEYWORDS: testing tests warnings our $VERSION = '0.030'; use parent 'Exporter'; use Test::Builder; our @EXPORT_OK = qw( allow_warnings allowing_warnings had_no_warnings warnings warning ); our %EXPORT_TAGS = ( all => \@EXPORT_OK ); my $warnings_allowed; my $forbidden_warnings_found; my $done_testing_called; my $no_end_test; my $fail_on_warning; my $report_warnings; my @collected_warnings; sub import { my $class = shift @_; my %names; @names{@_} = (); # END block will check for this status $no_end_test = exists $names{':no_end_test'}; # __WARN__ handler will check for this status $fail_on_warning = exists $names{':fail_on_warning'}; # Collect and report warnings at the end $report_warnings = exists $names{':report_warnings'}; delete @names{qw(:no_end_test :fail_on_warning :report_warnings)}; __PACKAGE__->export_to_level(1, $class, keys %names); } # for testing this module only! my $tb; sub _builder(;$) { if (not @_) { $tb ||= Test::Builder->new; return $tb; } $tb = shift; } my $_orig_warn_handler = $SIG{__WARN__}; $SIG{__WARN__} = sub { if ($warnings_allowed) { Test::Builder->new->note($_[0]); } else { $forbidden_warnings_found++; push @collected_warnings, $_[0] if $report_warnings; # TODO: this doesn't handle blessed coderefs... does anyone care? goto &$_orig_warn_handler if $_orig_warn_handler and ( (ref $_orig_warn_handler eq 'CODE') or ($_orig_warn_handler ne 'DEFAULT' and $_orig_warn_handler ne 'IGNORE' and defined &$_orig_warn_handler)); if ($_[0] =~ /\n$/) { warn $_[0]; } else { require Carp; Carp::carp($_[0]); } _builder->ok(0, 'unexpected warning') if $fail_on_warning; } }; sub warnings(;&) { # if someone manually does warnings->import in the same namespace this is # imported into, this sub will be called. in that case, just return the # string "warnings" so it calls the correct method. if (!@_) { return 'warnings'; } my $code = shift; my @warnings; local $SIG{__WARN__} = sub { push @warnings, shift; }; $code->(); @warnings; } sub warning(&) { my @warnings = &warnings(@_); return @warnings == 1 ? $warnings[0] : \@warnings; } if (Test::Builder->can('done_testing')) { # monkeypatch Test::Builder::done_testing: # check for any forbidden warnings, and record that we have done so # so we do not check again via END no strict 'refs'; my $orig = *{'Test::Builder::done_testing'}{CODE}; no warnings 'redefine'; *{'Test::Builder::done_testing'} = sub { # only do this at the end of all tests, not at the end of a subtest my $builder = _builder; my $in_subtest_sub = $builder->can('in_subtest'); if (not $no_end_test and not ($in_subtest_sub ? $builder->$in_subtest_sub : $builder->parent)) { local $Test::Builder::Level = $Test::Builder::Level + 3; had_no_warnings('no (unexpected) warnings (via done_testing)'); $done_testing_called = 1; } $orig->(@_); }; } END { if (not $no_end_test and not $done_testing_called # skip this if there is no plan and no tests have been run (e.g. # compilation tests of this module!) and (_builder->expected_tests or _builder->current_test > 0) ) { local $Test::Builder::Level = $Test::Builder::Level + 1; had_no_warnings('no (unexpected) warnings (via END block)'); } } # setter sub allow_warnings(;$) { $warnings_allowed = @_ || defined $_[0] ? $_[0] : 1; } # getter sub allowing_warnings() { $warnings_allowed } # call at any time to assert no (unexpected) warnings so far sub had_no_warnings(;$) { _builder->ok(!$forbidden_warnings_found, shift || 'no (unexpected) warnings'); if ($report_warnings and $forbidden_warnings_found) { _builder->diag("Got the following unexpected warnings:"); for my $i (1 .. @collected_warnings) { _builder->diag(" $i: $collected_warnings[ $i - 1 ]"); } } } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Warnings - Test for warnings and the lack of them =head1 VERSION version 0.030 =head1 SYNOPSIS use Test::More; use Test::Warnings; pass('yay!'); done_testing; emits TAP: ok 1 - yay! ok 2 - no (unexpected) warnings (via done_testing) 1..2 and: use Test::More tests => 3; use Test::Warnings 0.005 ':all'; pass('yay!'); like(warning { warn "oh noes!" }, qr/^oh noes/, 'we warned'); emits TAP: ok 1 - yay! ok 2 - we warned ok 3 - no (unexpected) warnings (via END block) 1..3 =head1 DESCRIPTION If you've ever tried to use L to confirm there are no warnings generated by your tests, combined with the convenience of C to not have to declare a L, you'll have discovered that these two features do not play well together, as the test count will be calculated I the warnings test is run, resulting in a TAP error. (See C in this distribution for a demonstration.) This module is intended to be used as a drop-in replacement for L: it also adds an extra test, but runs this test I C calculates the test count, rather than after. It does this by hooking into C as well as via an C block. You can declare a plan, or not, and things will still Just Work. It is actually equivalent to: use Test::NoWarnings 1.04 ':early'; as warnings are still printed normally as they occur. You are safe, and enthusiastically encouraged, to perform a global search-replace of the above with C whether or not your tests have a plan. It can also be used as a replacement for L, if you wish to test the content of expected warnings; read on to find out how. =head1 FUNCTIONS The following functions are available for import (not included by default; you can also get all of them by importing the tag C<:all>): =head2 C<< allow_warnings([bool]) >> - EXPERIMENTAL - MAY BE REMOVED When passed a true value, or no value at all, subsequent warnings will not result in a test failure; when passed a false value, subsequent warnings will result in a test failure. Initial value is C. When warnings are allowed, any warnings will instead be emitted via L. =head2 C - EXPERIMENTAL - MAY BE REMOVED Returns whether we are currently allowing warnings (set by C as described above). =head2 C<< had_no_warnings() >> Tests whether there have been any warnings so far, not preceded by an C call. It is run automatically at the end of all tests, but can also be called manually at any time, as often as desired. =head2 C<< warnings( { code } ) >> Given a code block, runs the block and returns a list of all the (not previously allowed via C) warnings issued within. This lets you test for the presence of warnings that you not only would I, but I be issued. Testing functions are not provided; given the strings returned, you can test these yourself using your favourite testing functions, such as L or L. You can use this construct as a replacement for L: is_deeply( [ warnings { ... } ], [ 'warning message 1', 'warning message 2', ], 'got expected warnings', ); or, to replace L: cmp_deeply( [ warnings { ... } ], bag( # ordering of messages doesn't matter re(qr/warning message 1/), re(qr/warning message 2/), ), 'got expected warnings (in any order)', ); Warnings generated by this code block are I propagated further. However, since they are returned from this function with their filename and line numbers intact, you can re-issue them yourself immediately after calling C, if desired. Note that C will give you a C subroutine in your namespace (most likely C
, if you're writing a test), so you (or things you load) can't subsequently do C<< warnings->import >> -- it will result in the error: "Not enough arguments for Test::Warnings::warnings at ..., near "warnings->import"". To work around this, either use the fully-qualified form (C) or make your calls to the C package first. =head2 C<< warning( { code } ) >> Same as C<< warnings( { code } ) >>, except a scalar is always returned - the single warning produced, if there was one, or an arrayref otherwise -- which can be more convenient to use than C if you are expecting exactly one warning. However, you are advised to capture the result from C into a temp variable so you can dump its value if it doesn't contain what you expect. e.g. with this test: like( warning { foo() }, qr/^this is a warning/, 'got a warning from foo()', ); if you get two warnings (or none) back instead of one, you'll get an arrayref, which will result in an unhelpful test failure message like: # Failed test 'got a warning from foo()' # at t/mytest.t line 10. # 'ARRAY(0xdeadbeef)' # doesn't match '(?^:^this is a warning)' So instead, change your test to: my $warning = warning { foo() }; like( $warning, qr/^this is a warning/, 'got a warning from foo()', ) or diag 'got warning(s): ', explain($warning); =head1 IMPORT OPTIONS =head2 C<:all> Imports all functions listed above =head2 C<:no_end_test> Disables the addition of a C test via C or C =head2 C<:fail_on_warning> =for stopwords unexempted When used, fail immediately when an unexempted warning is generated (as opposed to waiting until L or C is called). I recommend you only turn this option on when debugging a test, to see where a surprise warning is coming from, and rely on the end-of-tests check otherwise. =head2 C<:report_warnings> When used, C will print all the unexempted warning content, in case it had been suppressed earlier by other captures (such as L or L). =head1 CAVEATS =for stopwords smartmatch TODO irc Sometimes new warnings can appear in Perl that should B block installation -- for example, smartmatch was recently deprecated in perl 5.17.11, so now any distribution that uses smartmatch and also tests for warnings cannot be installed under 5.18.0. You might want to consider only making warnings fail tests in an author environment -- you can do this with the L pragma: use if $ENV{AUTHOR_TESTING} || $ENV{RELEASE_TESTING}, 'Test::Warnings'; In future versions of this module, when interfaces are added to test the content of warnings, there will likely be additional sugar available to indicate that warnings should be checked only in author tests (or TODO when not in author testing), but will still provide exported subs. Comments are enthusiastically solicited - drop me an email, write up an RT ticket, or come by C<#perl-qa> on irc! =for stopwords Achtung B This is not a great idea: sub warning_like(&$;$) { my ($code, $pattern, $name) = @_; like( &warning($code), $pattern, $name ); } warning_like( { ... }, qr/foo/, 'foo appears in the warning' ); If the code in the C<{ ... }> is going to warn with a stack trace with the arguments to each subroutine in its call stack (for example via C), the test name, "foo appears in the warning" will itself be matched by the regex (see F). Instead, write this: like( warning { ... }, qr/foo/, 'foo appears in the warning' ); =head1 TO DO (or: POSSIBLE FEATURES COMING IN FUTURE RELEASES) =over =item * C<< allow_warnings(qr/.../) >> - allow some warnings and not others =for stopwords subtest subtests =item * more sophisticated handling in subtests - if we save some state on the L object itself, we can allow warnings in a subtest and then the state will revert when the subtest ends, as well as check for warnings at the end of every subtest via C. =item * sugar for making failures TODO when testing outside an author environment =back =head1 SEE ALSO =for stopwords YANWT =over 4 =item * L =item * L =item * L =item * L - which makes all warnings fatal in tests, hence lessening the need for special warning testing =item * L =item * L =back =head1 SUPPORT Bugs may be submitted through L (or L). There is also a mailing list available for users of this distribution, at L. There is also an irc channel available for users of this distribution, at L on C|irc://irc.perl.org/#perl-qa>. I am also usually active on irc, as 'ether' at C. =head1 AUTHOR Karen Etheridge =head1 CONTRIBUTORS =for stopwords Graham Knop A. Sinan Unur Leon Timmermans Tina Mueller =over 4 =item * Graham Knop =item * A. Sinan Unur =item * Leon Timmermans =item * Tina Mueller =back =head1 COPYRIGHT AND LICENCE This software is copyright (c) 2013 by Karen Etheridge. 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 PK!êM³ãEEperl5/Test/Alien/Build.pmnuÏÃ6Ç$package Test::Alien::Build; use strict; use warnings; use 5.008004; use Exporter qw( import ); use Path::Tiny qw( path ); use Carp qw( croak ); use Test2::API qw( context run_subtest ); use Capture::Tiny qw( capture_merged ); use Alien::Build::Util qw( _mirror ); use List::Util 1.33 qw( any ); use Alien::Build::Temp; our @EXPORT = qw( alienfile alienfile_ok alienfile_skip_if_missing_prereqs alien_download_ok alien_extract_ok alien_build_ok alien_build_clean alien_clean_install alien_install_type_is alien_checkpoint_ok alien_resume_ok alien_subtest alien_rc ); # ABSTRACT: Tools for testing Alien::Build + alienfile our $VERSION = '2.83'; # VERSION my $build; my $build_alienfile; my $build_root; my $build_targ; sub alienfile::targ { $build_targ; } sub alienfile { my($package, $filename, $line) = caller; ($package, $filename, $line) = caller(2) if $package eq __PACKAGE__; $filename = path($filename)->absolute; my %args = @_ == 0 ? (filename => 'alienfile') : @_ % 2 ? ( source => do { '# line '. $line . ' "' . path($filename)->absolute . qq("\n) . $_[0] }) : @_; require alienfile; push @alienfile::EXPORT, 'targ' unless any { /^targ$/ } @alienfile::EXPORT; my $temp = Alien::Build::Temp->newdir; my $get_temp_root = do{ my $root; # may be undef; sub { $root ||= Path::Tiny->new($temp); if(@_) { my $path = $root->child(@_); $path->mkpath; $path; } else { return $root; } }; }; if($args{source}) { my $file = $get_temp_root->()->child('alienfile'); $file->spew_utf8($args{source}); $args{filename} = $file->stringify; } else { unless(defined $args{filename}) { croak "You must specify at least one of filename or source"; } $args{filename} = path($args{filename})->absolute->stringify; } $args{stage} ||= $get_temp_root->('stage')->stringify; $args{prefix} ||= $get_temp_root->('prefix')->stringify; $args{root} ||= $get_temp_root->('root')->stringify; require Alien::Build; _alienfile_clear(); my $out = capture_merged { $build_targ = $args{targ}; $build = Alien::Build->load($args{filename}, root => $args{root}); $build->set_stage($args{stage}); $build->set_prefix($args{prefix}); }; my $ctx = context(); $ctx->note($out) if $out; $ctx->release; $build_alienfile = $args{filename}; $build_root = $temp; $build } sub _alienfile_clear { eval { defined $build_root && -d $build_root && path($build_root)->remove_tree }; undef $build; undef $build_alienfile; undef $build_root; undef $build_targ; } sub alienfile_ok { my $build; my $name; my $error; if(@_ == 1 && ! defined $_[0]) { $build = $_[0]; $error = 'no alienfile given'; $name = 'alienfile compiled'; } elsif(@_ == 1 && eval { $_[0]->isa('Alien::Build') }) { $build = $_[0]; $name = 'alienfile compiled'; } else { $build = eval { alienfile(@_) }; $error = $@; $name = 'alienfile compiles'; } my $ok = !! $build; my $ctx = context(); $ctx->ok($ok, $name); $ctx->diag("error: $error") if $error; $ctx->release; $build; } sub alienfile_skip_if_missing_prereqs { my($phase) = @_; if($build) { eval { $build->load_requires('configure', 1) }; if(my $error = $@) { my $reason = "Missing configure prereq"; if($error =~ /Required (.*) (.*),/) { $reason .= ": $1 $2"; } my $ctx = context(); $ctx->plan(0, SKIP => $reason); $ctx->release; return; } $phase ||= $build->install_type; eval { $build->load_requires($phase, 1) }; if(my $error = $@) { my $reason = "Missing $phase prereq"; if($error =~ /Required (.*) (.*),/) { $reason .= ": $1 $2"; } my $ctx = context(); $ctx->plan(0, SKIP => $reason); $ctx->release; return; } } } sub alien_install_type_is { my($type, $name) = @_; croak "invalid install type" unless defined $type && $type =~ /^(system|share)$/; $name ||= "alien install type is $type"; my $ok = 0; my @diag; if($build) { my($out, $actual) = capture_merged { $build->load_requires('configure'); $build->install_type; }; if($type eq $actual) { $ok = 1; } else { push @diag, "expected install type of $type, but got $actual"; } } else { push @diag, 'no alienfile' } my $ctx = context(); $ctx->ok($ok, $name); $ctx->diag($_) for @diag; $ctx->release; $ok; } sub alien_download_ok { my($name) = @_; $name ||= 'alien download'; my $ok; my $file; my @diag; my @note; if($build) { my($out, $error) = capture_merged { eval { $build->load_requires('configure'); $build->load_requires($build->install_type); $build->download; }; $@; }; if($error) { $ok = 0; push @diag, $out if defined $out; push @diag, "extract threw exception: $error"; } else { $file = $build->install_prop->{download}; if(-d $file || -f $file) { $ok = 1; push @note, $out if defined $out; } else { $ok = 0; push @diag, $out if defined $out; push @diag, 'no file or directory'; } } } else { $ok = 0; push @diag, 'no alienfile'; } my $ctx = context(); $ctx->ok($ok, $name); $ctx->note($_) for @note; $ctx->diag($_) for @diag; $ctx->release; $file; } sub alien_extract_ok { my($archive, $name) = @_; $name ||= $archive ? "alien extraction of $archive" : 'alien extraction'; my $ok; my $dir; my @diag; my @note; if($build) { my($out, $error); ($out, $dir, $error) = capture_merged { my $dir = eval { $build->load_requires('configure'); $build->load_requires($build->install_type); $build->download; $build->extract($archive); }; ($dir, $@); }; if($error) { $ok = 0; push @diag, $out if defined $out; push @diag, "extract threw exception: $error"; } else { if(-d $dir) { $ok = 1; push @note, $out if defined $out; } else { $ok = 0; push @diag, $out if defined $out; push @diag, 'no directory'; } } } else { $ok = 0; push @diag, 'no alienfile'; } my $ctx = context(); $ctx->ok($ok, $name); $ctx->note($_) for @note; $ctx->diag($_) for @diag; $ctx->release; $dir; } my $count = 1; sub alien_build_ok { my $opt = defined $_[0] && ref($_[0]) eq 'HASH' ? shift : { class => 'Alien::Base' }; my($name) = @_; $name ||= 'alien builds okay'; my $ok; my @diag; my @note; my $alien; if($build) { my($out,$error) = capture_merged { eval { $build->load_requires('configure'); $build->load_requires($build->install_type); $build->download; $build->build; }; $@; }; if($error) { $ok = 0; push @diag, $out if defined $out; push @diag, "build threw exception: $error"; } else { $ok = 1; push @note, $out if defined $out; require Alien::Base; my $prefix = $build->runtime_prop->{prefix}; my $stage = $build->install_prop->{stage}; my %prop = %{ $build->runtime_prop }; $prop{distdir} = $prefix; _mirror $stage, $prefix; my $dist_dir = sub { $prefix; }; my $runtime_prop = sub { \%prop; }; $alien = sprintf 'Test::Alien::Build::Faux%04d', $count++; { no strict 'refs'; @{ "${alien}::ISA" } = $opt->{class}; *{ "${alien}::dist_dir" } = $dist_dir; *{ "${alien}::runtime_prop" } = $runtime_prop; } } } else { $ok = 0; push @diag, 'no alienfile'; } my $ctx = context(); $ctx->ok($ok, $name); $ctx->diag($_) for @diag; $ctx->note($_) for @note; $ctx->release; $alien; } sub alien_build_clean { my $ctx = context(); if($build_root) { foreach my $child (path($build_root)->children) { next if $child->basename eq 'prefix'; $ctx->note("clean: rm: $child"); $child->remove_tree; } } else { $ctx->note("no build to clean"); } $ctx->release; } sub alien_clean_install { my($name) = @_; $name ||= "run clean_install"; my $ok; my @diag; my @note; if($build) { my($out,$error) = capture_merged { eval { $build->clean_install; }; $@; }; if($error) { $ok = 0; push @diag, $out if defined $out && $out ne ''; push @diag, "build threw exception: $error"; } else { $ok = 1; push @note, $out if defined $out && $out ne ''; } } else { $ok = 0; push @diag, 'no alienfile'; } my $ctx = context(); $ctx->ok($ok, $name); $ctx->diag($_) for @diag; $ctx->note($_) for @note; $ctx->release; } sub alien_checkpoint_ok { my($name) = @_; $name ||= "alien checkpoint ok"; my $ok; my @diag; if($build) { eval { $build->checkpoint }; if($@) { push @diag, "error in checkpoint: $@"; $ok = 0; } else { $ok = 1; } undef $build; } else { push @diag, "no build to checkpoint"; $ok = 0; } my $ctx = context(); $ctx->ok($ok, $name); $ctx->diag($_) for @diag; $ctx->release; $ok; } sub alien_resume_ok { my($name) = @_; $name ||= "alien resume ok"; my $ok; my @diag; if($build_alienfile && $build_root && !defined $build) { $build = eval { Alien::Build->resume($build_alienfile, "$build_root/root") }; if($@) { push @diag, "error in resume: $@"; $ok = 0; } else { $ok = 1; } } else { if($build) { push @diag, "build has not been checkpointed"; } else { push @diag, "no build to resume"; } $ok = 0; } my $ctx = context(); $ctx->ok($ok, $name); $ctx->diag($_) for @diag; $ctx->release; ($ok && $build) || $ok; } my $alien_rc_root; sub alien_rc { my($code) = @_; croak "passed in undef rc" unless defined $code; croak "looks like you have already defined a rc.pl file" if $ENV{ALIEN_BUILD_RC} ne '-'; my(undef, $filename, $line) = caller; my $code2 = "use strict; use warnings;\n" . '# line ' . $line . ' "' . path($filename)->absolute . "\n$code"; $alien_rc_root ||= Alien::Build::Temp->newdir; my $rc = path($alien_rc_root)->child('rc.pl'); $rc->spew_utf8($code2); $ENV{ALIEN_BUILD_RC} = "$rc"; return 1; } sub alien_subtest { my($name, $code, @args) = @_; _alienfile_clear; my $ctx = context(); my $pass = run_subtest($name, $code, { buffered => 1 }, @args); $ctx->release; _alienfile_clear; $pass; } delete $ENV{$_} for qw( ALIEN_BUILD_LOG ALIEN_BUILD_PRELOAD ALIEN_BUILD_POSTLOAD ALIEN_INSTALL_TYPE PKG_CONFIG_PATH ALIEN_BUILD_PKG_CONFIG ); $ENV{ALIEN_BUILD_RC} = '-'; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien::Build - Tools for testing Alien::Build + alienfile =head1 VERSION version 2.83 =head1 SYNOPSIS use Test2::V0; use Test::Alien::Build; # returns an instance of Alien::Build. my $build = alienfile_ok q{ use alienfile; plugin 'My::Plugin' => ( foo => 1, bar => 'string', ... ); }; alien_build_ok 'builds okay.'; done_testing; =head1 DESCRIPTION This module provides some tools for testing L and L. Outside of L core development, It is probably most useful for L developers. This module also unsets a number of L specific environment variables, in order to make tests reproducible even when overrides are set in different environments. So if you want to test those variables in various states you should explicitly set them in your test script. These variables are unset if they defined: C C C. =head1 FUNCTIONS =head2 alienfile my $build = alienfile; my $build = alienfile q{ use alienfile ... }; my $build = alienfile filename => 'alienfile'; Create a Alien::Build instance from the given L. The first two forms are abbreviations. my $build = alienfile; # is the same as my $build = alienfile filename => 'alienfile'; and my $build = alienfile q{ use alienfile ... }; # is the same as my $build = alienfile source => q{ use alienfile ... }; Except for the second abbreviated form sets the line number before feeding the source into L so that you will get diagnostics with the correct line numbers. =over 4 =item source The source for the alienfile as a string. You must specify one of C or C. =item filename The filename for the alienfile. You must specify one of C or C. =item root The build root. =item stage The staging area for the build. =item prefix The install prefix for the build. =back =head2 alienfile_ok my $build = alienfile_ok; my $build = alienfile_ok q{ use alienfile ... }; my $build = alienfile_ok filename => 'alienfile'; my $build = alienfile_ok $build; Same as C above, except that it runs as a test, and will not throw an exception on failure (it will return undef instead). [version 1.49] As of version 1.49 you can also pass in an already formed instance of L. This allows you to do something like this: subtest 'a subtest' => sub { my $build = alienfile q{ use alienfile; ... }; alienfile_skip_if_missing_prereqs; # skip if alienfile prereqs are missing alienfile_ok $build; # delayed pass/fail for the compile of alienfile }; =head2 alienfile_skip_if_missing_prereqs alienfile_skip_if_missing_prereqs; alienfile_skip_if_missing_prereqs $phase; Skips the test or subtest if the prereqs for the alienfile are missing. If C<$phase> is not given, then either C or C will be detected. =head2 alien_install_type_is alien_install_type_is $type; alien_install_type_is $type, $name; Simple test to see if the install type is what you expect. C<$type> should be one of C or C. =head2 alien_download_ok my $file = alien_download_ok; my $file = alien_download_ok $name; Makes a download attempt and test that a file or directory results. Returns the file or directory if successful. Returns C otherwise. =head2 alien_extract_ok my $dir = alien_extract_ok; my $dir = alien_extract_ok $archive; my $dir = alien_extract_ok $archive, $name; my $dir = alien_extract_ok undef, $name; Makes an extraction attempt and test that a directory results. Returns the directory if successful. Returns C otherwise. =head2 alien_build_ok my $alien = alien_build_ok; my $alien = alien_build_ok $name; my $alien = alien_build_ok { class => $class }; my $alien = alien_build_ok { class => $class }, $name; Runs the download and build stages. Passes if the build succeeds. Returns an instance of L which can be passed into C from L. Returns C if the test fails. Options =over 4 =item class The base class to use for your alien. This is L by default. Should be a subclass of L, or at least adhere to its API. =back =head2 alien_build_clean alien_build_clean; Removes all files with the current build, except for the runtime prefix. This helps test that the final install won't depend on the build files. =head2 alien_clean_install alien_clean_install; Runs C<$build-Eclean_install>, and verifies it did not crash. =head2 alien_checkpoint_ok alien_checkpoint_ok; alien_checkpoint_ok $test_name; Test the checkpoint of a build. =head2 alien_resume_ok alien_resume_ok; alien_resume_ok $test_name; Test a resume a checkpointed build. =head2 alien_rc alien_rc $code; Creates C file in a temp directory and sets ALIEN_BUILD_RC. Useful for testing plugins that should be called from C<~/.alienbuild/rc.pl>. Note that because of the nature of how the C<~/.alienbuild/rc.pl> file works, you can only use this once! =head2 alien_subtest alien_subtest $test_name => sub { ... }; Clear the build object and clear the build object before and after the subtest. =head1 SEE ALSO =over 4 =item L =item L =item L =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!ŠKHppperl5/Test/Alien/Synthetic.pmnuÏÃ6Ç$package Test::Alien::Synthetic; use strict; use warnings; use 5.008004; use Test2::API qw( context ); # ABSTRACT: A mock alien object for testing our $VERSION = '2.83'; # VERSION sub _def ($) { my($val) = @_; defined $val ? $val : '' } sub cflags { _def shift->{cflags} } sub libs { _def shift->{libs} } sub dynamic_libs { @{ shift->{dynamic_libs} || [] } } sub runtime_prop { my($self) = @_; defined $self->{runtime_prop} ? $self->{runtime_prop} : {}; } sub cflags_static { my($self) = @_; defined $self->{cflags_static} ? $self->{cflags_static} : $self->cflags; } sub libs_static { my($self) = @_; defined $self->{libs_static} ? $self->{libs_static} : $self->libs; } sub bin_dir { my $dir = shift->{bin_dir}; defined $dir && -d $dir ? ($dir) : (); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien::Synthetic - A mock alien object for testing =head1 VERSION version 2.83 =head1 SYNOPSIS use Test2::V0; use Test::Alien; my $alien = synthetic { cflags => '-I/foo/bar/include', libs => '-L/foo/bar/lib -lbaz', }; alien_ok $alien; done_testing; =head1 DESCRIPTION This class is used to model a synthetic L class that implements the minimum L interface needed by L. It can be useful if you have a non-L based L distribution that you need to test. B: The name of this class may move in the future, so do not refer to this class name directly. Instead create instances of this class using the L function. =head1 ATTRIBUTES =head2 cflags String containing the compiler flags =head2 cflags_static String containing the static compiler flags =head2 libs String containing the linker and library flags =head2 libs_static String containing the static linker and library flags =head2 dynamic_libs List reference containing the dynamic libraries. =head2 bin_dir Tool binary directory. =head2 runtime_prop Runtime properties. =head1 EXAMPLE Here is a complete example using L which is a non-L based L distribution. use strict; use warnings; use Test2::V0; use Test::Alien; use Alien::Libarchive; my $real = Alien::Libarchive->new; my $alien = synthetic { cflags => scalar $real->cflags, libs => scalar $real->libs, dynamic_libs => [$real->dlls], }; alien_ok $alien; xs_ok do { local $/; }, with_subtest { my($module) = @_; my $ptr = $module->archive_read_new; like $ptr, qr{^[0-9]+$}; $module->archive_read_free($ptr); }; ffi_ok { symbols => [qw( archive_read_new )] }, with_subtest { my($ffi) = @_; my $new = $ffi->function(archive_read_new => [] => 'opaque'); my $free = $ffi->function(archive_read_close => ['opaque'] => 'void'); my $ptr = $new->(); like $ptr, qr{^[0-9]+$}; $free->($ptr); }; done_testing; __DATA__ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include MODULE = TA_MODULE PACKAGE = TA_MODULE void *archive_read_new(class); const char *class; CODE: RETVAL = (void*) archive_read_new(); OUTPUT: RETVAL void archive_read_free(class, ptr); const char *class; void *ptr; CODE: archive_read_free(ptr); =head1 SEE ALSO =over 4 =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!Z�_œœperl5/Test/Alien/CanPlatypus.pmnuÏÃ6Ç$package Test::Alien::CanPlatypus; use strict; use warnings; use 5.008004; use Test2::API qw( context ); # ABSTRACT: Skip a test file unless FFI::Platypus is available our $VERSION = '2.83'; # VERSION sub skip { eval { require FFI::Platypus; 1 } ? undef : 'This test requires FFI::Platypus.'; } sub import { my $skip = __PACKAGE__->skip; return unless defined $skip; my $ctx = context(); $ctx->plan(0, SKIP => $skip); $ctx->release; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien::CanPlatypus - Skip a test file unless FFI::Platypus is available =head1 VERSION version 2.83 =head1 SYNOPSIS use Test::Alien::CanPlatypus; =head1 DESCRIPTION This is just a L plugin that requires that L be available. Otherwise the test will be skipped. =head1 SEE ALSO =over 4 =item L =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!›Ôþ<perl5/Test/Alien/Diag.pmnuÏÃ6Ç$package Test::Alien::Diag; use strict; use warnings; use 5.008004; use Test2::API qw( context ); use Exporter qw( import ); our @EXPORT = qw( alien_diag ); our @EXPORT_OK = @EXPORT; # ABSTRACT: Print out standard diagnostic for Aliens in the test step. our $VERSION = '2.83'; # VERSION my @default_scalar_properties = qw( cflags cflags_static libs libs_static version install_type ); my @default_list_properties = qw( dynamic_libs bin_dir ); sub alien_diag ($@) { my $ctx = context(); my %options = defined $_[-1] && ref($_[-1]) eq 'HASH' ? %{ pop @_ } : (); my @extra_properties = @{ delete $options{properties} || [] }; my @extra_list_properties = @{ delete $options{list_properties} || [] }; my $max = 0; foreach my $alien (@_) { foreach my $name (@default_scalar_properties, @default_list_properties, @extra_properties, @extra_list_properties) { if(eval { $alien->can($name) }) { my $str = "$alien->$name"; if(length($str) > $max) { $max = length($str); } } } } $ctx->diag(''); if(%options) { my @extra = sort keys %options; $ctx->diag("warning: unknown option@{[ @extra > 1 ? 's' : '' ]} for alien_diag: @extra"); $ctx->diag("(you should check for typos or maybe upgrade to a newer version of Alien::Build)"); } foreach my $alien (@_) { $ctx->diag('') for 1..2; my $found = 0; foreach my $name (sort(@default_scalar_properties, @extra_properties)) { if(eval { $alien->can($name) }) { $found++; my $value = $alien->$name; $value = '[undef]' unless defined $value; $ctx->diag(sprintf "%-${max}s = %s", "$alien->$name", $value); } } foreach my $name (sort(@default_list_properties, @extra_list_properties)) { if(eval { $alien->can($name) }) { $found++; my @list = eval { $alien->$name }; next if $@; $ctx->diag(sprintf "%-${max}s = %s", "$alien->$name", $_) for @list; } } $ctx->diag("no diagnostics found for $alien") unless $found; } $ctx->diag('') for 1..2; $ctx->release; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien::Diag - Print out standard diagnostic for Aliens in the test step. =head1 VERSION version 2.83 =head1 SYNOPSIS use Test2::V0; use Test::Alien::Diag qw( alien_diag ); =head1 DESCRIPTION This module provides an C method that prints out diagnostics useful for cpantesters and other bug reports that gives a quick summary of the important settings like C and C. =head1 FUNCTIONS =head2 alien_diag alien_diag @aliens; prints out diagnostics for each given alien. Each alien must be the class name of an alien. [version 2.68] alien_diag @aliens, \%options; Starting with L 2.68, you can provide an option hash to adjust the behavior of C. Valid options are: =over 4 =item properties Additional properties to display in the diagnostic. Useful when you have an L with custom properties defined in the subclass. =item list_properties Additional properties that are returned as a list to display in the diagnostic. Useful when you have an L with customer properties that return a list. =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!ÏÒ›ddperl5/Test/Alien/Run.pmnuÏÃ6Ç$package Test::Alien::Run; use strict; use warnings; use 5.008004; use Test2::API qw( context ); # ABSTRACT: Run object our $VERSION = '2.83'; # VERSION sub out { shift->{out} } sub err { shift->{err} } sub exit { shift->{exit} } sub signal { shift->{sig} } sub success { my($self, $message) = @_; $message ||= 'command succeeded'; my $ok = $self->exit == 0 && $self->signal == 0; $ok = 0 if $self->{fail}; my $ctx = context(); $ctx->ok($ok, $message); unless($ok) { $ctx->diag(" command exited with @{[ $self->exit ]}") if $self->exit; $ctx->diag(" command killed with @{[ $self->signal ]}") if $self->signal; $ctx->diag(" @{[ $self->{fail} ]}") if $self->{fail}; } $ctx->release; $self; } sub exit_is { my($self, $exit, $message) = @_; $message ||= "command exited with value $exit"; my $ok = $self->exit == $exit; my $ctx = context(); $ctx->ok($ok, $message); $ctx->diag(" actual exit value was: @{[ $self->exit ]}") unless $ok; $ctx->release; $self; } sub exit_isnt { my($self, $exit, $message) = @_; $message ||= "command exited with value not $exit"; my $ok = $self->exit != $exit; my $ctx = context(); $ctx->ok($ok, $message); $ctx->diag(" actual exit value was: @{[ $self->exit ]}") unless $ok; $ctx->release; $self; } sub _like { my($self, $regex, $source, $not, $message) = @_; my $ok = $self->{$source} =~ $regex; $ok = !$ok if $not; my $ctx = context(); $ctx->ok($ok, $message); unless($ok) { $ctx->diag(" $source:"); $ctx->diag(" $_") for split /\r?\n/, $self->{$source}; $ctx->diag($not ? ' matches:' : ' does not match:'); $ctx->diag(" $regex"); } $ctx->release; $self; } sub out_like { my($self, $regex, $message) = @_; $message ||= "output matches $regex"; $self->_like($regex, 'out', 0, $message); } sub out_unlike { my($self, $regex, $message) = @_; $message ||= "output does not match $regex"; $self->_like($regex, 'out', 1, $message); } sub err_like { my($self, $regex, $message) = @_; $message ||= "standard error matches $regex"; $self->_like($regex, 'err', 0, $message); } sub err_unlike { my($self, $regex, $message) = @_; $message ||= "standard error does not match $regex"; $self->_like($regex, 'err', 1, $message); } sub note { my($self) = @_; my $ctx = context(); $ctx->note("[cmd]"); $ctx->note(" @{$self->{cmd}}"); if($self->out ne '') { $ctx->note("[out]"); $ctx->note(" $_") for split /\r?\n/, $self->out; } if($self->err ne '') { $ctx->note("[err]"); $ctx->note(" $_") for split /\r?\n/, $self->err; } $ctx->release; $self; } sub diag { my($self) = @_; my $ctx = context(); $ctx->diag("[cmd]"); $ctx->diag(" @{$self->{cmd}}"); if($self->out ne '') { $ctx->diag("[out]"); $ctx->diag(" $_") for split /\r?\n/, $self->out; } if($self->err ne '') { $ctx->diag("[err]"); $ctx->diag(" $_") for split /\r?\n/, $self->err; } $ctx->release; $self; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien::Run - Run object =head1 VERSION version 2.83 =head1 SYNOPSIS use Test2::V0; use Test::Alien; run_ok([ $^X, -e => 'print "some output"; exit 22']) ->exit_is(22) ->out_like(qr{some}); =head1 DESCRIPTION This class stores information about a process run as performed by L. That function is the I way to create an instance of this class. =head1 ATTRIBUTES =head2 out my $str = $run->out; The standard output from the run. =head2 err my $str = $run->err; The standard error from the run. =head2 exit my $int = $run->exit; The exit value of the run. =head2 signal my $int = $run->signal; The signal that killed the run, or zero if the process was terminated normally. =head1 METHODS These methods return the run object itself, so they can be chained, as in the synopsis above. =head2 success $run->success; $run->success($message); Passes if the process terminated normally with an exit value of 0. =head2 exit_is $run->exit_is($exit); $run->exit_is($exit, $message); Passes if the process terminated with the given exit value. =head2 exit_isnt $run->exit_isnt($exit); $run->exit_isnt($exit, $message); Passes if the process terminated with an exit value of anything but the given value. =head2 out_like $run->out_like($regex); $run->out_like($regex, $message); Passes if the output of the run matches the given pattern. =head2 out_unlike $run->out_unlike($regex); $run->out_unlike($regex, $message); Passes if the output of the run does not match the given pattern. =head2 err_like $run->err_like($regex); $run->err_like($regex, $message); Passes if the standard error of the run matches the given pattern. =head2 err_unlike $run->err_unlike($regex); $run->err_unlike($regex, $message); Passes if the standard error of the run does not match the given pattern. =head2 note $run->note; Send the output and standard error as test note. =head2 diag $run->diag; Send the output and standard error as test diagnostic. =head1 SEE ALSO =over 4 =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!t6F™™perl5/Test/Alien/CanCompile.pmnuÏÃ6Ç$package Test::Alien::CanCompile; use strict; use warnings; use 5.008004; use Test2::API qw( context ); # ABSTRACT: Skip a test file unless a C compiler is available our $VERSION = '2.83'; # VERSION sub skip { require ExtUtils::CBuilder; ExtUtils::CBuilder->new->have_compiler ? undef : 'This test requires a compiler.'; } sub import { my $skip = __PACKAGE__->skip; return unless defined $skip; my $ctx = context(); $ctx->plan(0, SKIP => $skip); $ctx->release; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test::Alien::CanCompile - Skip a test file unless a C compiler is available =head1 VERSION version 2.83 =head1 SYNOPSIS use Test::Alien::CanCompile; =head1 DESCRIPTION This is just a L plugin that requires that a compiler be available. Otherwise the test will be skipped. =head1 SEE ALSO =over 4 =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!á<,Pô/ô/perl5/Authen/NTLM.pmnuÏÃ6Ç$#!/usr/local/bin/perl package Authen::NTLM; use strict; use Authen::NTLM::DES; use Authen::NTLM::MD4; use MIME::Base64; use Digest::HMAC_MD5; use vars qw($VERSION @ISA @EXPORT); require Exporter; =head1 NAME Authen::NTLM - An NTLM authentication module =head1 SYNOPSIS use Mail::IMAPClient; use Authen::NTLM; my $imap = Mail::IMAPClient->new(Server=>'imaphost'); ntlm_user($username); ntlm_password($password); $imap->authenticate("NTLM", Authen::NTLM::ntlm); : $imap->logout; ntlm_reset; : or ntlmv2(1); ntlm_user($username); ntlm_host($host); ntlm_password($password); : or my $ntlm = Authen::NTLM-> new( host => $host, user => $username, domain => $domain, password => $password, version => 1, ); $ntlm-> challenge; : $ntlm-> challenge($challenge); =head1 DESCRIPTION This module provides methods to use NTLM authentication. It can be used as an authenticate method with the Mail::IMAPClient module to perform the challenge/response mechanism for NTLM connections or it can be used on its own for NTLM authentication with other protocols (eg. HTTP). The implementation is a direct port of the code from F which, itself, has based its NTLM implementation on F. As such, this code is not especially efficient, however it will still take a fraction of a second to negotiate a login on a PII which is likely to be good enough for most situations. =head2 FUNCTIONS =over 4 =item ntlm_domain() Set the domain to use in the NTLM authentication messages. Returns the new domain. Without an argument, this function returns the current domain entry. =item ntlm_user() Set the username to use in the NTLM authentication messages. Returns the new username. Without an argument, this function returns the current username entry. =item ntlm_password() Set the password to use in the NTLM authentication messages. Returns the new password. Without an argument, this function returns the current password entry. =item ntlm_reset() Resets the NTLM challenge/response state machine so that the next call to C will produce an initial connect message. =item ntlm() Generate a reply to a challenge. The NTLM protocol involves an initial empty challenge from the server requiring a message response containing the username and domain (which may be empty). The first call to C generates this first message ignoring any arguments. The second time it is called, it is assumed that the argument is the challenge string sent from the server. This will contain 8 bytes of data which are used in the DES functions to generate the response authentication strings. The result of the call is the final authentication string. If C is called, then the next call to C will start the process again allowing multiple authentications within an application. =item ntlmv2() Use NTLM v2 authentication. =back =head2 OBJECT API =over =item new %options Creates an object that accepts the following options: C, C, C, C, C. =item challenge [$challenge] If C<$challenge> is not supplied, first-stage challenge string is generated. Otherwise, the third-stage challenge is generated, where C<$challenge> is assumed to be extracted from the second stage of NTLM exchange. The result of the call is the final authentication string. =back =head1 AUTHOR David (Buzz) Bussenschutt - current maintainer Dmitry Karasik - nice ntlmv2 patch, OO extensions. Andrew Hobson - initial ntlmv2 code Mark Bush - perl port Eric S. Raymond - author of fetchmail Andrew Tridgell and Jeremy Allison for SMB/Netbios code =head1 SEE ALSO L, L, L =head1 HISTORY 1.09 - fix CPAN ticket # 70703 1.08 - fix CPAN ticket # 39925 1.07 - not publicly released 1.06 - relicense as GPL+ or Artistic 1.05 - add OO interface by Dmitry Karasik 1.04 - implementation of NTLMv2 by Andrew Hobson/Dmitry Karasik 1.03 - fixes long-standing 1 line bug L - released by David Bussenschutt 9th Aug 2007 1.02 - released by Mark Bush 29th Oct 2001 =cut $VERSION = "1.09"; @ISA = qw(Exporter); @EXPORT = qw(ntlm ntlm_domain ntlm_user ntlm_password ntlm_reset ntlm_host ntlmv2); my $domain = ""; my $user = ""; my $password = ""; my $str_hdr = "vvV"; my $hdr_len = 8; my $ident = "NTLMSSP"; my $msg1_f = 0x0000b207; my $msg1 = "Z8VV"; my $msg1_hlen = 16 + ($hdr_len*2); my $msg2 = "Z8Va${hdr_len}Va8a8a${hdr_len}"; my $msg2_hlen = 12 + $hdr_len + 20 + $hdr_len; my $msg3 = "Z8V"; my $msg3_tl = "V"; my $msg3_hlen = 12 + ($hdr_len*6) + 4; my $state = 0; my $host = ""; my $ntlm_v2 = 0; my $ntlm_v2_msg3_flags = 0x88205; # Domain Name supplied on negotiate use constant NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED => 0x00001000; # Workstation Name supplied on negotiate use constant NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED => 0x00002000; # Try to use NTLMv2 use constant NTLMSSP_NEGOTIATE_NTLM2 => 0x00080000; # Object API sub new { my ( $class, %opt) = @_; for (qw(domain user password host)) { $opt{$_} = "" unless defined $opt{$_}; } $opt{version} ||= 1; return bless { %opt }, $class; } sub challenge { my ( $self, $challenge) = @_; $state = defined $challenge; ($user,$domain,$password,$host) = @{$self}{qw(user domain password host)}; $ntlm_v2 = ($self-> {version} eq '2') ? 1 : 0; return ntlm($challenge); } eval "sub $_ { \$#_ ? \$_[0]->{$_} = \$_[1] : \$_[0]->{$_} }" for qw(user domain password host version); # Function API sub ntlm_domain { if (@_) { $domain = shift; } return $domain; } sub ntlm_user { if (@_) { $user = shift; } return $user; } sub ntlm_password { if (@_) { $password = shift; } return $password; } sub ntlm_reset { $state = 0; } sub ntlmv2 { if (@_) { $ntlm_v2 = shift; } return $ntlm_v2; } sub ntlm_host { if (@_) { $host = shift; } return $host; } sub ntlm { my ($challenge) = @_; my ($flags, $user_hdr, $domain_hdr, $u_off, $d_off, $c_info, $lmResp, $ntResp, $lm_hdr, $nt_hdr, $wks_hdr, $session_hdr, $lm_off, $nt_off, $wks_off, $s_off, $u_user, $msg1_host, $host_hdr, $u_host); my $response; if ($state) { $challenge =~ s/^\s*//; $challenge = decode_base64($challenge); $c_info = &decode_challenge($challenge); $u_user = &unicode($user); if (!$ntlm_v2) { $domain = substr($challenge, $c_info->{domain}{offset}, $c_info->{domain}{len}); $lmResp = &lmEncrypt($c_info->{data}); $ntResp = &ntEncrypt($c_info->{data}); $flags = pack($msg3_tl, $c_info->{flags}); } elsif ($ntlm_v2 eq '1') { $lmResp = &lmv2Encrypt($c_info->{data}); $ntResp = &ntv2Encrypt($c_info->{data}, $c_info->{target_data}); $flags = pack($msg3_tl, $ntlm_v2_msg3_flags); } else { $domain = &unicode($domain);#substr($challenge, $c_info->{domain}{offset}, $c_info->{domain}{len}); $lmResp = &lmEncrypt($c_info->{data}); $ntResp = &ntEncrypt($c_info->{data}); $flags = pack($msg3_tl, $c_info->{flags}); } $u_host = &unicode(($host ? $host : $user)); $response = pack($msg3, $ident, 3); $lm_off = $msg3_hlen; $nt_off = $lm_off + length($lmResp); $d_off = $nt_off + length($ntResp); $u_off = $d_off + length($domain); $wks_off = $u_off + length($u_user); $s_off = $wks_off + length($u_host); $lm_hdr = &hdr($lmResp, $msg3_hlen, $lm_off); $nt_hdr = &hdr($ntResp, $msg3_hlen, $nt_off); $domain_hdr = &hdr($domain, $msg3_hlen, $d_off); $user_hdr = &hdr($u_user, $msg3_hlen, $u_off); $wks_hdr = &hdr($u_host, $msg3_hlen, $wks_off); $session_hdr = &hdr("", $msg3_hlen, $s_off); $response .= $lm_hdr . $nt_hdr . $domain_hdr . $user_hdr . $wks_hdr . $session_hdr . $flags . $lmResp . $ntResp . $domain . $u_user . $u_host; } else # first response; { my $f = $msg1_f; if (!length $domain) { $f &= ~NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED; } $msg1_host = $user; if ($ntlm_v2 and $ntlm_v2 eq '1') { $f &= ~NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED; $f |= NTLMSSP_NEGOTIATE_NTLM2; $msg1_host = ""; } $response = pack($msg1, $ident, 1, $f); $u_off = $msg1_hlen; $d_off = $u_off + length($msg1_host); $host_hdr = &hdr($msg1_host, $msg1_hlen, $u_off); $domain_hdr = &hdr($domain, $msg1_hlen, $d_off); $response .= $host_hdr . $domain_hdr . $msg1_host . $domain; $state = 1; } return encode_base64($response, ""); } sub hdr { my ($string, $h_len, $offset) = @_; my ($res, $len); $len = length($string); if ($string) { $res = pack($str_hdr, $len, $len, $offset); } else { $res = pack($str_hdr, 0, 0, $offset - $h_len); } return $res; } sub decode_challenge { my ($challenge) = @_; my $res; my (@res, @hdr); my $original = $challenge; $res->{buffer} = $msg2_hlen < length $challenge ? substr($challenge, $msg2_hlen) : ''; $challenge = substr($challenge, 0, $msg2_hlen); @res = unpack($msg2, $challenge); $res->{ident} = $res[0]; $res->{type} = $res[1]; @hdr = unpack($str_hdr, $res[2]); $res->{domain}{len} = $hdr[0]; $res->{domain}{maxlen} = $hdr[1]; $res->{domain}{offset} = $hdr[2]; $res->{flags} = $res[3]; $res->{data} = $res[4]; $res->{reserved} = $res[5]; $res->{empty_hdr} = $res[6]; @hdr = unpack($str_hdr, $res[6]); $res->{target}{len} = $hdr[0]; $res->{target}{maxlen} = $hdr[1]; $res->{target}{offset} = $hdr[2]; $res->{target_data} = substr($original, $hdr[2], $hdr[1]); return $res; } sub unicode { my ($string) = @_; my ($reply, $c, $z) = (''); $z = sprintf "%c", 0; foreach $c (split //, $string) { $reply .= $c . $z; } return $reply; } sub NTunicode { my ($string) = @_; my ($reply, $c); foreach $c (map {ord($_)} split(//, $string)) { $reply .= pack("v", $c); } return $reply; } sub lmEncrypt { my ($data) = @_; my $p14 = substr($password, 0, 14); $p14 =~ tr/a-z/A-Z/; $p14 .= "\0"x(14-length($p14)); my $p21 = E_P16($p14); $p21 .= "\0"x(21-length($p21)); my $p24 = E_P24($p21, $data); return $p24; } sub ntEncrypt { my ($data) = @_; my $p21 = &E_md4hash; $p21 .= "\0"x(21-length($p21)); my $p24 = E_P24($p21, $data); return $p24; } sub E_md4hash { my $wpwd = &NTunicode($password); my $p16 = mdfour($wpwd); return $p16; } sub lmv2Encrypt { my ($data) = @_; my $u_pass = &unicode($password); my $ntlm_hash = mdfour($u_pass); my $u_user = &unicode("\U$user\E"); my $u_domain = &unicode("$domain"); my $concat = $u_user . $u_domain; my $hmac = Digest::HMAC_MD5->new($ntlm_hash); $hmac->add($concat); my $ntlm_v2_hash = $hmac->digest; # Firefox seems to use this as its random challenge my $random_challenge = "\0" x 8; my $concat2 = $data . $random_challenge; $hmac = Digest::HMAC_MD5->new($ntlm_v2_hash); $hmac->add(substr($data, 0, 8) . $random_challenge); my $r = $hmac->digest . $random_challenge; return $r; } sub ntv2Encrypt { my ($data, $target) = @_; my $u_pass = &unicode($password); my $ntlm_hash = mdfour($u_pass); my $u_user = &unicode("\U$user\E"); my $u_domain = &unicode("$domain"); my $concat = $u_user . $u_domain; my $hmac = Digest::HMAC_MD5->new($ntlm_hash); $hmac->add($concat); my $ntlm_v2_hash = $hmac->digest; my $zero_long = "\000" x 4; my $sig = pack("H8", "01010000"); my $time = pack("VV", (time + 11644473600) + 10000000); my $rand = "\0" x 8; my $blob = $sig . $zero_long . $time . $rand . $zero_long . $target . $zero_long; $concat = $data . $blob; $hmac = Digest::HMAC_MD5->new($ntlm_v2_hash); $hmac->add($concat); my $d = $hmac->digest; my $r = $d . $blob; return $r; } 1; PK!,c«+ÉÉperl5/Authen/NTLM/MD4.pmnuÏÃ6Ç$#!/usr/local/bin/perl # # This is a partial implentation of the MD4 checksum code. # # NOTE # # The function &add() in this module is required as we need to be # able to add 32bit integers ignoring overflow. The C code this is # based on does this because it uses the underlying hardware to # perform the required addition however we need to be more careful # as Perl will overflow an int and produce a result of 0xffffffff # which is not very useful. The &add() function splits its arguments # into two shorts and adds these carrying overflow from the low short # to the high short and ignoring carry from the high short. Not # exactly efficient, but it works and is fast enough for the purposes # of this implementation # package Authen::NTLM::MD4; use vars qw($VERSION @ISA @EXPORT); require Exporter; $VERSION = "1.02"; @ISA = qw(Exporter); @EXPORT = qw(mdfour); my ($A, $B, $C, $D); my (@X, $M); sub mdfour { my ($in) = @_; my ($i, $pos); my $len = length($in); my $b = $len * 8; $in .= "\0"x128; $A = 0x67452301; $B = 0xefcdab89; $C = 0x98badcfe; $D = 0x10325476; $pos = 0; while ($len > 64) { ©64(substr($in, $pos, 64)); &mdfour64; $pos += 64; $len -= 64; } my $buf = substr($in, $pos, $len); $buf .= sprintf "%c", 0x80; if ($len <= 55) { $buf .= "\0"x(55-$len); $buf .= pack("V", $b); $buf .= "\0"x4; ©64($buf); &mdfour64; } else { $buf .= "\0"x(120-$len); $buf .= pack("V", $b); $buf .= "\0"x4; ©64(substr($buf, 0, 64)); &mdfour64; ©64(substr($buf, 64, 64)); &mdfour64; } my $out = pack("VVVV", $A, $B, $C, $D); return $out; } sub F { my ($X, $Y, $Z) = @_; my $res = ($X&$Y) | ((~$X)&$Z); return $res; } sub G { my ($X, $Y, $Z) = @_; return ($X&$Y) | ($X&$Z) | ($Y&$Z); } sub H { my ($X, $Y, $Z) = @_; return $X^$Y^$Z; } sub lshift { my ($x, $s) = @_; $x &= 0xffffffff; return (($x<<$s)&0xffffffff) | ($x>>(32-$s)); } sub ROUND1 { my ($a, $b, $c, $d, $k, $s) = @_; my $e = &add($a, &F($b, $c, $d), $X[$k]); return &lshift($e, $s); } sub ROUND2 { my ($a, $b, $c, $d, $k, $s) = @_; my $e = &add($a, &G($b, $c, $d), $X[$k], 0x5a827999); return &lshift($e, $s); } sub ROUND3 { my ($a, $b, $c, $d, $k, $s) = @_; my $e = &add($a, &H($b, $c, $d), $X[$k], 0x6ed9eba1); return &lshift($e, $s); } sub mdfour64 { my ($i, $AA, $BB, $CC, $DD); @X = unpack("N16", $M); $AA = $A; $BB = $B; $CC = $C; $DD = $D; $A = &ROUND1($A,$B,$C,$D, 0, 3); $D = &ROUND1($D,$A,$B,$C, 1, 7); $C = &ROUND1($C,$D,$A,$B, 2,11); $B = &ROUND1($B,$C,$D,$A, 3,19); $A = &ROUND1($A,$B,$C,$D, 4, 3); $D = &ROUND1($D,$A,$B,$C, 5, 7); $C = &ROUND1($C,$D,$A,$B, 6,11); $B = &ROUND1($B,$C,$D,$A, 7,19); $A = &ROUND1($A,$B,$C,$D, 8, 3); $D = &ROUND1($D,$A,$B,$C, 9, 7); $C = &ROUND1($C,$D,$A,$B,10,11); $B = &ROUND1($B,$C,$D,$A,11,19); $A = &ROUND1($A,$B,$C,$D,12, 3); $D = &ROUND1($D,$A,$B,$C,13, 7); $C = &ROUND1($C,$D,$A,$B,14,11); $B = &ROUND1($B,$C,$D,$A,15,19); $A = &ROUND2($A,$B,$C,$D, 0, 3); $D = &ROUND2($D,$A,$B,$C, 4, 5); $C = &ROUND2($C,$D,$A,$B, 8, 9); $B = &ROUND2($B,$C,$D,$A,12,13); $A = &ROUND2($A,$B,$C,$D, 1, 3); $D = &ROUND2($D,$A,$B,$C, 5, 5); $C = &ROUND2($C,$D,$A,$B, 9, 9); $B = &ROUND2($B,$C,$D,$A,13,13); $A = &ROUND2($A,$B,$C,$D, 2, 3); $D = &ROUND2($D,$A,$B,$C, 6, 5); $C = &ROUND2($C,$D,$A,$B,10, 9); $B = &ROUND2($B,$C,$D,$A,14,13); $A = &ROUND2($A,$B,$C,$D, 3, 3); $D = &ROUND2($D,$A,$B,$C, 7, 5); $C = &ROUND2($C,$D,$A,$B,11, 9); $B = &ROUND2($B,$C,$D,$A,15,13); $A = &ROUND3($A,$B,$C,$D, 0, 3); $D = &ROUND3($D,$A,$B,$C, 8, 9); $C = &ROUND3($C,$D,$A,$B, 4,11); $B = &ROUND3($B,$C,$D,$A,12,15); $A = &ROUND3($A,$B,$C,$D, 2, 3); $D = &ROUND3($D,$A,$B,$C,10, 9); $C = &ROUND3($C,$D,$A,$B, 6,11); $B = &ROUND3($B,$C,$D,$A,14,15); $A = &ROUND3($A,$B,$C,$D, 1, 3); $D = &ROUND3($D,$A,$B,$C, 9, 9); $C = &ROUND3($C,$D,$A,$B, 5,11); $B = &ROUND3($B,$C,$D,$A,13,15); $A = &ROUND3($A,$B,$C,$D, 3, 3); $D = &ROUND3($D,$A,$B,$C,11, 9); $C = &ROUND3($C,$D,$A,$B, 7,11); $B = &ROUND3($B,$C,$D,$A,15,15); $A = &add($A, $AA); $B = &add($B, $BB); $C = &add($C, $CC); $D = &add($D, $DD); $A &= 0xffffffff; $B &= 0xffffffff; $C &= 0xffffffff; $D &= 0xffffffff; map {$_ = 0} @X; } sub copy64 { my ($in) = @_; $M = pack("V16", unpack("N16", $in)); } # see note at top of this file about this function sub add { my (@nums) = @_; my ($r_low, $r_high, $n_low, $l_high); my $num; $r_low = $r_high = 0; foreach $num (@nums) { $n_low = $num & 0xffff; $n_high = ($num&0xffff0000)>>16; $r_low += $n_low; ($r_low&0xf0000) && $r_high++; $r_low &= 0xffff; $r_high += $n_high; $r_high &= 0xffff; } return ($r_high<<16)|$r_low; } 1; PK!+ùrM[[perl5/Authen/NTLM/DES.pmnuÏÃ6Ç$#!/usr/local/bin/perl # # This is an implementation of part of the DES specification. According # to the code this is ported from, this code does NOT enable 2-way # encryption and is, hence, not a cypher and does not appear to come # under any export restrictions on such. # package Authen::NTLM::DES; use vars qw($VERSION @ISA @EXPORT); require Exporter; $VERSION = "1.02"; @ISA = qw(Exporter); @EXPORT = qw(E_P16 E_P24); my ($loop, $loop2); $loop = 0; $loop2 = 0; my $perm1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4]; my $perm2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32]; my $perm3 = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]; my $perm4 = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1]; my $perm5 = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25]; my $perm6 = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25]; my $sc = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]; my $sbox = [ [ [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13] ], [ [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9] ], [ [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12] ], [ [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14] ], [ [2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9], [14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6], [4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14], [11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3] ], [ [12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11], [10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8], [9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6], [4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13] ], [ [4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1], [13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6], [1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2], [6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12] ], [ [13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7], [1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2], [7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8], [2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11] ] ]; sub E_P16 { my ($p14) = @_; my $sp8 = [0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25]; my $p7 = substr($p14, 0, 7); my $p16 = smbhash($sp8, $p7); $p7 = substr($p14, 7, 7); $p16 .= smbhash($sp8, $p7); return $p16; } sub E_P24 { my ($p21, $c8_str) = @_; my @c8 = map {ord($_)} split(//, $c8_str); my $p24 = smbhash(\@c8, substr($p21, 0, 7)); $p24 .= smbhash(\@c8, substr($p21, 7, 7)); $p24 .= smbhash(\@c8, substr($p21, 14, 7)); } sub permute { my ($out, $in, $p, $n) = @_; my $i; foreach $i (0..($n-1)) { $out->[$i] = $in->[$p->[$i]-1]; } } sub lshift { my ($d, $count, $n) = @_; my (@out, $i); foreach $i (0..($n-1)) { $out[$i] = $d->[($i+$count)%$n]; } foreach $i (0..($n-1)) { $d->[$i] = $out[$i]; } } sub xor { my ($out, $in1, $in2, $n) = @_; my $i; foreach $i (0..($n-1)) { $out->[$i] = $in1->[$i]^$in2->[$i]; } } sub dohash { my ($out, $in, $key) = @_; my ($i, $j, $k, @pk1, @c, @d, @cd, @ki, @pd1, @l, @r, @rl); &permute(\@pk1, $key, $perm1, 56); foreach $i (0..27) { $c[$i] = $pk1[$i]; $d[$i] = $pk1[$i+28]; } foreach $i (0..15) { my @array; &lshift(\@c, $sc->[$i], 28); &lshift(\@d, $sc->[$i], 28); @cd = (@c, @d); &permute(\@array, \@cd, $perm2, 48); $ki[$i] = \@array; } &permute(\@pd1, $in, $perm3, 64); foreach $j (0..31) { $l[$j] = $pd1[$j]; $r[$j] = $pd1[$j+32]; } foreach $i (0..15) { local (@er, @erk, @b, @cb, @pcb, @r2); permute(\@er, \@r, $perm4, 48); &xor(\@erk, \@er, $ki[$i], 48); foreach $j (0..7) { foreach $k (0..5) { $b[$j][$k] = $erk[$j*6+$k]; } } foreach $j (0..7) { local ($m, $n); $m = ($b[$j][0]<<1) | $b[$j][5]; $n = ($b[$j][1]<<3) | ($b[$j][2]<<2) | ($b[$j][3]<<1) | $b[$j][4]; foreach $k (0..3) { $b[$j][$k] = ($sbox->[$j][$m][$n] & (1<<(3-$k)))? 1: 0; } } foreach $j (0..7) { foreach $k (0..3) { $cb[$j*4+$k] = $b[$j][$k]; } } &permute(\@pcb, \@cb, $perm5, 32); &xor(\@r2, \@l, \@pcb, 32); foreach $j (0..31) { $l[$j] = $r[$j]; $r[$j] = $r2[$j]; } } @rl = (@r, @l); &permute($out, \@rl, $perm6, 64); } sub str_to_key { my ($str) = @_; my $i; my @key; my $out; my @str = map {ord($_)} split(//, $str); $key[0] = $str[0]>>1; $key[1] = (($str[0]&0x01)<<6) | ($str[1]>>2); $key[2] = (($str[1]&0x03)<<5) | ($str[2]>>3); $key[3] = (($str[2]&0x07)<<4) | ($str[3]>>4); $key[4] = (($str[3]&0x0f)<<3) | ($str[4]>>5); $key[5] = (($str[4]&0x1f)<<2) | ($str[5]>>6); $key[6] = (($str[5]&0x3f)<<1) | ($str[6]>>7); $key[7] = $str[6]&0x7f; foreach $i (0..7) { $key[$i] = 0xff&($key[$i]<<1); } return \@key; } sub smbhash { my ($in, $key) = @_; my $key2 = &str_to_key($key); my ($i, $div, $mod, @in, @outb, @inb, @keyb, @out); foreach $i (0..63) { $div = int($i/8); $mod = $i%8; $inb[$i] = ($in->[$div] & (1<<(7-($mod))))? 1: 0; $keyb[$i] = ($key2->[$div] & (1<<(7-($mod))))? 1: 0; $outb[$i] = 0; } &dohash(\@outb, \@inb, \@keyb); foreach $i (0..7) { $out[$i] = 0; } foreach $i (0..63) { $out[int($i/8)] |= (1<<(7-($i%8))) if ($outb[$i]); } my $out = pack("C8", @out); return $out; } 1; PK!0“òÿQ4Q4perl5/HTTP/Status.pmnuÏÃ6Ç$package HTTP::Status; use strict; use warnings; our $VERSION = '6.26'; require 5.002; # because we use prototypes use base 'Exporter'; our @EXPORT = qw(is_info is_success is_redirect is_error status_message); our @EXPORT_OK = qw(is_client_error is_server_error is_cacheable_by_default); # Note also addition of mnemonics to @EXPORT below # Unmarked codes are from RFC 7231 (2017-12-20) # See also: # https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml my %StatusCode = ( 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', # RFC 2518: WebDAV 103 => 'Early Hints', # RFC 8297: Indicating Hints # 104 .. 199 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', # RFC 7233: Range Requests 207 => 'Multi-Status', # RFC 4918: WebDAV 208 => 'Already Reported', # RFC 5842: WebDAV bindings # 209 .. 225 226 => 'IM Used', # RFC 3229: Delta encoding # 227 .. 299 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', # RFC 7232: Conditional Request 305 => 'Use Proxy', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', # RFC 7528: Permanent Redirect # 309 .. 399 400 => 'Bad Request', 401 => 'Unauthorized', # RFC 7235: Authentication 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', # RFC 7235: Authentication 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', # RFC 7232: Conditional Request 413 => 'Payload Too Large', 414 => 'URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Range Not Satisfiable', # RFC 7233: Range Requests 417 => 'Expectation Failed', # 418 .. 420 421 => 'Misdirected Request', # RFC 7540: HTTP/2 422 => 'Unprocessable Entity', # RFC 4918: WebDAV 423 => 'Locked', # RFC 4918: WebDAV 424 => 'Failed Dependency', # RFC 4918: WebDAV 425 => 'Too Early', # RFC 8470: Using Early Data in HTTP 426 => 'Upgrade Required', # 427 428 => 'Precondition Required', # RFC 6585: Additional Codes 429 => 'Too Many Requests', # RFC 6585: Additional Codes # 430 431 => 'Request Header Fields Too Large', # RFC 6585: Additional Codes # 432 .. 450 451 => 'Unavailable For Legal Reasons', # RFC 7725: Legal Obstacles # 452 .. 499 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', # RFC 2295: Transparant Ngttn 507 => 'Insufficient Storage', # RFC 4918: WebDAV 508 => 'Loop Detected', # RFC 5842: WebDAV bindings # 509 510 => 'Not Extended', # RFC 2774: Extension Framework 511 => 'Network Authentication Required', # RFC 6585: Additional Codes ); # keep some unofficial codes that used to be in this distribution %StatusCode = ( %StatusCode, 418 => 'I\'m a teapot', # RFC 2324: HTCPC/1.0 1-april 449 => 'Retry with', # microsoft 509 => 'Bandwidth Limit Exceeded', # Apache / cPanel ); my $mnemonicCode = ''; my ($code, $message); while (($code, $message) = each %StatusCode) { # create mnemonic subroutines $message =~ s/I'm/I am/; $message =~ tr/a-z \-/A-Z__/; $mnemonicCode .= "sub HTTP_$message () { $code }\n"; $mnemonicCode .= "*RC_$message = \\&HTTP_$message;\n"; # legacy $mnemonicCode .= "push(\@EXPORT_OK, 'HTTP_$message');\n"; $mnemonicCode .= "push(\@EXPORT, 'RC_$message');\n"; } eval $mnemonicCode; # only one eval for speed die if $@; # backwards compatibility *RC_MOVED_TEMPORARILY = \&RC_FOUND; # 302 was renamed in the standard push(@EXPORT, "RC_MOVED_TEMPORARILY"); *RC_REQUEST_ENTITY_TOO_LARGE = \&RC_PAYLOAD_TOO_LARGE; push(@EXPORT, "RC_REQUEST_ENTITY_TOO_LARGE"); *RC_REQUEST_URI_TOO_LARGE = \&RC_URI_TOO_LONG; push(@EXPORT, "RC_REQUEST_URI_TOO_LARGE"); *RC_REQUEST_RANGE_NOT_SATISFIABLE = \&RC_RANGE_NOT_SATISFIABLE; push(@EXPORT, "RC_REQUEST_RANGE_NOT_SATISFIABLE"); *RC_NO_CODE = \&RC_TOO_EARLY; push(@EXPORT, "RC_NO_CODE"); *RC_UNORDERED_COLLECTION = \&RC_TOO_EARLY; push(@EXPORT, "RC_UNORDERED_COLLECTION"); *HTTP_REQUEST_ENTITY_TOO_LARGE = \&HTTP_PAYLOAD_TOO_LARGE; push(@EXPORT_OK, "HTTP_REQUEST_ENTITY_TOO_LARGE"); *HTTP_REQUEST_URI_TOO_LARGE = \&HTTP_URI_TOO_LONG; push(@EXPORT_OK, "HTTP_REQUEST_URI_TOO_LARGE"); *HTTP_REQUEST_RANGE_NOT_SATISFIABLE = \&HTTP_RANGE_NOT_SATISFIABLE; push(@EXPORT_OK, "HTTP_REQUEST_RANGE_NOT_SATISFIABLE"); *HTTP_NO_CODE = \&HTTP_TOO_EARLY; push(@EXPORT_OK, "HTTP_NO_CODE"); *HTTP_UNORDERED_COLLECTION = \&HTTP_TOO_EARLY; push(@EXPORT_OK, "HTTP_UNORDERED_COLLECTION"); our %EXPORT_TAGS = ( constants => [grep /^HTTP_/, @EXPORT_OK], is => [grep /^is_/, @EXPORT, @EXPORT_OK], ); sub status_message ($) { $StatusCode{$_[0]}; } sub is_info ($) { $_[0] && $_[0] >= 100 && $_[0] < 200; } sub is_success ($) { $_[0] && $_[0] >= 200 && $_[0] < 300; } sub is_redirect ($) { $_[0] && $_[0] >= 300 && $_[0] < 400; } sub is_error ($) { $_[0] && $_[0] >= 400 && $_[0] < 600; } sub is_client_error ($) { $_[0] && $_[0] >= 400 && $_[0] < 500; } sub is_server_error ($) { $_[0] && $_[0] >= 500 && $_[0] < 600; } sub is_cacheable_by_default ($) { $_[0] && ( $_[0] == 200 # OK || $_[0] == 203 # Non-Authoritative Information || $_[0] == 204 # No Content || $_[0] == 206 # Not Acceptable || $_[0] == 300 # Multiple Choices || $_[0] == 301 # Moved Permanently || $_[0] == 404 # Not Found || $_[0] == 405 # Method Not Allowed || $_[0] == 410 # Gone || $_[0] == 414 # Request-URI Too Large || $_[0] == 451 # Unavailable For Legal Reasons || $_[0] == 501 # Not Implemented ); } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Status - HTTP Status code processing =head1 VERSION version 6.26 =head1 SYNOPSIS use HTTP::Status qw(:constants :is status_message); if ($rc != HTTP_OK) { print status_message($rc), "\n"; } if (is_success($rc)) { ... } if (is_error($rc)) { ... } if (is_redirect($rc)) { ... } =head1 DESCRIPTION I is a library of routines for defining and classifying HTTP status codes for libwww-perl. Status codes are used to encode the overall outcome of an HTTP response message. Codes correspond to those defined in RFC 2616 and RFC 2518. =head1 CONSTANTS The following constant functions can be used as mnemonic status code names. None of these are exported by default. Use the C<:constants> tag to import them all. HTTP_CONTINUE (100) HTTP_SWITCHING_PROTOCOLS (101) HTTP_PROCESSING (102) HTTP_EARLY_HINTS (103) HTTP_OK (200) HTTP_CREATED (201) HTTP_ACCEPTED (202) HTTP_NON_AUTHORITATIVE_INFORMATION (203) HTTP_NO_CONTENT (204) HTTP_RESET_CONTENT (205) HTTP_PARTIAL_CONTENT (206) HTTP_MULTI_STATUS (207) HTTP_ALREADY_REPORTED (208) HTTP_IM_USED (226) HTTP_MULTIPLE_CHOICES (300) HTTP_MOVED_PERMANENTLY (301) HTTP_FOUND (302) HTTP_SEE_OTHER (303) HTTP_NOT_MODIFIED (304) HTTP_USE_PROXY (305) HTTP_TEMPORARY_REDIRECT (307) HTTP_PERMANENT_REDIRECT (308) HTTP_BAD_REQUEST (400) HTTP_UNAUTHORIZED (401) HTTP_PAYMENT_REQUIRED (402) HTTP_FORBIDDEN (403) HTTP_NOT_FOUND (404) HTTP_METHOD_NOT_ALLOWED (405) HTTP_NOT_ACCEPTABLE (406) HTTP_PROXY_AUTHENTICATION_REQUIRED (407) HTTP_REQUEST_TIMEOUT (408) HTTP_CONFLICT (409) HTTP_GONE (410) HTTP_LENGTH_REQUIRED (411) HTTP_PRECONDITION_FAILED (412) HTTP_PAYLOAD_TOO_LARGE (413) HTTP_URI_TOO_LONG (414) HTTP_UNSUPPORTED_MEDIA_TYPE (415) HTTP_RANGE_NOT_SATISFIABLE (416) HTTP_EXPECTATION_FAILED (417) HTTP_MISDIRECTED REQUEST (421) HTTP_UNPROCESSABLE_ENTITY (422) HTTP_LOCKED (423) HTTP_FAILED_DEPENDENCY (424) HTTP_TOO_EARLY (425) HTTP_UPGRADE_REQUIRED (426) HTTP_PRECONDITION_REQUIRED (428) HTTP_TOO_MANY_REQUESTS (429) HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE (431) HTTP_UNAVAILABLE_FOR_LEGAL_REASONS (451) HTTP_INTERNAL_SERVER_ERROR (500) HTTP_NOT_IMPLEMENTED (501) HTTP_BAD_GATEWAY (502) HTTP_SERVICE_UNAVAILABLE (503) HTTP_GATEWAY_TIMEOUT (504) HTTP_HTTP_VERSION_NOT_SUPPORTED (505) HTTP_VARIANT_ALSO_NEGOTIATES (506) HTTP_INSUFFICIENT_STORAGE (507) HTTP_LOOP_DETECTED (508) HTTP_NOT_EXTENDED (510) HTTP_NETWORK_AUTHENTICATION_REQUIRED (511) =head1 FUNCTIONS The following additional functions are provided. Most of them are exported by default. The C<:is> import tag can be used to import all the classification functions. =over 4 =item status_message( $code ) The status_message() function will translate status codes to human readable strings. The string is the same as found in the constant names above. If the $code is not registered in the L then C is returned. =item is_info( $code ) Return TRUE if C<$code> is an I status code (1xx). This class of status code indicates a provisional response which can't have any content. =item is_success( $code ) Return TRUE if C<$code> is a I status code (2xx). =item is_redirect( $code ) Return TRUE if C<$code> is a I status code (3xx). This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. =item is_error( $code ) Return TRUE if C<$code> is an I status code (4xx or 5xx). The function returns TRUE for both client and server error status codes. =item is_client_error( $code ) Return TRUE if C<$code> is a I status code (4xx). This class of status code is intended for cases in which the client seems to have erred. This function is B exported by default. =item is_server_error( $code ) Return TRUE if C<$code> is a I status code (5xx). This class of status codes is intended for cases in which the server is aware that it has erred or is incapable of performing the request. This function is B exported by default. =item is_cacheable_by_default( $code ) Return TRUE if C<$code> indicates that a response is cacheable by default, and it can be reused by a cache with heuristic expiration. All other status codes are not cacheable by default. See L. This function is B exported by default. =back =head1 SEE ALSO L =head1 BUGS For legacy reasons all the C constants are exported by default with the prefix C. It's recommended to use explicit imports and the C<:constants> tag instead of relying on this. =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: HTTP Status code processing PK!À—Ѥð"ð"perl5/HTTP/Request.pmnuÏÃ6Ç$package HTTP::Request; use strict; use warnings; our $VERSION = '6.26'; use base 'HTTP::Message'; sub new { my($class, $method, $uri, $header, $content) = @_; my $self = $class->SUPER::new($header, $content); $self->method($method); $self->uri($uri); $self; } sub parse { my($class, $str) = @_; Carp::carp('Undefined argument to parse()') if $^W && ! defined $str; my $request_line; if (defined $str && $str =~ s/^(.*)\n//) { $request_line = $1; } else { $request_line = $str; $str = ""; } my $self = $class->SUPER::parse($str); if (defined $request_line) { my($method, $uri, $protocol) = split(' ', $request_line); $self->method($method); $self->uri($uri) if defined($uri); $self->protocol($protocol) if $protocol; } $self; } sub clone { my $self = shift; my $clone = bless $self->SUPER::clone, ref($self); $clone->method($self->method); $clone->uri($self->uri); $clone; } sub method { shift->_elem('_method', @_); } sub uri { my $self = shift; my $old = $self->{'_uri'}; if (@_) { my $uri = shift; if (!defined $uri) { # that's ok } elsif (ref $uri) { Carp::croak("A URI can't be a " . ref($uri) . " reference") if ref($uri) eq 'HASH' or ref($uri) eq 'ARRAY'; Carp::croak("Can't use a " . ref($uri) . " object as a URI") unless $uri->can('scheme') && $uri->can('canonical'); $uri = $uri->clone; unless ($HTTP::URI_CLASS eq "URI") { # Argh!! Hate this... old LWP legacy! eval { local $SIG{__DIE__}; $uri = $uri->abs; }; die $@ if $@ && $@ !~ /Missing base argument/; } } else { $uri = $HTTP::URI_CLASS->new($uri); } $self->{'_uri'} = $uri; delete $self->{'_uri_canonical'}; } $old; } *url = \&uri; # legacy sub uri_canonical { my $self = shift; my $uri = $self->{_uri}; if (defined (my $canon = $self->{_uri_canonical})) { # early bailout if these are the exact same string; try to use # the cheapest comparison method possible return $canon if $$canon eq $$uri; } # otherwise we need to refresh the memoized value $self->{_uri_canonical} = $uri->canonical; } sub accept_decodable { my $self = shift; $self->header("Accept-Encoding", scalar($self->decodable)); } sub as_string { my $self = shift; my($eol) = @_; $eol = "\n" unless defined $eol; my $req_line = $self->method || "-"; my $uri = $self->uri; $uri = (defined $uri) ? $uri->as_string : "-"; $req_line .= " $uri"; my $proto = $self->protocol; $req_line .= " $proto" if $proto; return join($eol, $req_line, $self->SUPER::as_string(@_)); } sub dump { my $self = shift; my @pre = ($self->method || "-", $self->uri || "-"); if (my $prot = $self->protocol) { push(@pre, $prot); } return $self->SUPER::dump( preheader => join(" ", @pre), @_, ); } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Request - HTTP style request message =head1 VERSION version 6.26 =head1 SYNOPSIS require HTTP::Request; $request = HTTP::Request->new(GET => 'http://www.example.com/'); and usually used like this: $ua = LWP::UserAgent->new; $response = $ua->request($request); =head1 DESCRIPTION C is a class encapsulating HTTP style requests, consisting of a request line, some headers, and a content body. Note that the LWP library uses HTTP style requests even for non-HTTP protocols. Instances of this class are usually passed to the request() method of an C object. C is a subclass of C and therefore inherits its methods. The following additional methods are available: =over 4 =item $r = HTTP::Request->new( $method, $uri ) =item $r = HTTP::Request->new( $method, $uri, $header ) =item $r = HTTP::Request->new( $method, $uri, $header, $content ) Constructs a new C object describing a request on the object $uri using method $method. The $method argument must be a string. The $uri argument can be either a string, or a reference to a C object. The optional $header argument should be a reference to an C object or a plain array reference of key/value pairs. The optional $content argument should be a string of bytes. =item $r = HTTP::Request->parse( $str ) This constructs a new request object by parsing the given string. =item $r->method =item $r->method( $val ) This is used to get/set the method attribute. The method should be a short string like "GET", "HEAD", "PUT", "PATCH" or "POST". =item $r->uri =item $r->uri( $val ) This is used to get/set the uri attribute. The $val can be a reference to a URI object or a plain string. If a string is given, then it should be parsable as an absolute URI. =item $r->header( $field ) =item $r->header( $field => $value ) This is used to get/set header values and it is inherited from C via C. See L for details and other similar methods that can be used to access the headers. =item $r->accept_decodable This will set the C header to the list of encodings that decoded_content() can decode. =item $r->content =item $r->content( $bytes ) This is used to get/set the content and it is inherited from the C base class. See L for details and other methods that can be used to access the content. Note that the content should be a string of bytes. Strings in perl can contain characters outside the range of a byte. The C module can be used to turn such strings into a string of bytes. =item $r->as_string =item $r->as_string( $eol ) Method returning a textual representation of the request. =back =head1 EXAMPLES Creating requests to be sent with L or others can be easy. Here are a few examples. =head2 Simple POST Here, we'll create a simple POST request that could be used to send JSON data to an endpoint. #!/usr/bin/env perl use strict; use warnings; use HTTP::Request (); use JSON::MaybeXS qw(encode_json); my $url = 'https://www.example.com/api/user/123'; my $header = ['Content-Type' => 'application/json; charset=UTF-8']; my $data = {foo => 'bar', baz => 'quux'}; my $encoded_data = encode_json($data); my $r = HTTP::Request->new('POST', $url, $header, $encoded_data); # at this point, we could send it via LWP::UserAgent # my $ua = LWP::UserAgent->new(); # my $res = $ua->request($r); =head2 Batch POST Request Some services, like Google, allow multiple requests to be sent in one batch. L for example. Using the C method from L makes this simple. #!/usr/bin/env perl use strict; use warnings; use HTTP::Request (); use JSON::MaybeXS qw(encode_json); my $auth_token = 'auth_token'; my $batch_url = 'https://www.googleapis.com/batch'; my $url = 'https://www.googleapis.com/drive/v3/files/fileId/permissions?fields=id'; my $url_no_email = 'https://www.googleapis.com/drive/v3/files/fileId/permissions?fields=id&sendNotificationEmail=false'; # generate a JSON post request for one of the batch entries my $req1 = build_json_request($url, { emailAddress => 'example@appsrocks.com', role => "writer", type => "user", }); # generate a JSON post request for one of the batch entries my $req2 = build_json_request($url_no_email, { domain => "appsrocks.com", role => "reader", type => "domain", }); # generate a multipart request to send all of the other requests my $r = HTTP::Request->new('POST', $batch_url, [ 'Accept-Encoding' => 'gzip', # if we don't provide a boundary here, HTTP::Message will generate # one for us. We could use UUID::uuid() here if we wanted. 'Content-Type' => 'multipart/mixed; boundary=END_OF_PART' ]); # add the two POST requests to the main request $r->add_part($req1, $req2); # at this point, we could send it via LWP::UserAgent # my $ua = LWP::UserAgent->new(); # my $res = $ua->request($r); exit(); sub build_json_request { my ($url, $href) = @_; my $header = ['Authorization' => "Bearer $auth_token", 'Content-Type' => 'application/json; charset=UTF-8']; return HTTP::Request->new('POST', $url, $header, encode_json($href)); } =head1 SEE ALSO L, L, L, L =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: HTTP style request message PK!#ñkxxperl5/HTTP/Message.pmnuÏÃ6Ç$package HTTP::Message; use strict; use warnings; our $VERSION = '6.26'; require HTTP::Headers; require Carp; my $CRLF = "\015\012"; # "\r\n" is not portable unless ($HTTP::URI_CLASS) { if ($ENV{PERL_HTTP_URI_CLASS} && $ENV{PERL_HTTP_URI_CLASS} =~ /^([\w:]+)$/) { $HTTP::URI_CLASS = $1; } else { $HTTP::URI_CLASS = "URI"; } } eval "require $HTTP::URI_CLASS"; die $@ if $@; *_utf8_downgrade = defined(&utf8::downgrade) ? sub { utf8::downgrade($_[0], 1) or Carp::croak("HTTP::Message content must be bytes") } : sub { }; sub new { my($class, $header, $content) = @_; if (defined $header) { Carp::croak("Bad header argument") unless ref $header; if (ref($header) eq "ARRAY") { $header = HTTP::Headers->new(@$header); } else { $header = $header->clone; } } else { $header = HTTP::Headers->new; } if (defined $content) { _utf8_downgrade($content); } else { $content = ''; } bless { '_headers' => $header, '_content' => $content, }, $class; } sub parse { my($class, $str) = @_; my @hdr; while (1) { if ($str =~ s/^([^\s:]+)[ \t]*: ?(.*)\n?//) { push(@hdr, $1, $2); $hdr[-1] =~ s/\r\z//; } elsif (@hdr && $str =~ s/^([ \t].*)\n?//) { $hdr[-1] .= "\n$1"; $hdr[-1] =~ s/\r\z//; } else { $str =~ s/^\r?\n//; last; } } local $HTTP::Headers::TRANSLATE_UNDERSCORE; new($class, \@hdr, $str); } sub clone { my $self = shift; my $clone = HTTP::Message->new($self->headers, $self->content); $clone->protocol($self->protocol); $clone; } sub clear { my $self = shift; $self->{_headers}->clear; $self->content(""); delete $self->{_parts}; return; } sub protocol { shift->_elem('_protocol', @_); } sub headers { my $self = shift; # recalculation of _content might change headers, so we # need to force it now $self->_content unless exists $self->{_content}; $self->{_headers}; } sub headers_as_string { shift->headers->as_string(@_); } sub content { my $self = $_[0]; if (defined(wantarray)) { $self->_content unless exists $self->{_content}; my $old = $self->{_content}; $old = $$old if ref($old) eq "SCALAR"; &_set_content if @_ > 1; return $old; } if (@_ > 1) { &_set_content; } else { Carp::carp("Useless content call in void context") if $^W; } } sub _set_content { my $self = $_[0]; _utf8_downgrade($_[1]); if (!ref($_[1]) && ref($self->{_content}) eq "SCALAR") { ${$self->{_content}} = defined( $_[1] ) ? $_[1] : ''; } else { die "Can't set content to be a scalar reference" if ref($_[1]) eq "SCALAR"; $self->{_content} = defined( $_[1] ) ? $_[1] : ''; delete $self->{_content_ref}; } delete $self->{_parts} unless $_[2]; } sub add_content { my $self = shift; $self->_content unless exists $self->{_content}; my $chunkref = \$_[0]; $chunkref = $$chunkref if ref($$chunkref); # legacy _utf8_downgrade($$chunkref); my $ref = ref($self->{_content}); if (!$ref) { $self->{_content} .= $$chunkref; } elsif ($ref eq "SCALAR") { ${$self->{_content}} .= $$chunkref; } else { Carp::croak("Can't append to $ref content"); } delete $self->{_parts}; } sub add_content_utf8 { my($self, $buf) = @_; utf8::upgrade($buf); utf8::encode($buf); $self->add_content($buf); } sub content_ref { my $self = shift; $self->_content unless exists $self->{_content}; delete $self->{_parts}; my $old = \$self->{_content}; my $old_cref = $self->{_content_ref}; if (@_) { my $new = shift; Carp::croak("Setting content_ref to a non-ref") unless ref($new); delete $self->{_content}; # avoid modifying $$old $self->{_content} = $new; $self->{_content_ref}++; } $old = $$old if $old_cref; return $old; } sub content_charset { my $self = shift; if (my $charset = $self->content_type_charset) { return $charset; } # time to start guessing my $cref = $self->decoded_content(ref => 1, charset => "none"); # Unicode BOM for ($$cref) { return "UTF-8" if /^\xEF\xBB\xBF/; return "UTF-32LE" if /^\xFF\xFE\x00\x00/; return "UTF-32BE" if /^\x00\x00\xFE\xFF/; return "UTF-16LE" if /^\xFF\xFE/; return "UTF-16BE" if /^\xFE\xFF/; } if ($self->content_is_xml) { # http://www.w3.org/TR/2006/REC-xml-20060816/#sec-guessing # XML entity not accompanied by external encoding information and not # in UTF-8 or UTF-16 encoding must begin with an XML encoding declaration, # in which the first characters must be ')/) { if ($1 =~ /\sencoding\s*=\s*(["'])(.*?)\1/) { my $enc = $2; $enc =~ s/^\s+//; $enc =~ s/\s+\z//; return $enc if $enc; } } } return "UTF-8"; } elsif ($self->content_is_html) { # look for or # http://dev.w3.org/html5/spec/Overview.html#determining-the-character-encoding require IO::HTML; # Use relaxed search to match previous versions of HTTP::Message: my $encoding = IO::HTML::find_charset_in($$cref, { encoding => 1, need_pragma => 0 }); return $encoding->mime_name if $encoding; } elsif ($self->content_type eq "application/json") { for ($$cref) { # RFC 4627, ch 3 return "UTF-32BE" if /^\x00\x00\x00./s; return "UTF-32LE" if /^.\x00\x00\x00/s; return "UTF-16BE" if /^\x00.\x00./s; return "UTF-16LE" if /^.\x00.\x00/s; return "UTF-8"; } } if ($self->content_type =~ /^text\//) { for ($$cref) { if (length) { return "US-ASCII" unless /[\x80-\xFF]/; require Encode; eval { Encode::decode_utf8($_, Encode::FB_CROAK() | Encode::LEAVE_SRC()); }; return "UTF-8" unless $@; return "ISO-8859-1"; } } } return undef; } sub decoded_content { my($self, %opt) = @_; my $content_ref; my $content_ref_iscopy; eval { $content_ref = $self->content_ref; die "Can't decode ref content" if ref($content_ref) ne "SCALAR"; if (my $h = $self->header("Content-Encoding")) { $h =~ s/^\s+//; $h =~ s/\s+$//; for my $ce (reverse split(/\s*,\s*/, lc($h))) { next unless $ce; next if $ce eq "identity" || $ce eq "none"; if ($ce eq "gzip" || $ce eq "x-gzip") { require IO::Uncompress::Gunzip; my $output; IO::Uncompress::Gunzip::gunzip($content_ref, \$output, Transparent => 0) or die "Can't gunzip content: $IO::Uncompress::Gunzip::GunzipError"; $content_ref = \$output; $content_ref_iscopy++; } elsif ($ce eq "x-bzip2" or $ce eq "bzip2") { require IO::Uncompress::Bunzip2; my $output; IO::Uncompress::Bunzip2::bunzip2($content_ref, \$output, Transparent => 0) or die "Can't bunzip content: $IO::Uncompress::Bunzip2::Bunzip2Error"; $content_ref = \$output; $content_ref_iscopy++; } elsif ($ce eq "deflate") { require IO::Uncompress::Inflate; my $output; my $status = IO::Uncompress::Inflate::inflate($content_ref, \$output, Transparent => 0); my $error = $IO::Uncompress::Inflate::InflateError; unless ($status) { # "Content-Encoding: deflate" is supposed to mean the # "zlib" format of RFC 1950, but Microsoft got that # wrong, so some servers sends the raw compressed # "deflate" data. This tries to inflate this format. $output = undef; require IO::Uncompress::RawInflate; unless (IO::Uncompress::RawInflate::rawinflate($content_ref, \$output)) { $self->push_header("Client-Warning" => "Could not raw inflate content: $IO::Uncompress::RawInflate::RawInflateError"); $output = undef; } } die "Can't inflate content: $error" unless defined $output; $content_ref = \$output; $content_ref_iscopy++; } elsif ($ce eq "compress" || $ce eq "x-compress") { die "Can't uncompress content"; } elsif ($ce eq "base64") { # not really C-T-E, but should be harmless require MIME::Base64; $content_ref = \MIME::Base64::decode($$content_ref); $content_ref_iscopy++; } elsif ($ce eq "quoted-printable") { # not really C-T-E, but should be harmless require MIME::QuotedPrint; $content_ref = \MIME::QuotedPrint::decode($$content_ref); $content_ref_iscopy++; } else { die "Don't know how to decode Content-Encoding '$ce'"; } } } if ($self->content_is_text || (my $is_xml = $self->content_is_xml)) { my $charset = lc( $opt{charset} || $self->content_type_charset || $opt{default_charset} || $self->content_charset || "ISO-8859-1" ); if ($charset eq "none") { # leave it as is } elsif ($charset eq "us-ascii" || $charset eq "iso-8859-1") { if ($$content_ref =~ /[^\x00-\x7F]/ && defined &utf8::upgrade) { unless ($content_ref_iscopy) { my $copy = $$content_ref; $content_ref = \$copy; $content_ref_iscopy++; } utf8::upgrade($$content_ref); } } else { require Encode; eval { $content_ref = \Encode::decode($charset, $$content_ref, ($opt{charset_strict} ? Encode::FB_CROAK() : 0) | Encode::LEAVE_SRC()); }; if ($@) { my $retried; if ($@ =~ /^Unknown encoding/) { my $alt_charset = lc($opt{alt_charset} || ""); if ($alt_charset && $charset ne $alt_charset) { # Retry decoding with the alternative charset $content_ref = \Encode::decode($alt_charset, $$content_ref, ($opt{charset_strict} ? Encode::FB_CROAK() : 0) | Encode::LEAVE_SRC()) unless $alt_charset eq "none"; $retried++; } } die unless $retried; } die "Encode::decode() returned undef improperly" unless defined $$content_ref; if ($is_xml) { # Get rid of the XML encoding declaration if present $$content_ref =~ s/^\x{FEFF}//; if ($$content_ref =~ /^(\s*<\?xml[^\x00]*?\?>)/) { substr($$content_ref, 0, length($1)) =~ s/\sencoding\s*=\s*(["']).*?\1//; } } } } }; if ($@) { Carp::croak($@) if $opt{raise_error}; return undef; } return $opt{ref} ? $content_ref : $$content_ref; } sub decodable { # should match the Content-Encoding values that decoded_content can deal with my $self = shift; my @enc; local $@; # XXX preferably we should determine if the modules are available without loading # them here eval { require IO::Uncompress::Gunzip; push(@enc, "gzip", "x-gzip"); }; eval { require IO::Uncompress::Inflate; require IO::Uncompress::RawInflate; push(@enc, "deflate"); }; eval { require IO::Uncompress::Bunzip2; push(@enc, "x-bzip2", "bzip2"); }; # we don't care about announcing the 'identity', 'base64' and # 'quoted-printable' stuff return wantarray ? @enc : join(", ", @enc); } sub decode { my $self = shift; return 1 unless $self->header("Content-Encoding"); if (defined(my $content = $self->decoded_content(charset => "none"))) { $self->remove_header("Content-Encoding", "Content-Length", "Content-MD5"); $self->content($content); return 1; } return 0; } sub encode { my($self, @enc) = @_; Carp::croak("Can't encode multipart/* messages") if $self->content_type =~ m,^multipart/,; Carp::croak("Can't encode message/* messages") if $self->content_type =~ m,^message/,; return 1 unless @enc; # nothing to do my $content = $self->content; for my $encoding (@enc) { if ($encoding eq "identity" || $encoding eq "none") { # nothing to do } elsif ($encoding eq "base64") { require MIME::Base64; $content = MIME::Base64::encode($content); } elsif ($encoding eq "gzip" || $encoding eq "x-gzip") { require IO::Compress::Gzip; my $output; IO::Compress::Gzip::gzip(\$content, \$output, Minimal => 1) or die "Can't gzip content: $IO::Compress::Gzip::GzipError"; $content = $output; } elsif ($encoding eq "deflate") { require IO::Compress::Deflate; my $output; IO::Compress::Deflate::deflate(\$content, \$output) or die "Can't deflate content: $IO::Compress::Deflate::DeflateError"; $content = $output; } elsif ($encoding eq "x-bzip2" || $encoding eq "bzip2") { require IO::Compress::Bzip2; my $output; IO::Compress::Bzip2::bzip2(\$content, \$output) or die "Can't bzip2 content: $IO::Compress::Bzip2::Bzip2Error"; $content = $output; } elsif ($encoding eq "rot13") { # for the fun of it $content =~ tr/A-Za-z/N-ZA-Mn-za-m/; } else { return 0; } } my $h = $self->header("Content-Encoding"); unshift(@enc, $h) if $h; $self->header("Content-Encoding", join(", ", @enc)); $self->remove_header("Content-Length", "Content-MD5"); $self->content($content); return 1; } sub as_string { my($self, $eol) = @_; $eol = "\n" unless defined $eol; # The calculation of content might update the headers # so we need to do that first. my $content = $self->content; return join("", $self->{'_headers'}->as_string($eol), $eol, $content, (@_ == 1 && length($content) && $content !~ /\n\z/) ? "\n" : "", ); } sub dump { my($self, %opt) = @_; my $content = $self->content; my $chopped = 0; if (!ref($content)) { my $maxlen = $opt{maxlength}; $maxlen = 512 unless defined($maxlen); if ($maxlen && length($content) > $maxlen * 1.1 + 3) { $chopped = length($content) - $maxlen; $content = substr($content, 0, $maxlen) . "..."; } $content =~ s/\\/\\\\/g; $content =~ s/\t/\\t/g; $content =~ s/\r/\\r/g; # no need for 3 digits in escape for these $content =~ s/([\0-\11\13-\037])(?!\d)/sprintf('\\%o',ord($1))/eg; $content =~ s/([\0-\11\13-\037\177-\377])/sprintf('\\x%02X',ord($1))/eg; $content =~ s/([^\12\040-\176])/sprintf('\\x{%X}',ord($1))/eg; # remaining whitespace $content =~ s/( +)\n/("\\40" x length($1)) . "\n"/eg; $content =~ s/(\n+)\n/("\\n" x length($1)) . "\n"/eg; $content =~ s/\n\z/\\n/; my $no_content = $opt{no_content}; $no_content = "(no content)" unless defined $no_content; if ($content eq $no_content) { # escape our $no_content marker $content =~ s/^(.)/sprintf('\\x%02X',ord($1))/eg; } elsif ($content eq "") { $content = $no_content; } } my @dump; push(@dump, $opt{preheader}) if $opt{preheader}; push(@dump, $self->{_headers}->as_string, $content); push(@dump, "(+ $chopped more bytes not shown)") if $chopped; my $dump = join("\n", @dump, ""); $dump =~ s/^/$opt{prefix}/gm if $opt{prefix}; print $dump unless defined wantarray; return $dump; } # allow subclasses to override what will handle individual parts sub _part_class { return __PACKAGE__; } sub parts { my $self = shift; if (defined(wantarray) && (!exists $self->{_parts} || ref($self->{_content}) eq "SCALAR")) { $self->_parts; } my $old = $self->{_parts}; if (@_) { my @parts = map { ref($_) eq 'ARRAY' ? @$_ : $_ } @_; my $ct = $self->content_type || ""; if ($ct =~ m,^message/,) { Carp::croak("Only one part allowed for $ct content") if @parts > 1; } elsif ($ct !~ m,^multipart/,) { $self->remove_content_headers; $self->content_type("multipart/mixed"); } $self->{_parts} = \@parts; _stale_content($self); } return @$old if wantarray; return $old->[0]; } sub add_part { my $self = shift; if (($self->content_type || "") !~ m,^multipart/,) { my $p = $self->_part_class->new( $self->remove_content_headers, $self->content(""), ); $self->content_type("multipart/mixed"); $self->{_parts} = []; if ($p->headers->header_field_names || $p->content ne "") { push(@{$self->{_parts}}, $p); } } elsif (!exists $self->{_parts} || ref($self->{_content}) eq "SCALAR") { $self->_parts; } push(@{$self->{_parts}}, @_); _stale_content($self); return; } sub _stale_content { my $self = shift; if (ref($self->{_content}) eq "SCALAR") { # must recalculate now $self->_content; } else { # just invalidate cache delete $self->{_content}; delete $self->{_content_ref}; } } # delegate all other method calls to the headers object. our $AUTOLOAD; sub AUTOLOAD { my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::')+2); # We create the function here so that it will not need to be # autoloaded the next time. no strict 'refs'; *$method = sub { local $Carp::Internal{+__PACKAGE__} = 1; shift->headers->$method(@_) }; goto &$method; } sub DESTROY {} # avoid AUTOLOADing it # Private method to access members in %$self sub _elem { my $self = shift; my $elem = shift; my $old = $self->{$elem}; $self->{$elem} = $_[0] if @_; return $old; } # Create private _parts attribute from current _content sub _parts { my $self = shift; my $ct = $self->content_type; if ($ct =~ m,^multipart/,) { require HTTP::Headers::Util; my @h = HTTP::Headers::Util::split_header_words($self->header("Content-Type")); die "Assert" unless @h; my %h = @{$h[0]}; if (defined(my $b = $h{boundary})) { my $str = $self->content; $str =~ s/\r?\n--\Q$b\E--.*//s; if ($str =~ s/(^|.*?\r?\n)--\Q$b\E\r?\n//s) { $self->{_parts} = [map $self->_part_class->parse($_), split(/\r?\n--\Q$b\E\r?\n/, $str)] } } } elsif ($ct eq "message/http") { require HTTP::Request; require HTTP::Response; my $content = $self->content; my $class = ($content =~ m,^(HTTP/.*)\n,) ? "HTTP::Response" : "HTTP::Request"; $self->{_parts} = [$class->parse($content)]; } elsif ($ct =~ m,^message/,) { $self->{_parts} = [ $self->_part_class->parse($self->content) ]; } $self->{_parts} ||= []; } # Create private _content attribute from current _parts sub _content { my $self = shift; my $ct = $self->{_headers}->header("Content-Type") || "multipart/mixed"; if ($ct =~ m,^\s*message/,i) { _set_content($self, $self->{_parts}[0]->as_string($CRLF), 1); return; } require HTTP::Headers::Util; my @v = HTTP::Headers::Util::split_header_words($ct); Carp::carp("Multiple Content-Type headers") if @v > 1; @v = @{$v[0]}; my $boundary; my $boundary_index; for (my @tmp = @v; @tmp;) { my($k, $v) = splice(@tmp, 0, 2); if ($k eq "boundary") { $boundary = $v; $boundary_index = @v - @tmp - 1; last; } } my @parts = map $_->as_string($CRLF), @{$self->{_parts}}; my $bno = 0; $boundary = _boundary() unless defined $boundary; CHECK_BOUNDARY: { for (@parts) { if (index($_, $boundary) >= 0) { # must have a better boundary $boundary = _boundary(++$bno); redo CHECK_BOUNDARY; } } } if ($boundary_index) { $v[$boundary_index] = $boundary; } else { push(@v, boundary => $boundary); } $ct = HTTP::Headers::Util::join_header_words(@v); $self->{_headers}->header("Content-Type", $ct); _set_content($self, "--$boundary$CRLF" . join("$CRLF--$boundary$CRLF", @parts) . "$CRLF--$boundary--$CRLF", 1); } sub _boundary { my $size = shift || return "xYzZY"; require MIME::Base64; my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), ""); $b =~ s/[\W]/X/g; # ensure alnum only $b; } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Message - HTTP style message (base class) =head1 VERSION version 6.26 =head1 SYNOPSIS use base 'HTTP::Message'; =head1 DESCRIPTION An C object contains some headers and a content body. The following methods are available: =over 4 =item $mess = HTTP::Message->new =item $mess = HTTP::Message->new( $headers ) =item $mess = HTTP::Message->new( $headers, $content ) This constructs a new message object. Normally you would want construct C or C objects instead. The optional $header argument should be a reference to an C object or a plain array reference of key/value pairs. If an C object is provided then a copy of it will be embedded into the constructed message, i.e. it will not be owned and can be modified afterwards without affecting the message. The optional $content argument should be a string of bytes. =item $mess = HTTP::Message->parse( $str ) This constructs a new message object by parsing the given string. =item $mess->headers Returns the embedded C object. =item $mess->headers_as_string =item $mess->headers_as_string( $eol ) Call the as_string() method for the headers in the message. This will be the same as $mess->headers->as_string but it will make your program a whole character shorter :-) =item $mess->content =item $mess->content( $bytes ) The content() method sets the raw content if an argument is given. If no argument is given the content is not touched. In either case the original raw content is returned. If the C argument is given, the content is reset to its default value, which is an empty string. Note that the content should be a string of bytes. Strings in perl can contain characters outside the range of a byte. The C module can be used to turn such strings into a string of bytes. =item $mess->add_content( $bytes ) The add_content() methods appends more data bytes to the end of the current content buffer. =item $mess->add_content_utf8( $string ) The add_content_utf8() method appends the UTF-8 bytes representing the string to the end of the current content buffer. =item $mess->content_ref =item $mess->content_ref( \$bytes ) The content_ref() method will return a reference to content buffer string. It can be more efficient to access the content this way if the content is huge, and it can even be used for direct manipulation of the content, for instance: ${$res->content_ref} =~ s/\bfoo\b/bar/g; This example would modify the content buffer in-place. If an argument is passed it will setup the content to reference some external source. The content() and add_content() methods will automatically dereference scalar references passed this way. For other references content() will return the reference itself and add_content() will refuse to do anything. =item $mess->content_charset This returns the charset used by the content in the message. The charset is either found as the charset attribute of the C header or by guessing. See L for details about how charset is determined. =item $mess->decoded_content( %options ) Returns the content with any C undone and for textual content the raw content encoded to Perl's Unicode strings. If the C or C of the message is unknown this method will fail by returning C. The following options can be specified. =over =item C This override the charset parameter for text content. The value C can used to suppress decoding of the charset. =item C This override the default charset guessed by content_charset() or if that fails "ISO-8859-1". =item C If decoding fails because the charset specified in the Content-Type header isn't recognized by Perl's Encode module, then try decoding using this charset instead of failing. The C might be specified as C to simply return the string without any decoding of charset as alternative. =item C Abort decoding if malformed characters is found in the content. By default you get the substitution character ("\x{FFFD}") in place of malformed characters. =item C If TRUE then raise an exception if not able to decode content. Reason might be that the specified C or C is not supported. If this option is FALSE, then decoded_content() will return C on errors, but will still set $@. =item C If TRUE then a reference to decoded content is returned. This might be more efficient in cases where the decoded content is identical to the raw content as no data copying is required in this case. =back =item $mess->decodable =item HTTP::Message::decodable() This returns the encoding identifiers that decoded_content() can process. In scalar context returns a comma separated string of identifiers. This value is suitable for initializing the C request header field. =item $mess->decode This method tries to replace the content of the message with the decoded version and removes the C header. Returns TRUE if successful and FALSE if not. If the message does not have a C header this method does nothing and returns TRUE. Note that the content of the message is still bytes after this method has been called and you still need to call decoded_content() if you want to process its content as a string. =item $mess->encode( $encoding, ... ) Apply the given encodings to the content of the message. Returns TRUE if successful. The "identity" (non-)encoding is always supported; other currently supported encodings, subject to availability of required additional modules, are "gzip", "deflate", "x-bzip2" and "base64". A successful call to this function will set the C header. Note that C or C messages can't be encoded and this method will croak if you try. =item $mess->parts =item $mess->parts( @parts ) =item $mess->parts( \@parts ) Messages can be composite, i.e. contain other messages. The composite messages have a content type of C or C. This method give access to the contained messages. The argumentless form will return a list of C objects. If the content type of $msg is not C or C then this will return the empty list. In scalar context only the first object is returned. The returned message parts should be regarded as read-only (future versions of this library might make it possible to modify the parent by modifying the parts). If the content type of $msg is C then there will only be one part returned. If the content type is C, then the return value will be either an C or an C object. If a @parts argument is given, then the content of the message will be modified. The array reference form is provided so that an empty list can be provided. The @parts array should contain C objects. The @parts objects are owned by $mess after this call and should not be modified or made part of other messages. When updating the message with this method and the old content type of $mess is not C or C, then the content type is set to C and all other content headers are cleared. This method will croak if the content type is C and more than one part is provided. =item $mess->add_part( $part ) This will add a part to a message. The $part argument should be another C object. If the previous content type of $mess is not C then the old content (together with all content headers) will be made part #1 and the content type made C before the new part is added. The $part object is owned by $mess after this call and should not be modified or made part of other messages. There is no return value. =item $mess->clear Will clear the headers and set the content to the empty string. There is no return value =item $mess->protocol =item $mess->protocol( $proto ) Sets the HTTP protocol used for the message. The protocol() is a string like C or C. =item $mess->clone Returns a copy of the message object. =item $mess->as_string =item $mess->as_string( $eol ) Returns the message formatted as a single string. The optional $eol parameter specifies the line ending sequence to use. The default is "\n". If no $eol is given then as_string will ensure that the returned string is newline terminated (even when the message content is not). No extra newline is appended if an explicit $eol is passed. =item $mess->dump( %opt ) Returns the message formatted as a string. In void context print the string. This differs from C<< $mess->as_string >> in that it escapes the bytes of the content so that it's safe to print them and it limits how much content to print. The escapes syntax used is the same as for Perl's double quoted strings. If there is no content the string "(no content)" is shown in its place. Options to influence the output can be passed as key/value pairs. The following options are recognized: =over =item maxlength => $num How much of the content to show. The default is 512. Set this to 0 for unlimited. If the content is longer then the string is chopped at the limit and the string "...\n(### more bytes not shown)" appended. =item no_content => $str Replaces the "(no content)" marker. =item prefix => $str A string that will be prefixed to each line of the dump. =back =back All methods unknown to C itself are delegated to the C object that is part of every message. This allows convenient access to these methods. Refer to L for details of these methods: $mess->header( $field => $val ) $mess->push_header( $field => $val ) $mess->init_header( $field => $val ) $mess->remove_header( $field ) $mess->remove_content_headers $mess->header_field_names $mess->scan( \&doit ) $mess->date $mess->expires $mess->if_modified_since $mess->if_unmodified_since $mess->last_modified $mess->content_type $mess->content_encoding $mess->content_length $mess->content_language $mess->title $mess->user_agent $mess->server $mess->from $mess->referer $mess->www_authenticate $mess->authorization $mess->proxy_authorization $mess->authorization_basic $mess->proxy_authorization_basic =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: HTTP style message (base class) PK!ÇÃPd‹-‹-perl5/HTTP/Config.pmnuÏÃ6Ç$package HTTP::Config; use strict; use warnings; our $VERSION = '6.26'; use URI; sub new { my $class = shift; return bless [], $class; } sub entries { my $self = shift; @$self; } sub empty { my $self = shift; not @$self; } sub add { if (@_ == 2) { my $self = shift; push(@$self, shift); return; } my($self, %spec) = @_; push(@$self, \%spec); return; } sub find2 { my($self, %spec) = @_; my @found; my @rest; ITEM: for my $item (@$self) { for my $k (keys %spec) { no warnings 'uninitialized'; if (!exists $item->{$k} || $spec{$k} ne $item->{$k}) { push(@rest, $item); next ITEM; } } push(@found, $item); } return \@found unless wantarray; return \@found, \@rest; } sub find { my $self = shift; my $f = $self->find2(@_); return @$f if wantarray; return $f->[0]; } sub remove { my($self, %spec) = @_; my($removed, $rest) = $self->find2(%spec); @$self = @$rest if @$removed; return @$removed; } my %MATCH = ( m_scheme => sub { my($v, $uri) = @_; return $uri->_scheme eq $v; # URI known to be canonical }, m_secure => sub { my($v, $uri) = @_; my $secure = $uri->can("secure") ? $uri->secure : $uri->_scheme eq "https"; return $secure == !!$v; }, m_host_port => sub { my($v, $uri) = @_; return unless $uri->can("host_port"); return $uri->host_port eq $v, 7; }, m_host => sub { my($v, $uri) = @_; return unless $uri->can("host"); return $uri->host eq $v, 6; }, m_port => sub { my($v, $uri) = @_; return unless $uri->can("port"); return $uri->port eq $v; }, m_domain => sub { my($v, $uri) = @_; return unless $uri->can("host"); my $h = $uri->host; $h = "$h.local" unless $h =~ /\./; $v = ".$v" unless $v =~ /^\./; return length($v), 5 if substr($h, -length($v)) eq $v; return 0; }, m_path => sub { my($v, $uri) = @_; return unless $uri->can("path"); return $uri->path eq $v, 4; }, m_path_prefix => sub { my($v, $uri) = @_; return unless $uri->can("path"); my $path = $uri->path; my $len = length($v); return $len, 3 if $path eq $v; return 0 if length($path) <= $len; $v .= "/" unless $v =~ m,/\z,,; return $len, 3 if substr($path, 0, length($v)) eq $v; return 0; }, m_path_match => sub { my($v, $uri) = @_; return unless $uri->can("path"); return $uri->path =~ $v; }, m_uri__ => sub { my($v, $k, $uri) = @_; return unless $uri->can($k); return 1 unless defined $v; return $uri->$k eq $v; }, m_method => sub { my($v, $uri, $request) = @_; return $request && $request->method eq $v; }, m_proxy => sub { my($v, $uri, $request) = @_; return $request && ($request->{proxy} || "") eq $v; }, m_code => sub { my($v, $uri, $request, $response) = @_; $v =~ s/xx\z//; return unless $response; return length($v), 2 if substr($response->code, 0, length($v)) eq $v; }, m_media_type => sub { # for request too?? my($v, $uri, $request, $response) = @_; return unless $response; return 1, 1 if $v eq "*/*"; my $ct = $response->content_type; return 2, 1 if $v =~ s,/\*\z,, && $ct =~ m,^\Q$v\E/,; return 3, 1 if $v eq "html" && $response->content_is_html; return 4, 1 if $v eq "xhtml" && $response->content_is_xhtml; return 10, 1 if $v eq $ct; return 0; }, m_header__ => sub { my($v, $k, $uri, $request, $response) = @_; return unless $request; return 1 if $request->header($k) eq $v; return 1 if $response && $response->header($k) eq $v; return 0; }, m_response_attr__ => sub { my($v, $k, $uri, $request, $response) = @_; return unless $response; return 1 if !defined($v) && exists $response->{$k}; return 0 unless exists $response->{$k}; return 1 if $response->{$k} eq $v; return 0; }, ); sub matching { my $self = shift; if (@_ == 1) { if ($_[0]->can("request")) { unshift(@_, $_[0]->request); unshift(@_, undef) unless defined $_[0]; } unshift(@_, $_[0]->uri_canonical) if $_[0] && $_[0]->can("uri_canonical"); } my($uri, $request, $response) = @_; $uri = URI->new($uri) unless ref($uri); my @m; ITEM: for my $item (@$self) { my $order; for my $ikey (keys %$item) { my $mkey = $ikey; my $k; $k = $1 if $mkey =~ s/__(.*)/__/; if (my $m = $MATCH{$mkey}) { #print "$ikey $mkey\n"; my($c, $o); my @arg = ( defined($k) ? $k : (), $uri, $request, $response ); my $v = $item->{$ikey}; $v = [$v] unless ref($v) eq "ARRAY"; for (@$v) { ($c, $o) = $m->($_, @arg); #print " - $_ ==> $c $o\n"; last if $c; } next ITEM unless $c; $order->[$o || 0] += $c; } } $order->[7] ||= 0; $item->{_order} = join(".", reverse map sprintf("%03d", $_ || 0), @$order); push(@m, $item); } @m = sort { $b->{_order} cmp $a->{_order} } @m; delete $_->{_order} for @m; return @m if wantarray; return $m[0]; } sub add_item { my $self = shift; my $item = shift; return $self->add(item => $item, @_); } sub remove_items { my $self = shift; return map $_->{item}, $self->remove(@_); } sub matching_items { my $self = shift; return map $_->{item}, $self->matching(@_); } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Config - Configuration for request and response objects =head1 VERSION version 6.26 =head1 SYNOPSIS use HTTP::Config; my $c = HTTP::Config->new; $c->add(m_domain => ".example.com", m_scheme => "http", verbose => 1); use HTTP::Request; my $request = HTTP::Request->new(GET => "http://www.example.com"); if (my @m = $c->matching($request)) { print "Yadayada\n" if $m[0]->{verbose}; } =head1 DESCRIPTION An C object is a list of entries that can be matched against request or request/response pairs. Its purpose is to hold configuration data that can be looked up given a request or response object. Each configuration entry is a hash. Some keys specify matching to occur against attributes of request/response objects. Other keys can be used to hold user data. The following methods are provided: =over 4 =item $conf = HTTP::Config->new Constructs a new empty C object and returns it. =item $conf->entries Returns the list of entries in the configuration object. In scalar context returns the number of entries. =item $conf->empty Return true if there are no entries in the configuration object. This is just a shorthand for C<< not $conf->entries >>. =item $conf->add( %matchspec, %other ) =item $conf->add( \%entry ) Adds a new entry to the configuration. You can either pass separate key/value pairs or a hash reference. =item $conf->remove( %spec ) Removes (and returns) the entries that have matches for all the key/value pairs in %spec. If %spec is empty this will match all entries; so it will empty the configuration object. =item $conf->matching( $uri, $request, $response ) =item $conf->matching( $uri ) =item $conf->matching( $request ) =item $conf->matching( $response ) Returns the entries that match the given $uri, $request and $response triplet. If called with a single $request object then the $uri is obtained by calling its 'uri_canonical' method. If called with a single $response object, then the request object is obtained by calling its 'request' method; and then the $uri is obtained as if a single $request was provided. The entries are returned with the most specific matches first. In scalar context returns the most specific match or C in none match. =item $conf->add_item( $item, %matchspec ) =item $conf->remove_items( %spec ) =item $conf->matching_items( $uri, $request, $response ) Wrappers that hides the entries themselves. =back =head2 Matching The following keys on a configuration entry specify matching. For all of these you can provide an array of values instead of a single value. The entry matches if at least one of the values in the array matches. Entries that require match against a response object attribute will never match unless a response object was provided. =over =item m_scheme => $scheme Matches if the URI uses the specified scheme; e.g. "http". =item m_secure => $bool If $bool is TRUE; matches if the URI uses a secure scheme. If $bool is FALSE; matches if the URI does not use a secure scheme. An example of a secure scheme is "https". =item m_host_port => "$hostname:$port" Matches if the URI's host_port method return the specified value. =item m_host => $hostname Matches if the URI's host method returns the specified value. =item m_port => $port Matches if the URI's port method returns the specified value. =item m_domain => ".$domain" Matches if the URI's host method return a value that within the given domain. The hostname "www.example.com" will for instance match the domain ".com". =item m_path => $path Matches if the URI's path method returns the specified value. =item m_path_prefix => $path Matches if the URI's path is the specified path or has the specified path as prefix. =item m_path_match => $Regexp Matches if the regular expression matches the URI's path. Eg. qr/\.html$/. =item m_method => $method Matches if the request method matches the specified value. Eg. "GET" or "POST". =item m_code => $digit =item m_code => $status_code Matches if the response status code matches. If a single digit is specified; matches for all response status codes beginning with that digit. =item m_proxy => $url Matches if the request is to be sent to the given Proxy server. =item m_media_type => "*/*" =item m_media_type => "text/*" =item m_media_type => "html" =item m_media_type => "xhtml" =item m_media_type => "text/html" Matches if the response media type matches. With a value of "html" matches if $response->content_is_html returns TRUE. With a value of "xhtml" matches if $response->content_is_xhtml returns TRUE. =item m_uri__I<$method> => undef Matches if the URI object provides the method. =item m_uri__I<$method> => $string Matches if the URI's $method method returns the given value. =item m_header__I<$field> => $string Matches if either the request or the response have a header $field with the given value. =item m_response_attr__I<$key> => undef =item m_response_attr__I<$key> => $string Matches if the response object has that key, or the entry has the given value. =back =head1 SEE ALSO L, L, L =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: Configuration for request and response objects PK!Þ¨ÿÏÏperl5/HTTP/Headers/Util.pmnuÏÃ6Ç$package HTTP::Headers::Util; use strict; use warnings; our $VERSION = '6.26'; use base 'Exporter'; our @EXPORT_OK=qw(split_header_words _split_header_words join_header_words); sub split_header_words { my @res = &_split_header_words; for my $arr (@res) { for (my $i = @$arr - 2; $i >= 0; $i -= 2) { $arr->[$i] = lc($arr->[$i]); } } return @res; } sub _split_header_words { my(@val) = @_; my @res; for (@val) { my @cur; while (length) { if (s/^\s*(=*[^\s=;,]+)//) { # 'token' or parameter 'attribute' push(@cur, $1); # a quoted value if (s/^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"//) { my $val = $1; $val =~ s/\\(.)/$1/g; push(@cur, $val); # some unquoted value } elsif (s/^\s*=\s*([^;,\s]*)//) { my $val = $1; $val =~ s/\s+$//; push(@cur, $val); # no value, a lone token } else { push(@cur, undef); } } elsif (s/^\s*,//) { push(@res, [@cur]) if @cur; @cur = (); } elsif (s/^\s*;// || s/^\s+//) { # continue } else { die "This should not happen: '$_'"; } } push(@res, \@cur) if @cur; } @res; } sub join_header_words { @_ = ([@_]) if @_ && !ref($_[0]); my @res; for (@_) { my @cur = @$_; my @attr; while (@cur) { my $k = shift @cur; my $v = shift @cur; if (defined $v) { if ($v =~ /[\x00-\x20()<>@,;:\\\"\/\[\]?={}\x7F-\xFF]/ || !length($v)) { $v =~ s/([\"\\])/\\$1/g; # escape " and \ $k .= qq(="$v"); } else { # token $k .= "=$v"; } } push(@attr, $k); } push(@res, join("; ", @attr)) if @attr; } join(", ", @res); } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Headers::Util - Header value parsing utility functions =head1 VERSION version 6.26 =head1 SYNOPSIS use HTTP::Headers::Util qw(split_header_words); @values = split_header_words($h->header("Content-Type")); =head1 DESCRIPTION This module provides a few functions that helps parsing and construction of valid HTTP header values. None of the functions are exported by default. The following functions are available: =over 4 =item split_header_words( @header_values ) This function will parse the header values given as argument into a list of anonymous arrays containing key/value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the @header_values passed as argument contains multiple values, then they are treated as if they were a single value separated by comma ",". This means that this function is useful for parsing header fields that follow this syntax (BNF as from the HTTP/1.1 specification, but we relax the requirement for tokens). headers = #header header = (token | parameter) *( [";"] (token | parameter)) token = 1* separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) qdtext = > quoted-pair = "\" CHAR parameter = attribute "=" value attribute = token value = token | quoted-string Each I
is represented by an anonymous array of key/value pairs. The keys will be all be forced to lower case. The value for a simple token (not part of a parameter) is C. Syntactically incorrect headers will not necessarily be parsed as you would want. This is easier to describe with some examples: split_header_words('foo="bar"; port="80,81"; DISCARD, BAR=baz'); split_header_words('text/html; charset="iso-8859-1"'); split_header_words('Basic realm="\\"foo\\\\bar\\""'); will return [foo=>'bar', port=>'80,81', discard=> undef], [bar=>'baz' ] ['text/html' => undef, charset => 'iso-8859-1'] [basic => undef, realm => "\"foo\\bar\""] If you don't want the function to convert tokens and attribute keys to lower case you can call it as C<_split_header_words> instead (with a leading underscore). =item join_header_words( @arrays ) This will do the opposite of the conversion done by split_header_words(). It takes a list of anonymous arrays as arguments (or a list of key/value pairs) and produces a single header value. Attribute values are quoted if needed. Example: join_header_words(["text/plain" => undef, charset => "iso-8859/1"]); join_header_words("text/plain" => undef, charset => "iso-8859/1"); will both return the string: text/plain; charset="iso-8859/1" =back =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: Header value parsing utility functions PK!äö+~ö ö perl5/HTTP/Headers/ETag.pmnuÏÃ6Ç$package HTTP::Headers::ETag; use strict; use warnings; our $VERSION = '6.26'; require HTTP::Date; require HTTP::Headers; package HTTP::Headers; sub _etags { my $self = shift; my $header = shift; my @old = _split_etag_list($self->_header($header)); if (@_) { $self->_header($header => join(", ", _split_etag_list(@_))); } wantarray ? @old : join(", ", @old); } sub etag { shift->_etags("ETag", @_); } sub if_match { shift->_etags("If-Match", @_); } sub if_none_match { shift->_etags("If-None-Match", @_); } sub if_range { # Either a date or an entity-tag my $self = shift; my @old = $self->_header("If-Range"); if (@_) { my $new = shift; if (!defined $new) { $self->remove_header("If-Range"); } elsif ($new =~ /^\d+$/) { $self->_date_header("If-Range", $new); } else { $self->_etags("If-Range", $new); } } return unless defined(wantarray); for (@old) { my $t = HTTP::Date::str2time($_); $_ = $t if $t; } wantarray ? @old : join(", ", @old); } # Split a list of entity tag values. The return value is a list # consisting of one element per entity tag. Suitable for parsing # headers like C, C. You might even want to # use it on C and C entity tag values, because it will # normalize them to the common form. # # entity-tag = [ weak ] opaque-tag # weak = "W/" # opaque-tag = quoted-string sub _split_etag_list { my(@val) = @_; my @res; for (@val) { while (length) { my $weak = ""; $weak = "W/" if s,^\s*[wW]/,,; my $etag = ""; if (s/^\s*(\"[^\"\\]*(?:\\.[^\"\\]*)*\")//) { push(@res, "$weak$1"); } elsif (s/^\s*,//) { push(@res, qq(W/"")) if $weak; } elsif (s/^\s*([^,\s]+)//) { $etag = $1; $etag =~ s/([\"\\])/\\$1/g; push(@res, qq($weak"$etag")); } elsif (s/^\s+// || !length) { push(@res, qq(W/"")) if $weak; } else { die "This should not happen: '$_'"; } } } @res; } 1; __END__ =pod =encoding UTF-8 =head1 NAME HTTP::Headers::ETag =head1 VERSION version 6.26 =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 PK!ëPT. . perl5/HTTP/Headers/Auth.pmnuÏÃ6Ç$package HTTP::Headers::Auth; use strict; use warnings; our $VERSION = '6.26'; use HTTP::Headers; package HTTP::Headers; BEGIN { # we provide a new (and better) implementations below undef(&www_authenticate); undef(&proxy_authenticate); } require HTTP::Headers::Util; sub _parse_authenticate { my @ret; for (HTTP::Headers::Util::split_header_words(@_)) { if (!defined($_->[1])) { # this is a new auth scheme push(@ret, shift(@$_) => {}); shift @$_; } if (@ret) { # this a new parameter pair for the last auth scheme while (@$_) { my $k = shift @$_; my $v = shift @$_; $ret[-1]{$k} = $v; } } else { # something wrong, parameter pair without any scheme seen # IGNORE } } @ret; } sub _authenticate { my $self = shift; my $header = shift; my @old = $self->_header($header); if (@_) { $self->remove_header($header); my @new = @_; while (@new) { my $a_scheme = shift(@new); if ($a_scheme =~ /\s/) { # assume complete valid value, pass it through $self->push_header($header, $a_scheme); } else { my @param; if (@new) { my $p = $new[0]; if (ref($p) eq "ARRAY") { @param = @$p; shift(@new); } elsif (ref($p) eq "HASH") { @param = %$p; shift(@new); } } my $val = ucfirst(lc($a_scheme)); if (@param) { my $sep = " "; while (@param) { my $k = shift @param; my $v = shift @param; if ($v =~ /[^0-9a-zA-Z]/ || lc($k) eq "realm") { # must quote the value $v =~ s,([\\\"]),\\$1,g; $v = qq("$v"); } $val .= "$sep$k=$v"; $sep = ", "; } } $self->push_header($header, $val); } } } return unless defined wantarray; wantarray ? _parse_authenticate(@old) : join(", ", @old); } sub www_authenticate { shift->_authenticate("WWW-Authenticate", @_) } sub proxy_authenticate { shift->_authenticate("Proxy-Authenticate", @_) } 1; __END__ =pod =encoding UTF-8 =head1 NAME HTTP::Headers::Auth =head1 VERSION version 6.26 =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 PK!½  RB?B?perl5/HTTP/Request/Common.pmnuÏÃ6Ç$package HTTP::Request::Common; use strict; use warnings; our $VERSION = '6.26'; our $DYNAMIC_FILE_UPLOAD ||= 0; # make it defined (don't know why) use Exporter 5.57 'import'; our @EXPORT =qw(GET HEAD PUT PATCH POST OPTIONS); our @EXPORT_OK = qw($DYNAMIC_FILE_UPLOAD DELETE); require HTTP::Request; use Carp(); my $CRLF = "\015\012"; # "\r\n" is not portable sub GET { _simple_req('GET', @_); } sub HEAD { _simple_req('HEAD', @_); } sub DELETE { _simple_req('DELETE', @_); } sub PATCH { request_type_with_data('PATCH', @_); } sub POST { request_type_with_data('POST', @_); } sub PUT { request_type_with_data('PUT', @_); } sub OPTIONS { request_type_with_data('OPTIONS', @_); } sub request_type_with_data { my $type = shift; my $url = shift; my $req = HTTP::Request->new($type => $url); my $content; $content = shift if @_ and ref $_[0]; my($k, $v); while (($k,$v) = splice(@_, 0, 2)) { if (lc($k) eq 'content') { $content = $v; } else { $req->push_header($k, $v); } } my $ct = $req->header('Content-Type'); unless ($ct) { $ct = 'application/x-www-form-urlencoded'; } elsif ($ct eq 'form-data') { $ct = 'multipart/form-data'; } if (ref $content) { if ($ct =~ m,^multipart/form-data\s*(;|$),i) { require HTTP::Headers::Util; my @v = HTTP::Headers::Util::split_header_words($ct); Carp::carp("Multiple Content-Type headers") if @v > 1; @v = @{$v[0]}; my $boundary; my $boundary_index; for (my @tmp = @v; @tmp;) { my($k, $v) = splice(@tmp, 0, 2); if ($k eq "boundary") { $boundary = $v; $boundary_index = @v - @tmp - 1; last; } } ($content, $boundary) = form_data($content, $boundary, $req); if ($boundary_index) { $v[$boundary_index] = $boundary; } else { push(@v, boundary => $boundary); } $ct = HTTP::Headers::Util::join_header_words(@v); } else { # We use a temporary URI object to format # the application/x-www-form-urlencoded content. require URI; my $url = URI->new('http:'); $url->query_form(ref($content) eq "HASH" ? %$content : @$content); $content = $url->query; # HTML/4.01 says that line breaks are represented as "CR LF" pairs (i.e., `%0D%0A') $content =~ s/(?header('Content-Type' => $ct); # might be redundant if (defined($content)) { $req->header('Content-Length' => length($content)) unless ref($content); $req->content($content); } else { $req->header('Content-Length' => 0); } $req; } sub _simple_req { my($method, $url) = splice(@_, 0, 2); my $req = HTTP::Request->new($method => $url); my($k, $v); my $content; while (($k,$v) = splice(@_, 0, 2)) { if (lc($k) eq 'content') { $req->add_content($v); $content++; } else { $req->push_header($k, $v); } } if ($content && !defined($req->header("Content-Length"))) { $req->header("Content-Length", length(${$req->content_ref})); } $req; } sub form_data # RFC1867 { my($data, $boundary, $req) = @_; my @data = ref($data) eq "HASH" ? %$data : @$data; # copy my $fhparts; my @parts; while (my ($k,$v) = splice(@data, 0, 2)) { if (!ref($v)) { $k =~ s/([\\\"])/\\$1/g; # escape quotes and backslashes no warnings 'uninitialized'; push(@parts, qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v)); } else { my($file, $usename, @headers) = @$v; unless (defined $usename) { $usename = $file; $usename =~ s,.*/,, if defined($usename); } $k =~ s/([\\\"])/\\$1/g; my $disp = qq(form-data; name="$k"); if (defined($usename) and length($usename)) { $usename =~ s/([\\\"])/\\$1/g; $disp .= qq(; filename="$usename"); } my $content = ""; my $h = HTTP::Headers->new(@headers); if ($file) { open(my $fh, "<", $file) or Carp::croak("Can't open file $file: $!"); binmode($fh); if ($DYNAMIC_FILE_UPLOAD) { # will read file later, close it now in order to # not accumulate to many open file handles close($fh); $content = \$file; } else { local($/) = undef; # slurp files $content = <$fh>; close($fh); } unless ($h->header("Content-Type")) { require LWP::MediaTypes; LWP::MediaTypes::guess_media_type($file, $h); } } if ($h->header("Content-Disposition")) { # just to get it sorted first $disp = $h->header("Content-Disposition"); $h->remove_header("Content-Disposition"); } if ($h->header("Content")) { $content = $h->header("Content"); $h->remove_header("Content"); } my $head = join($CRLF, "Content-Disposition: $disp", $h->as_string($CRLF), ""); if (ref $content) { push(@parts, [$head, $$content]); $fhparts++; } else { push(@parts, $head . $content); } } } return ("", "none") unless @parts; my $content; if ($fhparts) { $boundary = boundary(10) # hopefully enough randomness unless $boundary; # add the boundaries to the @parts array for (1..@parts-1) { splice(@parts, $_*2-1, 0, "$CRLF--$boundary$CRLF"); } unshift(@parts, "--$boundary$CRLF"); push(@parts, "$CRLF--$boundary--$CRLF"); # See if we can generate Content-Length header my $length = 0; for (@parts) { if (ref $_) { my ($head, $f) = @$_; my $file_size; unless ( -f $f && ($file_size = -s _) ) { # The file is either a dynamic file like /dev/audio # or perhaps a file in the /proc file system where # stat may return a 0 size even though reading it # will produce data. So we cannot make # a Content-Length header. undef $length; last; } $length += $file_size + length $head; } else { $length += length; } } $length && $req->header('Content-Length' => $length); # set up a closure that will return content piecemeal $content = sub { for (;;) { unless (@parts) { defined $length && $length != 0 && Carp::croak "length of data sent did not match calculated Content-Length header. Probably because uploaded file changed in size during transfer."; return; } my $p = shift @parts; unless (ref $p) { $p .= shift @parts while @parts && !ref($parts[0]); defined $length && ($length -= length $p); return $p; } my($buf, $fh) = @$p; unless (ref($fh)) { my $file = $fh; undef($fh); open($fh, "<", $file) || Carp::croak("Can't open file $file: $!"); binmode($fh); } my $buflength = length $buf; my $n = read($fh, $buf, 2048, $buflength); if ($n) { $buflength += $n; unshift(@parts, ["", $fh]); } else { close($fh); } if ($buflength) { defined $length && ($length -= $buflength); return $buf } } }; } else { $boundary = boundary() unless $boundary; my $bno = 0; CHECK_BOUNDARY: { for (@parts) { if (index($_, $boundary) >= 0) { # must have a better boundary $boundary = boundary(++$bno); redo CHECK_BOUNDARY; } } last; } $content = "--$boundary$CRLF" . join("$CRLF--$boundary$CRLF", @parts) . "$CRLF--$boundary--$CRLF"; } wantarray ? ($content, $boundary) : $content; } sub boundary { my $size = shift || return "xYzZY"; require MIME::Base64; my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), ""); $b =~ s/[\W]/X/g; # ensure alnum only $b; } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Request::Common - Construct common HTTP::Request objects =head1 VERSION version 6.26 =head1 SYNOPSIS use HTTP::Request::Common; $ua = LWP::UserAgent->new; $ua->request(GET 'http://www.sn.no/'); $ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]); $ua->request(PATCH 'http://somewhere/foo', [foo => bar, bar => foo]); $ua->request(PUT 'http://somewhere/foo', [foo => bar, bar => foo]); $ua->request(OPTIONS 'http://somewhere/foo', [foo => bar, bar => foo]); =head1 DESCRIPTION This module provides functions that return newly created C objects. These functions are usually more convenient to use than the standard C constructor for the most common requests. Note that L has several convenience methods, including C, C, C, C and C. The following functions are provided: =over 4 =item GET $url =item GET $url, Header => Value,... The C function returns an L object initialized with the "GET" method and the specified URL. It is roughly equivalent to the following call HTTP::Request->new( GET => $url, HTTP::Headers->new(Header => Value,...), ) but is less cluttered. What is different is that a header named C will initialize the content part of the request instead of setting a header field. Note that GET requests should normally not have a content, so this hack makes more sense for the C, C and C functions described below. The C method of L exists as a shortcut for C<< $ua->request(GET ...) >>. =item HEAD $url =item HEAD $url, Header => Value,... Like GET() but the method in the request is "HEAD". The C method of L exists as a shortcut for C<< $ua->request(HEAD ...) >>. =item DELETE $url =item DELETE $url, Header => Value,... Like C but the method in the request is C. This function is not exported by default. =item PATCH $url =item PATCH $url, Header => Value,... =item PATCH $url, $form_ref, Header => Value,... =item PATCH $url, Header => Value,..., Content => $form_ref =item PATCH $url, Header => Value,..., Content => $content The same as C below, but the method in the request is C. =item PUT $url =item PUT $url, Header => Value,... =item PUT $url, $form_ref, Header => Value,... =item PUT $url, Header => Value,..., Content => $form_ref =item PUT $url, Header => Value,..., Content => $content The same as C below, but the method in the request is C =item OPTIONS $url =item OPTIONS $url, Header => Value,... =item OPTIONS $url, $form_ref, Header => Value,... =item OPTIONS $url, Header => Value,..., Content => $form_ref =item OPTIONS $url, Header => Value,..., Content => $content The same as C below, but the method in the request is C =item POST $url =item POST $url, Header => Value,... =item POST $url, $form_ref, Header => Value,... =item POST $url, Header => Value,..., Content => $form_ref =item POST $url, Header => Value,..., Content => $content C, C and C all work with the same parameters. %data = ( title => 'something', body => something else' ); $ua = LWP::UserAgent->new(); $request = HTTP::Request::Common::POST( $url, [ %data ] ); $response = $ua->request($request); They take a second optional array or hash reference parameter C<$form_ref>. The content can also be specified directly using the C pseudo-header, and you may also provide the C<$form_ref> this way. The C pseudo-header steals a bit of the header field namespace as there is no way to directly specify a header that is actually called "Content". If you really need this you must update the request returned in a separate statement. The C<$form_ref> argument can be used to pass key/value pairs for the form content. By default we will initialize a request using the C content type. This means that you can emulate an HTML Eform> POSTing like this: POST 'http://www.perl.org/survey.cgi', [ name => 'Gisle Aas', email => 'gisle@aas.no', gender => 'M', born => '1964', perc => '3%', ]; This will create an L object that looks like this: POST http://www.perl.org/survey.cgi Content-Length: 66 Content-Type: application/x-www-form-urlencoded name=Gisle%20Aas&email=gisle%40aas.no&gender=M&born=1964&perc=3%25 Multivalued form fields can be specified by either repeating the field name or by passing the value as an array reference. The POST method also supports the C content used for I as specified in RFC 1867. You trigger this content format by specifying a content type of C<'form-data'> as one of the request headers. If one of the values in the C<$form_ref> is an array reference, then it is treated as a file part specification with the following interpretation: [ $file, $filename, Header => Value... ] [ undef, $filename, Header => Value,..., Content => $content ] The first value in the array ($file) is the name of a file to open. This file will be read and its content placed in the request. The routine will croak if the file can't be opened. Use an C as $file value if you want to specify the content directly with a C header. The $filename is the filename to report in the request. If this value is undefined, then the basename of the $file will be used. You can specify an empty string as $filename if you want to suppress sending the filename when you provide a $file value. If a $file is provided by no C header, then C and C will be filled in automatically with the values returned by C Sending my F<~/.profile> to the survey used as example above can be achieved by this: POST 'http://www.perl.org/survey.cgi', Content_Type => 'form-data', Content => [ name => 'Gisle Aas', email => 'gisle@aas.no', gender => 'M', born => '1964', init => ["$ENV{HOME}/.profile"], ] This will create an L object that almost looks this (the boundary and the content of your F<~/.profile> is likely to be different): POST http://www.perl.org/survey.cgi Content-Length: 388 Content-Type: multipart/form-data; boundary="6G+f" --6G+f Content-Disposition: form-data; name="name" Gisle Aas --6G+f Content-Disposition: form-data; name="email" gisle@aas.no --6G+f Content-Disposition: form-data; name="gender" M --6G+f Content-Disposition: form-data; name="born" 1964 --6G+f Content-Disposition: form-data; name="init"; filename=".profile" Content-Type: text/plain PATH=/local/perl/bin:$PATH export PATH --6G+f-- If you set the C<$DYNAMIC_FILE_UPLOAD> variable (exportable) to some TRUE value, then you get back a request object with a subroutine closure as the content attribute. This subroutine will read the content of any files on demand and return it in suitable chunks. This allow you to upload arbitrary big files without using lots of memory. You can even upload infinite files like F if you wish; however, if the file is not a plain file, there will be no C header defined for the request. Not all servers (or server applications) like this. Also, if the file(s) change in size between the time the C is calculated and the time that the last chunk is delivered, the subroutine will C. The C method of L exists as a shortcut for C<< $ua->request(POST ...) >>. =back =head1 SEE ALSO L, L Also, there are some examples in L that you might find useful. For example, batch requests are explained there. =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: Construct common HTTP::Request objects PK!ˆbèSBBperl5/HTTP/Response.pmnuÏÃ6Ç$package HTTP::Response; use strict; use warnings; our $VERSION = '6.26'; use base 'HTTP::Message'; use HTTP::Status (); sub new { my($class, $rc, $msg, $header, $content) = @_; my $self = $class->SUPER::new($header, $content); $self->code($rc); $self->message($msg); $self; } sub parse { my($class, $str) = @_; Carp::carp('Undefined argument to parse()') if $^W && ! defined $str; my $status_line; if (defined $str && $str =~ s/^(.*)\n//) { $status_line = $1; } else { $status_line = $str; $str = ""; } $status_line =~ s/\r\z// if defined $status_line; my $self = $class->SUPER::parse($str); if (defined $status_line) { my($protocol, $code, $message); if ($status_line =~ /^\d{3} /) { # Looks like a response created by HTTP::Response->new ($code, $message) = split(' ', $status_line, 2); } else { ($protocol, $code, $message) = split(' ', $status_line, 3); } $self->protocol($protocol) if $protocol; $self->code($code) if defined($code); $self->message($message) if defined($message); } $self; } sub clone { my $self = shift; my $clone = bless $self->SUPER::clone, ref($self); $clone->code($self->code); $clone->message($self->message); $clone->request($self->request->clone) if $self->request; # we don't clone previous $clone; } sub code { shift->_elem('_rc', @_); } sub message { shift->_elem('_msg', @_); } sub previous { shift->_elem('_previous',@_); } sub request { shift->_elem('_request', @_); } sub status_line { my $self = shift; my $code = $self->{'_rc'} || "000"; my $mess = $self->{'_msg'} || HTTP::Status::status_message($code) || "Unknown code"; return "$code $mess"; } sub base { my $self = shift; my $base = ( $self->header('Content-Base'), # used to be HTTP/1.1 $self->header('Content-Location'), # HTTP/1.1 $self->header('Base'), # HTTP/1.0 )[0]; if ($base && $base =~ /^$URI::scheme_re:/o) { # already absolute return $HTTP::URI_CLASS->new($base); } my $req = $self->request; if ($req) { # if $base is undef here, the return value is effectively # just a copy of $self->request->uri. return $HTTP::URI_CLASS->new_abs($base, $req->uri); } # can't find an absolute base return undef; } sub redirects { my $self = shift; my @r; my $r = $self; while (my $p = $r->previous) { push(@r, $p); $r = $p; } return @r unless wantarray; return reverse @r; } sub filename { my $self = shift; my $file; my $cd = $self->header('Content-Disposition'); if ($cd) { require HTTP::Headers::Util; if (my @cd = HTTP::Headers::Util::split_header_words($cd)) { my ($disposition, undef, %cd_param) = @{$cd[-1]}; $file = $cd_param{filename}; # RFC 2047 encoded? if ($file && $file =~ /^=\?(.+?)\?(.+?)\?(.+)\?=$/) { my $charset = $1; my $encoding = uc($2); my $encfile = $3; if ($encoding eq 'Q' || $encoding eq 'B') { local($SIG{__DIE__}); eval { if ($encoding eq 'Q') { $encfile =~ s/_/ /g; require MIME::QuotedPrint; $encfile = MIME::QuotedPrint::decode($encfile); } else { # $encoding eq 'B' require MIME::Base64; $encfile = MIME::Base64::decode($encfile); } require Encode; require Encode::Locale; Encode::from_to($encfile, $charset, "locale_fs"); }; $file = $encfile unless $@; } } } } unless (defined($file) && length($file)) { my $uri; if (my $cl = $self->header('Content-Location')) { $uri = URI->new($cl); } elsif (my $request = $self->request) { $uri = $request->uri; } if ($uri) { $file = ($uri->path_segments)[-1]; } } if ($file) { $file =~ s,.*[\\/],,; # basename } if ($file && !length($file)) { $file = undef; } $file; } sub as_string { my $self = shift; my($eol) = @_; $eol = "\n" unless defined $eol; my $status_line = $self->status_line; my $proto = $self->protocol; $status_line = "$proto $status_line" if $proto; return join($eol, $status_line, $self->SUPER::as_string(@_)); } sub dump { my $self = shift; my $status_line = $self->status_line; my $proto = $self->protocol; $status_line = "$proto $status_line" if $proto; return $self->SUPER::dump( preheader => $status_line, @_, ); } sub is_info { HTTP::Status::is_info (shift->{'_rc'}); } sub is_success { HTTP::Status::is_success (shift->{'_rc'}); } sub is_redirect { HTTP::Status::is_redirect (shift->{'_rc'}); } sub is_error { HTTP::Status::is_error (shift->{'_rc'}); } sub is_client_error { HTTP::Status::is_client_error (shift->{'_rc'}); } sub is_server_error { HTTP::Status::is_server_error (shift->{'_rc'}); } sub error_as_HTML { my $self = shift; my $title = 'An Error Occurred'; my $body = $self->status_line; $body =~ s/&/&/g; $body =~ s/ $title

$title

$body

EOM } sub current_age { my $self = shift; my $time = shift; # Implementation of RFC 2616 section 13.2.3 # (age calculations) my $response_time = $self->client_date; my $date = $self->date; my $age = 0; if ($response_time && $date) { $age = $response_time - $date; # apparent_age $age = 0 if $age < 0; } my $age_v = $self->header('Age'); if ($age_v && $age_v > $age) { $age = $age_v; # corrected_received_age } if ($response_time) { my $request = $self->request; if ($request) { my $request_time = $request->date; if ($request_time && $request_time < $response_time) { # Add response_delay to age to get 'corrected_initial_age' $age += $response_time - $request_time; } } $age += ($time || time) - $response_time; } return $age; } sub freshness_lifetime { my($self, %opt) = @_; # First look for the Cache-Control: max-age=n header for my $cc ($self->header('Cache-Control')) { for my $cc_dir (split(/\s*,\s*/, $cc)) { return $1 if $cc_dir =~ /^max-age\s*=\s*(\d+)/i; } } # Next possibility is to look at the "Expires" header my $date = $self->date || $self->client_date || $opt{time} || time; if (my $expires = $self->expires) { return $expires - $date; } # Must apply heuristic expiration return undef if exists $opt{heuristic_expiry} && !$opt{heuristic_expiry}; # Default heuristic expiration parameters $opt{h_min} ||= 60; $opt{h_max} ||= 24 * 3600; $opt{h_lastmod_fraction} ||= 0.10; # 10% since last-mod suggested by RFC2616 $opt{h_default} ||= 3600; # Should give a warning if more than 24 hours according to # RFC 2616 section 13.2.4. Here we just make this the default # maximum value. if (my $last_modified = $self->last_modified) { my $h_exp = ($date - $last_modified) * $opt{h_lastmod_fraction}; return $opt{h_min} if $h_exp < $opt{h_min}; return $opt{h_max} if $h_exp > $opt{h_max}; return $h_exp; } # default when all else fails return $opt{h_min} if $opt{h_min} > $opt{h_default}; return $opt{h_default}; } sub is_fresh { my($self, %opt) = @_; $opt{time} ||= time; my $f = $self->freshness_lifetime(%opt); return undef unless defined($f); return $f > $self->current_age($opt{time}); } sub fresh_until { my($self, %opt) = @_; $opt{time} ||= time; my $f = $self->freshness_lifetime(%opt); return undef unless defined($f); return $f - $self->current_age($opt{time}) + $opt{time}; } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Response - HTTP style response message =head1 VERSION version 6.26 =head1 SYNOPSIS Response objects are returned by the request() method of the C: # ... $response = $ua->request($request); if ($response->is_success) { print $response->decoded_content; } else { print STDERR $response->status_line, "\n"; } =head1 DESCRIPTION The C class encapsulates HTTP style responses. A response consists of a response line, some headers, and a content body. Note that the LWP library uses HTTP style responses even for non-HTTP protocol schemes. Instances of this class are usually created and returned by the request() method of an C object. C is a subclass of C and therefore inherits its methods. The following additional methods are available: =over 4 =item $r = HTTP::Response->new( $code ) =item $r = HTTP::Response->new( $code, $msg ) =item $r = HTTP::Response->new( $code, $msg, $header ) =item $r = HTTP::Response->new( $code, $msg, $header, $content ) Constructs a new C object describing a response with response code $code and optional message $msg. The optional $header argument should be a reference to an C object or a plain array reference of key/value pairs. The optional $content argument should be a string of bytes. The meanings of these arguments are described below. =item $r = HTTP::Response->parse( $str ) This constructs a new response object by parsing the given string. =item $r->code =item $r->code( $code ) This is used to get/set the code attribute. The code is a 3 digit number that encode the overall outcome of an HTTP response. The C module provide constants that provide mnemonic names for the code attribute. =item $r->message =item $r->message( $message ) This is used to get/set the message attribute. The message is a short human readable single line string that explains the response code. =item $r->header( $field ) =item $r->header( $field => $value ) This is used to get/set header values and it is inherited from C via C. See L for details and other similar methods that can be used to access the headers. =item $r->content =item $r->content( $bytes ) This is used to get/set the raw content and it is inherited from the C base class. See L for details and other methods that can be used to access the content. =item $r->decoded_content( %options ) This will return the content after any C and charsets have been decoded. See L for details. =item $r->request =item $r->request( $request ) This is used to get/set the request attribute. The request attribute is a reference to the request that caused this response. It does not have to be the same request passed to the $ua->request() method, because there might have been redirects and authorization retries in between. =item $r->previous =item $r->previous( $response ) This is used to get/set the previous attribute. The previous attribute is used to link together chains of responses. You get chains of responses if the first response is redirect or unauthorized. The value is C if this is the first response in a chain. Note that the method $r->redirects is provided as a more convenient way to access the response chain. =item $r->status_line Returns the string "Ecode> Emessage>". If the message attribute is not set then the official name of Ecode> (see L) is substituted. =item $r->base Returns the base URI for this response. The return value will be a reference to a URI object. The base URI is obtained from one the following sources (in priority order): =over 4 =item 1. Embedded in the document content, for instance in HTML documents. =item 2. A "Content-Base:" or a "Content-Location:" header in the response. For backwards compatibility with older HTTP implementations we will also look for the "Base:" header. =item 3. The URI used to request this response. This might not be the original URI that was passed to $ua->request() method, because we might have received some redirect responses first. =back If none of these sources provide an absolute URI, undef is returned. When the LWP protocol modules produce the HTTP::Response object, then any base URI embedded in the document (step 1) will already have initialized the "Content-Base:" header. (See L). This means that this method only performs the last 2 steps (the content is not always available either). =item $r->filename Returns a filename for this response. Note that doing sanity checks on the returned filename (eg. removing characters that cannot be used on the target filesystem where the filename would be used, and laundering it for security purposes) are the caller's responsibility; the only related thing done by this method is that it makes a simple attempt to return a plain filename with no preceding path segments. The filename is obtained from one the following sources (in priority order): =over 4 =item 1. A "Content-Disposition:" header in the response. Proper decoding of RFC 2047 encoded filenames requires the C (for "Q" encoding), C (for "B" encoding), and C modules. =item 2. A "Content-Location:" header in the response. =item 3. The URI used to request this response. This might not be the original URI that was passed to $ua->request() method, because we might have received some redirect responses first. =back If a filename cannot be derived from any of these sources, undef is returned. =item $r->as_string =item $r->as_string( $eol ) Returns a textual representation of the response. =item $r->is_info =item $r->is_success =item $r->is_redirect =item $r->is_error =item $r->is_client_error =item $r->is_server_error These methods indicate if the response was informational, successful, a redirection, or an error. See L for the meaning of these. =item $r->error_as_HTML Returns a string containing a complete HTML document indicating what error occurred. This method should only be called when $r->is_error is TRUE. =item $r->redirects Returns the list of redirect responses that lead up to this response by following the $r->previous chain. The list order is oldest first. In scalar context return the number of redirect responses leading up to this one. =item $r->current_age Calculates the "current age" of the response as specified by RFC 2616 section 13.2.3. The age of a response is the time since it was sent by the origin server. The returned value is a number representing the age in seconds. =item $r->freshness_lifetime( %opt ) Calculates the "freshness lifetime" of the response as specified by RFC 2616 section 13.2.4. The "freshness lifetime" is the length of time between the generation of a response and its expiration time. The returned value is the number of seconds until expiry. If the response does not contain an "Expires" or a "Cache-Control" header, then this function will apply some simple heuristic based on the "Last-Modified" header to determine a suitable lifetime. The following options might be passed to control the heuristics: =over =item heuristic_expiry => $bool If passed as a FALSE value, don't apply heuristics and just return C when "Expires" or "Cache-Control" is lacking. =item h_lastmod_fraction => $num This number represent the fraction of the difference since the "Last-Modified" timestamp to make the expiry time. The default is C<0.10>, the suggested typical setting of 10% in RFC 2616. =item h_min => $sec This is the lower limit of the heuristic expiry age to use. The default is C<60> (1 minute). =item h_max => $sec This is the upper limit of the heuristic expiry age to use. The default is C<86400> (24 hours). =item h_default => $sec This is the expiry age to use when nothing else applies. The default is C<3600> (1 hour) or "h_min" if greater. =back =item $r->is_fresh( %opt ) Returns TRUE if the response is fresh, based on the values of freshness_lifetime() and current_age(). If the response is no longer fresh, then it has to be re-fetched or re-validated by the origin server. Options might be passed to control expiry heuristics, see the description of freshness_lifetime(). =item $r->fresh_until( %opt ) Returns the time (seconds since epoch) when this entity is no longer fresh. Options might be passed to control expiry heuristics, see the description of freshness_lifetime(). =back =head1 SEE ALSO L, L, L, L =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: HTTP style response message PK!÷�L==perl5/HTTP/Tiny.pmnuÏÃ6Ç$# vim: ts=4 sts=4 sw=4 et: package HTTP::Tiny; use strict; use warnings; # ABSTRACT: A small, simple, correct HTTP/1.1 client our $VERSION = '0.088'; sub _croak { require Carp; Carp::croak(@_) } #pod =method new #pod #pod $http = HTTP::Tiny->new( %attributes ); #pod #pod This constructor returns a new HTTP::Tiny object. Valid attributes include: #pod #pod =for :list #pod * C — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If #pod C — ends in a space character, the default user-agent string is #pod appended. #pod * C — An instance of L — or equivalent class #pod that supports the C and C methods #pod * C — A hashref of default headers to apply to requests #pod * C — The local IP address to bind to #pod * C — Whether to reuse the last connection (if for the same #pod scheme, host and port) (defaults to 1) #pod * C — Maximum number of redirects allowed (defaults to 5) #pod * C — Maximum response size in bytes (only when not using a data #pod callback). If defined, requests with responses larger than this will return #pod a 599 status code. #pod * C — URL of a proxy server to use for HTTP connections #pod (default is C<$ENV{http_proxy}> — if set) #pod * C — URL of a proxy server to use for HTTPS connections #pod (default is C<$ENV{https_proxy}> — if set) #pod * C — URL of a generic proxy server for both HTTP and HTTPS #pod connections (default is C<$ENV{all_proxy}> — if set) #pod * C — List of domain suffixes that should not be proxied. Must #pod be a comma-separated string or an array reference. (default is #pod C<$ENV{no_proxy}> —) #pod * C — Request timeout in seconds (default is 60) If a socket open, #pod read or write takes longer than the timeout, the request response status code #pod will be 599. #pod * C — A boolean that indicates whether to validate the TLS/SSL #pod certificate of an C — connection (default is true). Changed from false #pod to true in version 0.083. #pod * C — A hashref of C — options to pass through to #pod L #pod * C<$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}> - Changes the default #pod certificate verification behavior to not check server identity if set to 1. #pod Only effective if C is not set. Added in version 0.083. #pod #pod #pod An accessor/mutator method exists for each attribute. #pod #pod Passing an explicit C for C, C or C will #pod prevent getting the corresponding proxies from the environment. #pod #pod Errors during request execution will result in a pseudo-HTTP status code of 599 #pod and a reason of "Internal Exception". The content field in the response will #pod contain the text of the error. #pod #pod The C parameter enables a persistent connection, but only to a #pod single destination scheme, host and port. If any connection-relevant #pod attributes are modified via accessor, or if the process ID or thread ID change, #pod the persistent connection will be dropped. If you want persistent connections #pod across multiple destinations, use multiple HTTP::Tiny objects. #pod #pod See L for more on the C and C attributes. #pod #pod =cut my @attributes; BEGIN { @attributes = qw( cookie_jar default_headers http_proxy https_proxy keep_alive local_address max_redirect max_size proxy no_proxy SSL_options verify_SSL ); my %persist_ok = map {; $_ => 1 } qw( cookie_jar default_headers max_redirect max_size ); no strict 'refs'; no warnings 'uninitialized'; for my $accessor ( @attributes ) { *{$accessor} = sub { @_ > 1 ? do { delete $_[0]->{handle} if !$persist_ok{$accessor} && $_[1] ne $_[0]->{$accessor}; $_[0]->{$accessor} = $_[1] } : $_[0]->{$accessor}; }; } } sub agent { my($self, $agent) = @_; if( @_ > 1 ){ $self->{agent} = (defined $agent && $agent =~ / $/) ? $agent . $self->_agent : $agent; } return $self->{agent}; } sub timeout { my ($self, $timeout) = @_; if ( @_ > 1 ) { $self->{timeout} = $timeout; if ($self->{handle}) { $self->{handle}->timeout($timeout); } } return $self->{timeout}; } sub new { my($class, %args) = @_; # Support lower case verify_ssl argument, but only if verify_SSL is not # true. if ( exists $args{verify_ssl} ) { $args{verify_SSL} ||= $args{verify_ssl}; } my $self = { max_redirect => 5, timeout => defined $args{timeout} ? $args{timeout} : 60, keep_alive => 1, verify_SSL => defined $args{verify_SSL} ? $args{verify_SSL} : _verify_SSL_default(), no_proxy => $ENV{no_proxy}, }; bless $self, $class; $class->_validate_cookie_jar( $args{cookie_jar} ) if $args{cookie_jar}; for my $key ( @attributes ) { $self->{$key} = $args{$key} if exists $args{$key} } $self->agent( exists $args{agent} ? $args{agent} : $class->_agent ); $self->_set_proxies; return $self; } sub _verify_SSL_default { my ($self) = @_; # Check if insecure default certificate verification behaviour has been # changed by the user by setting PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT=1 return (($ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT} || '') eq '1') ? 0 : 1; } sub _set_proxies { my ($self) = @_; # get proxies from %ENV only if not provided; explicit undef will disable # getting proxies from the environment # generic proxy if (! exists $self->{proxy} ) { $self->{proxy} = $ENV{all_proxy} || $ENV{ALL_PROXY}; } if ( defined $self->{proxy} ) { $self->_split_proxy( 'generic proxy' => $self->{proxy} ); # validate } else { delete $self->{proxy}; } # http proxy if (! exists $self->{http_proxy} ) { # under CGI, bypass HTTP_PROXY as request sets it from Proxy header local $ENV{HTTP_PROXY} = ($ENV{CGI_HTTP_PROXY} || "") if $ENV{REQUEST_METHOD}; $self->{http_proxy} = $ENV{http_proxy} || $ENV{HTTP_PROXY} || $self->{proxy}; } if ( defined $self->{http_proxy} ) { $self->_split_proxy( http_proxy => $self->{http_proxy} ); # validate $self->{_has_proxy}{http} = 1; } else { delete $self->{http_proxy}; } # https proxy if (! exists $self->{https_proxy} ) { $self->{https_proxy} = $ENV{https_proxy} || $ENV{HTTPS_PROXY} || $self->{proxy}; } if ( $self->{https_proxy} ) { $self->_split_proxy( https_proxy => $self->{https_proxy} ); # validate $self->{_has_proxy}{https} = 1; } else { delete $self->{https_proxy}; } # Split no_proxy to array reference if not provided as such unless ( ref $self->{no_proxy} eq 'ARRAY' ) { $self->{no_proxy} = (defined $self->{no_proxy}) ? [ split /\s*,\s*/, $self->{no_proxy} ] : []; } return; } #pod =method get|head|put|post|patch|delete #pod #pod $response = $http->get($url); #pod $response = $http->get($url, \%options); #pod $response = $http->head($url); #pod #pod These methods are shorthand for calling C for the given method. The #pod URL must have unsafe characters escaped and international domain names encoded. #pod See C for valid options and a description of the response. #pod #pod The C field of the response will be true if the status code is 2XX. #pod #pod =cut for my $sub_name ( qw/get head put post patch delete/ ) { my $req_method = uc $sub_name; no strict 'refs'; eval <<"HERE"; ## no critic sub $sub_name { my (\$self, \$url, \$args) = \@_; \@_ == 2 || (\@_ == 3 && ref \$args eq 'HASH') or _croak(q/Usage: \$http->$sub_name(URL, [HASHREF])/ . "\n"); return \$self->request('$req_method', \$url, \$args || {}); } HERE } #pod =method post_form #pod #pod $response = $http->post_form($url, $form_data); #pod $response = $http->post_form($url, $form_data, \%options); #pod #pod This method executes a C request and sends the key/value pairs from a #pod form data hash or array reference to the given URL with a C of #pod C. If data is provided as an array #pod reference, the order is preserved; if provided as a hash reference, the terms #pod are sorted on key and value for consistency. See documentation for the #pod C method for details on the encoding. #pod #pod The URL must have unsafe characters escaped and international domain names #pod encoded. See C for valid options and a description of the response. #pod Any C header or content in the options hashref will be ignored. #pod #pod The C field of the response will be true if the status code is 2XX. #pod #pod =cut sub post_form { my ($self, $url, $data, $args) = @_; (@_ == 3 || @_ == 4 && ref $args eq 'HASH') or _croak(q/Usage: $http->post_form(URL, DATAREF, [HASHREF])/ . "\n"); my $headers = {}; while ( my ($key, $value) = each %{$args->{headers} || {}} ) { $headers->{lc $key} = $value; } return $self->request('POST', $url, { # Any existing 'headers' key in $args will be overridden with a # normalized version below. %$args, content => $self->www_form_urlencode($data), headers => { %$headers, 'content-type' => 'application/x-www-form-urlencoded' }, } ); } #pod =method mirror #pod #pod $response = $http->mirror($url, $file, \%options) #pod if ( $response->{success} ) { #pod print "$file is up to date\n"; #pod } #pod #pod Executes a C request for the URL and saves the response body to the file #pod name provided. The URL must have unsafe characters escaped and international #pod domain names encoded. If the file already exists, the request will include an #pod C header with the modification timestamp of the file. You #pod may specify a different C header yourself in the C<< #pod $options->{headers} >> hash. #pod #pod The C field of the response will be true if the status code is 2XX #pod or if the status code is 304 (unmodified). #pod #pod If the file was modified and the server response includes a properly #pod formatted C header, the file modification time will #pod be updated accordingly. #pod #pod =cut sub mirror { my ($self, $url, $file, $args) = @_; @_ == 3 || (@_ == 4 && ref $args eq 'HASH') or _croak(q/Usage: $http->mirror(URL, FILE, [HASHREF])/ . "\n"); if ( exists $args->{headers} ) { my $headers = {}; while ( my ($key, $value) = each %{$args->{headers} || {}} ) { $headers->{lc $key} = $value; } $args->{headers} = $headers; } if ( -e $file and my $mtime = (stat($file))[9] ) { $args->{headers}{'if-modified-since'} ||= $self->_http_date($mtime); } my $tempfile = $file . int(rand(2**31)); require Fcntl; sysopen my $fh, $tempfile, Fcntl::O_CREAT()|Fcntl::O_EXCL()|Fcntl::O_WRONLY() or _croak(qq/Error: Could not create temporary file $tempfile for downloading: $!\n/); binmode $fh; $args->{data_callback} = sub { print {$fh} $_[0] }; my $response = $self->request('GET', $url, $args); close $fh or _croak(qq/Error: Caught error closing temporary file $tempfile: $!\n/); if ( $response->{success} ) { rename $tempfile, $file or _croak(qq/Error replacing $file with $tempfile: $!\n/); my $lm = $response->{headers}{'last-modified'}; if ( $lm and my $mtime = $self->_parse_http_date($lm) ) { utime $mtime, $mtime, $file; } } $response->{success} ||= $response->{status} eq '304'; unlink $tempfile; return $response; } #pod =method request #pod #pod $response = $http->request($method, $url); #pod $response = $http->request($method, $url, \%options); #pod #pod Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST', #pod 'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and #pod international domain names encoded. #pod #pod B: Method names are B per the HTTP/1.1 specification. #pod Don't use C when you really want C. See L for #pod how this applies to redirection. #pod #pod If the URL includes a "user:password" stanza, they will be used for Basic-style #pod authorization headers. (Authorization headers will not be included in a #pod redirected request.) For example: #pod #pod $http->request('GET', 'http://Aladdin:open sesame@example.com/'); #pod #pod If the "user:password" stanza contains reserved characters, they must #pod be percent-escaped: #pod #pod $http->request('GET', 'http://john%40example.com:password@example.com/'); #pod #pod A hashref of options may be appended to modify the request. #pod #pod Valid options are: #pod #pod =for :list #pod * C — #pod A hashref containing headers to include with the request. If the value for #pod a header is an array reference, the header will be output multiple times with #pod each value in the array. These headers over-write any default headers. #pod * C — #pod A scalar to include as the body of the request OR a code reference #pod that will be called iteratively to produce the body of the request #pod * C — #pod A code reference that will be called if it exists to provide a hashref #pod of trailing headers (only used with chunked transfer-encoding) #pod * C — #pod A code reference that will be called for each chunks of the response #pod body received. #pod * C — #pod Override host resolution and force all connections to go only to a #pod specific peer address, regardless of the URL of the request. This will #pod include any redirections! This options should be used with extreme #pod caution (e.g. debugging or very special circumstances). It can be given as #pod either a scalar or a code reference that will receive the hostname and #pod whose response will be taken as the address. #pod #pod The C header is generated from the URL in accordance with RFC 2616. It #pod is a fatal error to specify C in the C option. Other headers #pod may be ignored or overwritten if necessary for transport compliance. #pod #pod If the C option is a code reference, it will be called iteratively #pod to provide the content body of the request. It should return the empty #pod string or undef when the iterator is exhausted. #pod #pod If the C option is the empty string, no C or #pod C headers will be generated. #pod #pod If the C option is provided, it will be called iteratively until #pod the entire response body is received. The first argument will be a string #pod containing a chunk of the response body, the second argument will be the #pod in-progress response hash reference, as described below. (This allows #pod customizing the action of the callback based on the C or C #pod received prior to the content body.) #pod #pod Content data in the request/response is handled as "raw bytes". Any #pod encoding/decoding (with associated headers) are the responsibility of the #pod caller. #pod #pod The C method returns a hashref containing the response. The hashref #pod will have the following keys: #pod #pod =for :list #pod * C — #pod Boolean indicating whether the operation returned a 2XX status code #pod * C — #pod URL that provided the response. This is the URL of the request unless #pod there were redirections, in which case it is the last URL queried #pod in a redirection chain #pod * C — #pod The HTTP status code of the response #pod * C — #pod The response phrase returned by the server #pod * C — #pod The body of the response. If the response does not have any content #pod or if a data callback is provided to consume the response body, #pod this will be the empty string #pod * C — #pod A hashref of header fields. All header field names will be normalized #pod to be lower case. If a header is repeated, the value will be an arrayref; #pod it will otherwise be a scalar string containing the value #pod * C - #pod If this field exists, it is the protocol of the response #pod such as HTTP/1.0 or HTTP/1.1 #pod * C #pod If this field exists, it is an arrayref of response hash references from #pod redirects in the same order that redirections occurred. If it does #pod not exist, then no redirections occurred. #pod #pod On an error during the execution of the request, the C field will #pod contain 599, and the C field will contain the text of the error. #pod #pod =cut my %idempotent = map { $_ => 1 } qw/GET HEAD PUT DELETE OPTIONS TRACE/; sub request { my ($self, $method, $url, $args) = @_; @_ == 3 || (@_ == 4 && ref $args eq 'HASH') or _croak(q/Usage: $http->request(METHOD, URL, [HASHREF])/ . "\n"); $args ||= {}; # we keep some state in this during _request # RFC 2616 Section 8.1.4 mandates a single retry on broken socket my $response; for ( 0 .. 1 ) { $response = eval { $self->_request($method, $url, $args) }; last unless $@ && $idempotent{$method} && $@ =~ m{^(?:Socket closed|Unexpected end|SSL read error)}; } if (my $e = $@) { # maybe we got a response hash thrown from somewhere deep if ( ref $e eq 'HASH' && exists $e->{status} ) { $e->{redirects} = delete $args->{_redirects} if @{ $args->{_redirects} || []}; return $e; } # otherwise, stringify it $e = "$e"; $response = { url => $url, success => q{}, status => 599, reason => 'Internal Exception', content => $e, headers => { 'content-type' => 'text/plain', 'content-length' => length $e, }, ( @{$args->{_redirects} || []} ? (redirects => delete $args->{_redirects}) : () ), }; } return $response; } #pod =method www_form_urlencode #pod #pod $params = $http->www_form_urlencode( $data ); #pod $response = $http->get("http://example.com/query?$params"); #pod #pod This method converts the key/value pairs from a data hash or array reference #pod into a C string. The keys and values from the data #pod reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an #pod array reference, the key will be repeated with each of the values of the array #pod reference. If data is provided as a hash reference, the key/value pairs in the #pod resulting string will be sorted by key and value for consistent ordering. #pod #pod =cut sub www_form_urlencode { my ($self, $data) = @_; (@_ == 2 && ref $data) or _croak(q/Usage: $http->www_form_urlencode(DATAREF)/ . "\n"); (ref $data eq 'HASH' || ref $data eq 'ARRAY') or _croak("form data must be a hash or array reference\n"); my @params = ref $data eq 'HASH' ? %$data : @$data; @params % 2 == 0 or _croak("form data reference must have an even number of terms\n"); my @terms; while( @params ) { my ($key, $value) = splice(@params, 0, 2); _croak("form data keys must not be undef") if !defined($key); if ( ref $value eq 'ARRAY' ) { unshift @params, map { $key => $_ } @$value; } else { push @terms, join("=", map { $self->_uri_escape($_) } $key, $value); } } return join("&", (ref $data eq 'ARRAY') ? (@terms) : (sort @terms) ); } #pod =method can_ssl #pod #pod $ok = HTTP::Tiny->can_ssl; #pod ($ok, $why) = HTTP::Tiny->can_ssl; #pod ($ok, $why) = $http->can_ssl; #pod #pod Indicates if SSL support is available. When called as a class object, it #pod checks for the correct version of L and L. #pod When called as an object methods, if C is true or if C #pod is set in C, it checks that a CA file is available. #pod #pod In scalar context, returns a boolean indicating if SSL is available. #pod In list context, returns the boolean and a (possibly multi-line) string of #pod errors indicating why SSL isn't available. #pod #pod =cut sub can_ssl { my ($self) = @_; my($ok, $reason) = (1, ''); # Need IO::Socket::SSL 1.42 for SSL_create_ctx_callback local @INC = @INC; pop @INC if $INC[-1] eq '.'; unless (eval {require IO::Socket::SSL; IO::Socket::SSL->VERSION(1.42)}) { $ok = 0; $reason .= qq/IO::Socket::SSL 1.42 must be installed for https support\n/; } # Need Net::SSLeay 1.49 for MODE_AUTO_RETRY unless (eval {require Net::SSLeay; Net::SSLeay->VERSION(1.49)}) { $ok = 0; $reason .= qq/Net::SSLeay 1.49 must be installed for https support\n/; } # If an object, check that SSL config lets us get a CA if necessary if ( ref($self) && ( $self->{verify_SSL} || $self->{SSL_options}{SSL_verify_mode} ) ) { my $handle = HTTP::Tiny::Handle->new( SSL_options => $self->{SSL_options}, verify_SSL => $self->{verify_SSL}, ); unless ( eval { $handle->_find_CA_file; 1 } ) { $ok = 0; $reason .= "$@"; } } wantarray ? ($ok, $reason) : $ok; } #pod =method connected #pod #pod $host = $http->connected; #pod ($host, $port) = $http->connected; #pod #pod Indicates if a connection to a peer is being kept alive, per the C #pod option. #pod #pod In scalar context, returns the peer host and port, joined with a colon, or #pod C (if no peer is connected). #pod In list context, returns the peer host and port or an empty list (if no peer #pod is connected). #pod #pod B: This method cannot reliably be used to discover whether the remote #pod host has closed its end of the socket. #pod #pod =cut sub connected { my ($self) = @_; if ( $self->{handle} ) { return $self->{handle}->connected; } return; } #--------------------------------------------------------------------------# # private methods #--------------------------------------------------------------------------# my %DefaultPort = ( http => 80, https => 443, ); sub _agent { my $class = ref($_[0]) || $_[0]; (my $default_agent = $class) =~ s{::}{-}g; my $version = $class->VERSION; $default_agent .= "/$version" if defined $version; return $default_agent; } sub _request { my ($self, $method, $url, $args) = @_; my ($scheme, $host, $port, $path_query, $auth) = $self->_split_url($url); if ($scheme ne 'http' && $scheme ne 'https') { die(qq/Unsupported URL scheme '$scheme'\n/); } my $request = { method => $method, scheme => $scheme, host => $host, port => $port, host_port => ($port == $DefaultPort{$scheme} ? $host : "$host:$port"), uri => $path_query, headers => {}, }; my $peer = $args->{peer} || $host; # Allow 'peer' to be a coderef. if ('CODE' eq ref $peer) { $peer = $peer->($host); } # We remove the cached handle so it is not reused in the case of redirect. # If all is well, it will be recached at the end of _request. We only # reuse for the same scheme, host and port my $handle = delete $self->{handle}; if ( $handle ) { unless ( $handle->can_reuse( $scheme, $host, $port, $peer ) ) { $handle->close; undef $handle; } } $handle ||= $self->_open_handle( $request, $scheme, $host, $port, $peer ); $self->_prepare_headers_and_cb($request, $args, $url, $auth); $handle->write_request($request); my $response; do { $response = $handle->read_response_header } until (substr($response->{status},0,1) ne '1'); $self->_update_cookie_jar( $url, $response ) if $self->{cookie_jar}; my @redir_args = $self->_maybe_redirect($request, $response, $args); my $known_message_length; if ($method eq 'HEAD' || $response->{status} =~ /^[23]04/) { # response has no message body $known_message_length = 1; } else { # Ignore any data callbacks during redirection. my $cb_args = @redir_args ? +{} : $args; my $data_cb = $self->_prepare_data_cb($response, $cb_args); $known_message_length = $handle->read_body($data_cb, $response); } if ( $self->{keep_alive} && $handle->connected && $known_message_length && $response->{protocol} eq 'HTTP/1.1' && ($response->{headers}{connection} || '') ne 'close' ) { $self->{handle} = $handle; } else { $handle->close; } $response->{success} = substr( $response->{status}, 0, 1 ) eq '2'; $response->{url} = $url; # Push the current response onto the stack of redirects if redirecting. if (@redir_args) { push @{$args->{_redirects}}, $response; return $self->_request(@redir_args, $args); } # Copy the stack of redirects into the response before returning. $response->{redirects} = delete $args->{_redirects} if @{$args->{_redirects}}; return $response; } sub _open_handle { my ($self, $request, $scheme, $host, $port, $peer) = @_; my $handle = HTTP::Tiny::Handle->new( timeout => $self->{timeout}, SSL_options => $self->{SSL_options}, verify_SSL => $self->{verify_SSL}, local_address => $self->{local_address}, keep_alive => $self->{keep_alive} ); if ($self->{_has_proxy}{$scheme} && ! grep { $host =~ /\Q$_\E$/ } @{$self->{no_proxy}}) { return $self->_proxy_connect( $request, $handle ); } else { return $handle->connect($scheme, $host, $port, $peer); } } sub _proxy_connect { my ($self, $request, $handle) = @_; my @proxy_vars; if ( $request->{scheme} eq 'https' ) { _croak(qq{No https_proxy defined}) unless $self->{https_proxy}; @proxy_vars = $self->_split_proxy( https_proxy => $self->{https_proxy} ); if ( $proxy_vars[0] eq 'https' ) { _croak(qq{Can't proxy https over https: $request->{uri} via $self->{https_proxy}}); } } else { _croak(qq{No http_proxy defined}) unless $self->{http_proxy}; @proxy_vars = $self->_split_proxy( http_proxy => $self->{http_proxy} ); } my ($p_scheme, $p_host, $p_port, $p_auth) = @proxy_vars; if ( length $p_auth && ! defined $request->{headers}{'proxy-authorization'} ) { $self->_add_basic_auth_header( $request, 'proxy-authorization' => $p_auth ); } $handle->connect($p_scheme, $p_host, $p_port, $p_host); if ($request->{scheme} eq 'https') { $self->_create_proxy_tunnel( $request, $handle ); } else { # non-tunneled proxy requires absolute URI $request->{uri} = "$request->{scheme}://$request->{host_port}$request->{uri}"; } return $handle; } sub _split_proxy { my ($self, $type, $proxy) = @_; my ($scheme, $host, $port, $path_query, $auth) = eval { $self->_split_url($proxy) }; unless( defined($scheme) && length($scheme) && length($host) && length($port) && $path_query eq '/' ) { _croak(qq{$type URL must be in format http[s]://[auth@]:/\n}); } return ($scheme, $host, $port, $auth); } sub _create_proxy_tunnel { my ($self, $request, $handle) = @_; $handle->_assert_ssl; my $agent = exists($request->{headers}{'user-agent'}) ? $request->{headers}{'user-agent'} : $self->{agent}; my $connect_request = { method => 'CONNECT', uri => "$request->{host}:$request->{port}", headers => { host => "$request->{host}:$request->{port}", 'user-agent' => $agent, } }; if ( $request->{headers}{'proxy-authorization'} ) { $connect_request->{headers}{'proxy-authorization'} = delete $request->{headers}{'proxy-authorization'}; } $handle->write_request($connect_request); my $response; do { $response = $handle->read_response_header } until (substr($response->{status},0,1) ne '1'); # if CONNECT failed, throw the response so it will be # returned from the original request() method; unless (substr($response->{status},0,1) eq '2') { die $response; } # tunnel established, so start SSL handshake $handle->start_ssl( $request->{host} ); return; } sub _prepare_headers_and_cb { my ($self, $request, $args, $url, $auth) = @_; for ($self->{default_headers}, $args->{headers}) { next unless defined; while (my ($k, $v) = each %$_) { $request->{headers}{lc $k} = $v; $request->{header_case}{lc $k} = $k; } } if (exists $request->{headers}{'host'}) { die(qq/The 'Host' header must not be provided as header option\n/); } $request->{headers}{'host'} = $request->{host_port}; $request->{headers}{'user-agent'} ||= $self->{agent}; $request->{headers}{'connection'} = "close" unless $self->{keep_alive}; # Some servers error on an empty-body PUT/POST without a content-length if ( $request->{method} eq 'PUT' || $request->{method} eq 'POST' ) { if (!defined($args->{content}) || !length($args->{content}) ) { $request->{headers}{'content-length'} = 0; } } if ( defined $args->{content} ) { if ( ref $args->{content} eq 'CODE' ) { if ( exists $request->{'content-length'} && $request->{'content-length'} == 0 ) { $request->{cb} = sub { "" }; } else { $request->{headers}{'content-type'} ||= "application/octet-stream"; $request->{headers}{'transfer-encoding'} = 'chunked' unless exists $request->{headers}{'content-length'} || $request->{headers}{'transfer-encoding'}; $request->{cb} = $args->{content}; } } elsif ( length $args->{content} ) { my $content = $args->{content}; if ( $] ge '5.008' ) { utf8::downgrade($content, 1) or die(qq/Wide character in request message body\n/); } $request->{headers}{'content-type'} ||= "application/octet-stream"; $request->{headers}{'content-length'} = length $content unless $request->{headers}{'content-length'} || $request->{headers}{'transfer-encoding'}; $request->{cb} = sub { substr $content, 0, length $content, '' }; } $request->{trailer_cb} = $args->{trailer_callback} if ref $args->{trailer_callback} eq 'CODE'; } ### If we have a cookie jar, then maybe add relevant cookies if ( $self->{cookie_jar} ) { my $cookies = $self->cookie_jar->cookie_header( $url ); $request->{headers}{cookie} = $cookies if length $cookies; } # if we have Basic auth parameters, add them if ( length $auth && ! defined $request->{headers}{authorization} ) { $self->_add_basic_auth_header( $request, 'authorization' => $auth ); } return; } sub _add_basic_auth_header { my ($self, $request, $header, $auth) = @_; require MIME::Base64; $request->{headers}{$header} = "Basic " . MIME::Base64::encode_base64($auth, ""); return; } sub _prepare_data_cb { my ($self, $response, $args) = @_; my $data_cb = $args->{data_callback}; $response->{content} = ''; if (!$data_cb || $response->{status} !~ /^2/) { if (defined $self->{max_size}) { $data_cb = sub { $_[1]->{content} .= $_[0]; die(qq/Size of response body exceeds the maximum allowed of $self->{max_size}\n/) if length $_[1]->{content} > $self->{max_size}; }; } else { $data_cb = sub { $_[1]->{content} .= $_[0] }; } } return $data_cb; } sub _update_cookie_jar { my ($self, $url, $response) = @_; my $cookies = $response->{headers}->{'set-cookie'}; return unless defined $cookies; my @cookies = ref $cookies ? @$cookies : $cookies; $self->cookie_jar->add( $url, $_ ) for @cookies; return; } sub _validate_cookie_jar { my ($class, $jar) = @_; # duck typing for my $method ( qw/add cookie_header/ ) { _croak(qq/Cookie jar must provide the '$method' method\n/) unless ref($jar) && ref($jar)->can($method); } return; } sub _maybe_redirect { my ($self, $request, $response, $args) = @_; my $headers = $response->{headers}; my ($status, $method) = ($response->{status}, $request->{method}); $args->{_redirects} ||= []; if (($status eq '303' or ($status =~ /^30[1278]/ && $method =~ /^GET|HEAD$/)) and $headers->{location} and @{$args->{_redirects}} < $self->{max_redirect} ) { my $location = ($headers->{location} =~ /^\//) ? "$request->{scheme}://$request->{host_port}$headers->{location}" : $headers->{location} ; return (($status eq '303' ? 'GET' : $method), $location); } return; } sub _split_url { my $url = pop; # URI regex adapted from the URI module my ($scheme, $host, $path_query) = $url =~ m<\A([^:/?#]+)://([^/?#]*)([^#]*)> or die(qq/Cannot parse URL: '$url'\n/); $scheme = lc $scheme; $path_query = "/$path_query" unless $path_query =~ m<\A/>; my $auth = ''; if ( (my $i = index $host, '@') != -1 ) { # user:pass@host $auth = substr $host, 0, $i, ''; # take up to the @ for auth substr $host, 0, 1, ''; # knock the @ off the host # userinfo might be percent escaped, so recover real auth info $auth =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg; } my $port = $host =~ s/:(\d*)\z// && length $1 ? $1 : $scheme eq 'http' ? 80 : $scheme eq 'https' ? 443 : undef; return ($scheme, (length $host ? lc $host : "localhost") , $port, $path_query, $auth); } # Date conversions adapted from HTTP::Date my $DoW = "Sun|Mon|Tue|Wed|Thu|Fri|Sat"; my $MoY = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec"; sub _http_date { my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($_[1]); return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", substr($DoW,$wday*4,3), $mday, substr($MoY,$mon*4,3), $year+1900, $hour, $min, $sec ); } sub _parse_http_date { my ($self, $str) = @_; require Time::Local; my @tl_parts; if ($str =~ /^[SMTWF][a-z]+, +(\d{1,2}) ($MoY) +(\d\d\d\d) +(\d\d):(\d\d):(\d\d) +GMT$/) { @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3); } elsif ($str =~ /^[SMTWF][a-z]+, +(\d\d)-($MoY)-(\d{2,4}) +(\d\d):(\d\d):(\d\d) +GMT$/ ) { @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3); } elsif ($str =~ /^[SMTWF][a-z]+ +($MoY) +(\d{1,2}) +(\d\d):(\d\d):(\d\d) +(?:[^0-9]+ +)?(\d\d\d\d)$/ ) { @tl_parts = ($5, $4, $3, $2, (index($MoY,$1)/4), $6); } return eval { my $t = @tl_parts ? Time::Local::timegm(@tl_parts) : -1; $t < 0 ? undef : $t; }; } # URI escaping adapted from URI::Escape # c.f. http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1 # perl 5.6 ready UTF-8 encoding adapted from JSON::PP my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255; $escapes{' '}="+"; my $unsafe_char = qr/[^A-Za-z0-9\-\._~]/; sub _uri_escape { my ($self, $str) = @_; return "" if !defined $str; if ( $] ge '5.008' ) { utf8::encode($str); } else { $str = pack("U*", unpack("C*", $str)) # UTF-8 encode a byte string if ( length $str == do { use bytes; length $str } ); $str = pack("C*", unpack("C*", $str)); # clear UTF-8 flag } $str =~ s/($unsafe_char)/$escapes{$1}/g; return $str; } package HTTP::Tiny::Handle; # hide from PAUSE/indexers use strict; use warnings; use Errno qw[EINTR EPIPE]; use IO::Socket qw[SOCK_STREAM]; use Socket qw[SOL_SOCKET SO_KEEPALIVE]; # PERL_HTTP_TINY_IPV4_ONLY is a private environment variable to force old # behavior if someone is unable to boostrap CPAN from a new perl install; it is # not intended for general, per-client use and may be removed in the future my $SOCKET_CLASS = $ENV{PERL_HTTP_TINY_IPV4_ONLY} ? 'IO::Socket::INET' : eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.32) } ? 'IO::Socket::IP' : 'IO::Socket::INET'; sub BUFSIZE () { 32768 } ## no critic my $Printable = sub { local $_ = shift; s/\r/\\r/g; s/\n/\\n/g; s/\t/\\t/g; s/([^\x20-\x7E])/sprintf('\\x%.2X', ord($1))/ge; $_; }; my $Token = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/; my $Field_Content = qr/[[:print:]]+ (?: [\x20\x09]+ [[:print:]]+ )*/x; sub new { my ($class, %args) = @_; return bless { rbuf => '', timeout => 60, max_line_size => 16384, max_header_lines => 64, verify_SSL => HTTP::Tiny::_verify_SSL_default(), SSL_options => {}, %args }, $class; } sub timeout { my ($self, $timeout) = @_; if ( @_ > 1 ) { $self->{timeout} = $timeout; if ( $self->{fh} && $self->{fh}->can('timeout') ) { $self->{fh}->timeout($timeout); } } return $self->{timeout}; } sub connect { @_ == 5 || die(q/Usage: $handle->connect(scheme, host, port, peer)/ . "\n"); my ($self, $scheme, $host, $port, $peer) = @_; if ( $scheme eq 'https' ) { $self->_assert_ssl; } $self->{fh} = $SOCKET_CLASS->new( PeerHost => $peer, PeerPort => $port, $self->{local_address} ? ( LocalAddr => $self->{local_address} ) : (), Proto => 'tcp', Type => SOCK_STREAM, Timeout => $self->{timeout}, ) or die(qq/Could not connect to '$host:$port': $@\n/); binmode($self->{fh}) or die(qq/Could not binmode() socket: '$!'\n/); if ( $self->{keep_alive} ) { unless ( defined( $self->{fh}->setsockopt( SOL_SOCKET, SO_KEEPALIVE, 1 ) ) ) { CORE::close($self->{fh}); die(qq/Could not set SO_KEEPALIVE on socket: '$!'\n/); } } $self->start_ssl($host) if $scheme eq 'https'; $self->{scheme} = $scheme; $self->{host} = $host; $self->{peer} = $peer; $self->{port} = $port; $self->{pid} = $$; $self->{tid} = _get_tid(); return $self; } sub connected { my ($self) = @_; if ( $self->{fh} && $self->{fh}->connected ) { return wantarray ? ( $self->{fh}->peerhost, $self->{fh}->peerport ) : join( ':', $self->{fh}->peerhost, $self->{fh}->peerport ); } return; } sub start_ssl { my ($self, $host) = @_; # As this might be used via CONNECT after an SSL session # to a proxy, we shut down any existing SSL before attempting # the handshake if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) { unless ( $self->{fh}->stop_SSL ) { my $ssl_err = IO::Socket::SSL->errstr; die(qq/Error halting prior SSL connection: $ssl_err/); } } my $ssl_args = $self->_ssl_args($host); IO::Socket::SSL->start_SSL( $self->{fh}, %$ssl_args, SSL_create_ctx_callback => sub { my $ctx = shift; Net::SSLeay::CTX_set_mode($ctx, Net::SSLeay::MODE_AUTO_RETRY()); }, ); unless ( ref($self->{fh}) eq 'IO::Socket::SSL' ) { my $ssl_err = IO::Socket::SSL->errstr; die(qq/SSL connection failed for $host: $ssl_err\n/); } } sub close { @_ == 1 || die(q/Usage: $handle->close()/ . "\n"); my ($self) = @_; CORE::close($self->{fh}) or die(qq/Could not close socket: '$!'\n/); } sub write { @_ == 2 || die(q/Usage: $handle->write(buf)/ . "\n"); my ($self, $buf) = @_; if ( $] ge '5.008' ) { utf8::downgrade($buf, 1) or die(qq/Wide character in write()\n/); } my $len = length $buf; my $off = 0; local $SIG{PIPE} = 'IGNORE'; while () { $self->can_write or die(qq/Timed out while waiting for socket to become ready for writing\n/); my $r = syswrite($self->{fh}, $buf, $len, $off); if (defined $r) { $len -= $r; $off += $r; last unless $len > 0; } elsif ($! == EPIPE) { die(qq/Socket closed by remote server: $!\n/); } elsif ($! != EINTR) { if ($self->{fh}->can('errstr')){ my $err = $self->{fh}->errstr(); die (qq/Could not write to SSL socket: '$err'\n /); } else { die(qq/Could not write to socket: '$!'\n/); } } } return $off; } sub read { @_ == 2 || @_ == 3 || die(q/Usage: $handle->read(len [, allow_partial])/ . "\n"); my ($self, $len, $allow_partial) = @_; my $buf = ''; my $got = length $self->{rbuf}; if ($got) { my $take = ($got < $len) ? $got : $len; $buf = substr($self->{rbuf}, 0, $take, ''); $len -= $take; } # Ignore SIGPIPE because SSL reads can result in writes that might error. # See "Expecting exactly the same behavior as plain sockets" in # https://metacpan.org/dist/IO-Socket-SSL/view/lib/IO/Socket/SSL.pod#Common-Usage-Errors local $SIG{PIPE} = 'IGNORE'; while ($len > 0) { $self->can_read or die(q/Timed out while waiting for socket to become ready for reading/ . "\n"); my $r = sysread($self->{fh}, $buf, $len, length $buf); if (defined $r) { last unless $r; $len -= $r; } elsif ($! != EINTR) { if ($self->{fh}->can('errstr')){ my $err = $self->{fh}->errstr(); die (qq/Could not read from SSL socket: '$err'\n /); } else { die(qq/Could not read from socket: '$!'\n/); } } } if ($len && !$allow_partial) { die(qq/Unexpected end of stream\n/); } return $buf; } sub readline { @_ == 1 || die(q/Usage: $handle->readline()/ . "\n"); my ($self) = @_; while () { if ($self->{rbuf} =~ s/\A ([^\x0D\x0A]* \x0D?\x0A)//x) { return $1; } if (length $self->{rbuf} >= $self->{max_line_size}) { die(qq/Line size exceeds the maximum allowed size of $self->{max_line_size}\n/); } $self->can_read or die(qq/Timed out while waiting for socket to become ready for reading\n/); my $r = sysread($self->{fh}, $self->{rbuf}, BUFSIZE, length $self->{rbuf}); if (defined $r) { last unless $r; } elsif ($! != EINTR) { if ($self->{fh}->can('errstr')){ my $err = $self->{fh}->errstr(); die (qq/Could not read from SSL socket: '$err'\n /); } else { die(qq/Could not read from socket: '$!'\n/); } } } die(qq/Unexpected end of stream while looking for line\n/); } sub read_header_lines { @_ == 1 || @_ == 2 || die(q/Usage: $handle->read_header_lines([headers])/ . "\n"); my ($self, $headers) = @_; $headers ||= {}; my $lines = 0; my $val; while () { my $line = $self->readline; if (++$lines >= $self->{max_header_lines}) { die(qq/Header lines exceeds maximum number allowed of $self->{max_header_lines}\n/); } elsif ($line =~ /\A ([^\x00-\x1F\x7F:]+) : [\x09\x20]* ([^\x0D\x0A]*)/x) { my ($field_name) = lc $1; if (exists $headers->{$field_name}) { for ($headers->{$field_name}) { $_ = [$_] unless ref $_ eq "ARRAY"; push @$_, $2; $val = \$_->[-1]; } } else { $val = \($headers->{$field_name} = $2); } } elsif ($line =~ /\A [\x09\x20]+ ([^\x0D\x0A]*)/x) { $val or die(qq/Unexpected header continuation line\n/); next unless length $1; $$val .= ' ' if length $$val; $$val .= $1; } elsif ($line =~ /\A \x0D?\x0A \z/x) { last; } else { die(q/Malformed header line: / . $Printable->($line) . "\n"); } } return $headers; } sub write_request { @_ == 2 || die(q/Usage: $handle->write_request(request)/ . "\n"); my($self, $request) = @_; $self->write_request_header(@{$request}{qw/method uri headers header_case/}); $self->write_body($request) if $request->{cb}; return; } # Standard request header names/case from HTTP/1.1 RFCs my @rfc_request_headers = qw( Accept Accept-Charset Accept-Encoding Accept-Language Authorization Cache-Control Connection Content-Length Expect From Host If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since Max-Forwards Pragma Proxy-Authorization Range Referer TE Trailer Transfer-Encoding Upgrade User-Agent Via ); my @other_request_headers = qw( Content-Encoding Content-MD5 Content-Type Cookie DNT Date Origin X-XSS-Protection ); my %HeaderCase = map { lc($_) => $_ } @rfc_request_headers, @other_request_headers; # to avoid multiple small writes and hence nagle, you can pass the method line or anything else to # combine writes. sub write_header_lines { (@_ >= 2 && @_ <= 4 && ref $_[1] eq 'HASH') || die(q/Usage: $handle->write_header_lines(headers, [header_case, prefix])/ . "\n"); my($self, $headers, $header_case, $prefix_data) = @_; $header_case ||= {}; my $buf = (defined $prefix_data ? $prefix_data : ''); # Per RFC, control fields should be listed first my %seen; for my $k ( qw/host cache-control expect max-forwards pragma range te/ ) { next unless exists $headers->{$k}; $seen{$k}++; my $field_name = $HeaderCase{$k}; my $v = $headers->{$k}; for (ref $v eq 'ARRAY' ? @$v : $v) { $_ = '' unless defined $_; $buf .= "$field_name: $_\x0D\x0A"; } } # Other headers sent in arbitrary order while (my ($k, $v) = each %$headers) { my $field_name = lc $k; next if $seen{$field_name}; if (exists $HeaderCase{$field_name}) { $field_name = $HeaderCase{$field_name}; } else { if (exists $header_case->{$field_name}) { $field_name = $header_case->{$field_name}; } else { $field_name =~ s/\b(\w)/\u$1/g; } $field_name =~ /\A $Token+ \z/xo or die(q/Invalid HTTP header field name: / . $Printable->($field_name) . "\n"); $HeaderCase{lc $field_name} = $field_name; } for (ref $v eq 'ARRAY' ? @$v : $v) { # unwrap a field value if pre-wrapped by user s/\x0D?\x0A\s+/ /g; die(qq/Invalid HTTP header field value ($field_name): / . $Printable->($_). "\n") unless $_ eq '' || /\A $Field_Content \z/xo; $_ = '' unless defined $_; $buf .= "$field_name: $_\x0D\x0A"; } } $buf .= "\x0D\x0A"; return $self->write($buf); } # return value indicates whether message length was defined; this is generally # true unless there was no content-length header and we just read until EOF. # Other message length errors are thrown as exceptions sub read_body { @_ == 3 || die(q/Usage: $handle->read_body(callback, response)/ . "\n"); my ($self, $cb, $response) = @_; my $te = $response->{headers}{'transfer-encoding'} || ''; my $chunked = grep { /chunked/i } ( ref $te eq 'ARRAY' ? @$te : $te ) ; return $chunked ? $self->read_chunked_body($cb, $response) : $self->read_content_body($cb, $response); } sub write_body { @_ == 2 || die(q/Usage: $handle->write_body(request)/ . "\n"); my ($self, $request) = @_; if (exists $request->{headers}{'content-length'}) { return unless $request->{headers}{'content-length'}; return $self->write_content_body($request); } else { return $self->write_chunked_body($request); } } sub read_content_body { @_ == 3 || @_ == 4 || die(q/Usage: $handle->read_content_body(callback, response, [read_length])/ . "\n"); my ($self, $cb, $response, $content_length) = @_; $content_length ||= $response->{headers}{'content-length'}; if ( defined $content_length ) { my $len = $content_length; while ($len > 0) { my $read = ($len > BUFSIZE) ? BUFSIZE : $len; $cb->($self->read($read, 0), $response); $len -= $read; } return length($self->{rbuf}) == 0; } my $chunk; $cb->($chunk, $response) while length( $chunk = $self->read(BUFSIZE, 1) ); return; } sub write_content_body { @_ == 2 || die(q/Usage: $handle->write_content_body(request)/ . "\n"); my ($self, $request) = @_; my ($len, $content_length) = (0, $request->{headers}{'content-length'}); while () { my $data = $request->{cb}->(); defined $data && length $data or last; if ( $] ge '5.008' ) { utf8::downgrade($data, 1) or die(qq/Wide character in write_content()\n/); } $len += $self->write($data); } $len == $content_length or die(qq/Content-Length mismatch (got: $len expected: $content_length)\n/); return $len; } sub read_chunked_body { @_ == 3 || die(q/Usage: $handle->read_chunked_body(callback, $response)/ . "\n"); my ($self, $cb, $response) = @_; while () { my $head = $self->readline; $head =~ /\A ([A-Fa-f0-9]+)/x or die(q/Malformed chunk head: / . $Printable->($head) . "\n"); my $len = hex($1) or last; $self->read_content_body($cb, $response, $len); $self->read(2) eq "\x0D\x0A" or die(qq/Malformed chunk: missing CRLF after chunk data\n/); } $self->read_header_lines($response->{headers}); return 1; } sub write_chunked_body { @_ == 2 || die(q/Usage: $handle->write_chunked_body(request)/ . "\n"); my ($self, $request) = @_; my $len = 0; while () { my $data = $request->{cb}->(); defined $data && length $data or last; if ( $] ge '5.008' ) { utf8::downgrade($data, 1) or die(qq/Wide character in write_chunked_body()\n/); } $len += length $data; my $chunk = sprintf '%X', length $data; $chunk .= "\x0D\x0A"; $chunk .= $data; $chunk .= "\x0D\x0A"; $self->write($chunk); } $self->write("0\x0D\x0A"); if ( ref $request->{trailer_cb} eq 'CODE' ) { $self->write_header_lines($request->{trailer_cb}->()) } else { $self->write("\x0D\x0A"); } return $len; } sub read_response_header { @_ == 1 || die(q/Usage: $handle->read_response_header()/ . "\n"); my ($self) = @_; my $line = $self->readline; $line =~ /\A (HTTP\/(0*\d+\.0*\d+)) [\x09\x20]+ ([0-9]{3}) (?: [\x09\x20]+ ([^\x0D\x0A]*) )? \x0D?\x0A/x or die(q/Malformed Status-Line: / . $Printable->($line). "\n"); my ($protocol, $version, $status, $reason) = ($1, $2, $3, $4); $reason = "" unless defined $reason; die (qq/Unsupported HTTP protocol: $protocol\n/) unless $version =~ /0*1\.0*[01]/; return { status => $status, reason => $reason, headers => $self->read_header_lines, protocol => $protocol, }; } sub write_request_header { @_ == 5 || die(q/Usage: $handle->write_request_header(method, request_uri, headers, header_case)/ . "\n"); my ($self, $method, $request_uri, $headers, $header_case) = @_; return $self->write_header_lines($headers, $header_case, "$method $request_uri HTTP/1.1\x0D\x0A"); } sub _do_timeout { my ($self, $type, $timeout) = @_; $timeout = $self->{timeout} unless defined $timeout && $timeout >= 0; my $fd = fileno $self->{fh}; defined $fd && $fd >= 0 or die(qq/select(2): 'Bad file descriptor'\n/); my $initial = time; my $pending = $timeout; my $nfound; vec(my $fdset = '', $fd, 1) = 1; while () { $nfound = ($type eq 'read') ? select($fdset, undef, undef, $pending) : select(undef, $fdset, undef, $pending) ; if ($nfound == -1) { $! == EINTR or die(qq/select(2): '$!'\n/); redo if !$timeout || ($pending = $timeout - (time - $initial)) > 0; $nfound = 0; } last; } $! = 0; return $nfound; } sub can_read { @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_read([timeout])/ . "\n"); my $self = shift; if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) { return 1 if $self->{fh}->pending; } return $self->_do_timeout('read', @_) } sub can_write { @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_write([timeout])/ . "\n"); my $self = shift; return $self->_do_timeout('write', @_) } sub _assert_ssl { my($ok, $reason) = HTTP::Tiny->can_ssl(); die $reason unless $ok; } sub can_reuse { my ($self,$scheme,$host,$port,$peer) = @_; return 0 if $self->{pid} != $$ || $self->{tid} != _get_tid() || length($self->{rbuf}) || $scheme ne $self->{scheme} || $host ne $self->{host} || $port ne $self->{port} || $peer ne $self->{peer} || eval { $self->can_read(0) } || $@ ; return 1; } # Try to find a CA bundle to validate the SSL cert, # prefer Mozilla::CA or fallback to a system file sub _find_CA_file { my $self = shift(); my $ca_file = defined( $self->{SSL_options}->{SSL_ca_file} ) ? $self->{SSL_options}->{SSL_ca_file} : $ENV{SSL_CERT_FILE}; if ( defined $ca_file ) { unless ( -r $ca_file ) { die qq/SSL_ca_file '$ca_file' not found or not readable\n/; } return $ca_file; } local @INC = @INC; pop @INC if $INC[-1] eq '.'; return Mozilla::CA::SSL_ca_file() if eval { require Mozilla::CA; 1 }; # cert list copied from golang src/crypto/x509/root_unix.go foreach my $ca_bundle ( "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc. "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL "/etc/ssl/ca-bundle.pem", # OpenSUSE "/etc/openssl/certs/ca-certificates.crt", # NetBSD "/etc/ssl/cert.pem", # OpenBSD "/usr/local/share/certs/ca-root-nss.crt", # FreeBSD/DragonFly "/etc/pki/tls/cacert.pem", # OpenELEC "/etc/certs/ca-certificates.crt", # Solaris 11.2+ ) { return $ca_bundle if -e $ca_bundle; } die qq/Couldn't find a CA bundle with which to verify the SSL certificate.\n/ . qq/Try installing Mozilla::CA from CPAN\n/; } # for thread safety, we need to know thread id if threads are loaded sub _get_tid { no warnings 'reserved'; # for 'threads' return threads->can("tid") ? threads->tid : 0; } sub _ssl_args { my ($self, $host) = @_; my %ssl_args; # This test reimplements IO::Socket::SSL::can_client_sni(), which wasn't # added until IO::Socket::SSL 1.84 if ( Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x01000000 ) { $ssl_args{SSL_hostname} = $host, # Sane SNI support } if ($self->{verify_SSL}) { $ssl_args{SSL_verifycn_scheme} = 'http'; # enable CN validation $ssl_args{SSL_verifycn_name} = $host; # set validation hostname $ssl_args{SSL_verify_mode} = 0x01; # enable cert validation $ssl_args{SSL_ca_file} = $self->_find_CA_file; } else { $ssl_args{SSL_verifycn_scheme} = 'none'; # disable CN validation $ssl_args{SSL_verify_mode} = 0x00; # disable cert validation } # user options override settings from verify_SSL for my $k ( keys %{$self->{SSL_options}} ) { $ssl_args{$k} = $self->{SSL_options}{$k} if $k =~ m/^SSL_/; } return \%ssl_args; } 1; __END__ =pod =encoding UTF-8 =head1 NAME HTTP::Tiny - A small, simple, correct HTTP/1.1 client =head1 VERSION version 0.088 =head1 SYNOPSIS use HTTP::Tiny; my $response = HTTP::Tiny->new->get('http://example.com/'); die "Failed!\n" unless $response->{success}; print "$response->{status} $response->{reason}\n"; while (my ($k, $v) = each %{$response->{headers}}) { for (ref $v eq 'ARRAY' ? @$v : $v) { print "$k: $_\n"; } } print $response->{content} if length $response->{content}; =head1 DESCRIPTION This is a very simple HTTP/1.1 client, designed for doing simple requests without the overhead of a large framework like L. It is more correct and more complete than L. It supports proxies and redirection. It also correctly resumes after EINTR. If L 0.25 or later is installed, HTTP::Tiny will use it instead of L for transparent support for both IPv4 and IPv6. Cookie support requires L or an equivalent class. =head1 METHODS =head2 new $http = HTTP::Tiny->new( %attributes ); This constructor returns a new HTTP::Tiny object. Valid attributes include: =over 4 =item * C — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If C — ends in a space character, the default user-agent string is appended. =item * C — An instance of L — or equivalent class that supports the C and C methods =item * C — A hashref of default headers to apply to requests =item * C — The local IP address to bind to =item * C — Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1) =item * C — Maximum number of redirects allowed (defaults to 5) =item * C — Maximum response size in bytes (only when not using a data callback). If defined, requests with responses larger than this will return a 599 status code. =item * C — URL of a proxy server to use for HTTP connections (default is C<$ENV{http_proxy}> — if set) =item * C — URL of a proxy server to use for HTTPS connections (default is C<$ENV{https_proxy}> — if set) =item * C — URL of a generic proxy server for both HTTP and HTTPS connections (default is C<$ENV{all_proxy}> — if set) =item * C — List of domain suffixes that should not be proxied. Must be a comma-separated string or an array reference. (default is C<$ENV{no_proxy}> —) =item * C — Request timeout in seconds (default is 60) If a socket open, read or write takes longer than the timeout, the request response status code will be 599. =item * C — A boolean that indicates whether to validate the TLS/SSL certificate of an C — connection (default is true). Changed from false to true in version 0.083. =item * C — A hashref of C — options to pass through to L =item * C<$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}> - Changes the default certificate verification behavior to not check server identity if set to 1. Only effective if C is not set. Added in version 0.083. =back An accessor/mutator method exists for each attribute. Passing an explicit C for C, C or C will prevent getting the corresponding proxies from the environment. Errors during request execution will result in a pseudo-HTTP status code of 599 and a reason of "Internal Exception". The content field in the response will contain the text of the error. The C parameter enables a persistent connection, but only to a single destination scheme, host and port. If any connection-relevant attributes are modified via accessor, or if the process ID or thread ID change, the persistent connection will be dropped. If you want persistent connections across multiple destinations, use multiple HTTP::Tiny objects. See L for more on the C and C attributes. =head2 get|head|put|post|patch|delete $response = $http->get($url); $response = $http->get($url, \%options); $response = $http->head($url); These methods are shorthand for calling C for the given method. The URL must have unsafe characters escaped and international domain names encoded. See C for valid options and a description of the response. The C field of the response will be true if the status code is 2XX. =head2 post_form $response = $http->post_form($url, $form_data); $response = $http->post_form($url, $form_data, \%options); This method executes a C request and sends the key/value pairs from a form data hash or array reference to the given URL with a C of C. If data is provided as an array reference, the order is preserved; if provided as a hash reference, the terms are sorted on key and value for consistency. See documentation for the C method for details on the encoding. The URL must have unsafe characters escaped and international domain names encoded. See C for valid options and a description of the response. Any C header or content in the options hashref will be ignored. The C field of the response will be true if the status code is 2XX. =head2 mirror $response = $http->mirror($url, $file, \%options) if ( $response->{success} ) { print "$file is up to date\n"; } Executes a C request for the URL and saves the response body to the file name provided. The URL must have unsafe characters escaped and international domain names encoded. If the file already exists, the request will include an C header with the modification timestamp of the file. You may specify a different C header yourself in the C<< $options->{headers} >> hash. The C field of the response will be true if the status code is 2XX or if the status code is 304 (unmodified). If the file was modified and the server response includes a properly formatted C header, the file modification time will be updated accordingly. =head2 request $response = $http->request($method, $url); $response = $http->request($method, $url, \%options); Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST', 'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and international domain names encoded. B: Method names are B per the HTTP/1.1 specification. Don't use C when you really want C. See L for how this applies to redirection. If the URL includes a "user:password" stanza, they will be used for Basic-style authorization headers. (Authorization headers will not be included in a redirected request.) For example: $http->request('GET', 'http://Aladdin:open sesame@example.com/'); If the "user:password" stanza contains reserved characters, they must be percent-escaped: $http->request('GET', 'http://john%40example.com:password@example.com/'); A hashref of options may be appended to modify the request. Valid options are: =over 4 =item * C — A hashref containing headers to include with the request. If the value for a header is an array reference, the header will be output multiple times with each value in the array. These headers over-write any default headers. =item * C — A scalar to include as the body of the request OR a code reference that will be called iteratively to produce the body of the request =item * C — A code reference that will be called if it exists to provide a hashref of trailing headers (only used with chunked transfer-encoding) =item * C — A code reference that will be called for each chunks of the response body received. =item * C — Override host resolution and force all connections to go only to a specific peer address, regardless of the URL of the request. This will include any redirections! This options should be used with extreme caution (e.g. debugging or very special circumstances). It can be given as either a scalar or a code reference that will receive the hostname and whose response will be taken as the address. =back The C header is generated from the URL in accordance with RFC 2616. It is a fatal error to specify C in the C option. Other headers may be ignored or overwritten if necessary for transport compliance. If the C option is a code reference, it will be called iteratively to provide the content body of the request. It should return the empty string or undef when the iterator is exhausted. If the C option is the empty string, no C or C headers will be generated. If the C option is provided, it will be called iteratively until the entire response body is received. The first argument will be a string containing a chunk of the response body, the second argument will be the in-progress response hash reference, as described below. (This allows customizing the action of the callback based on the C or C received prior to the content body.) Content data in the request/response is handled as "raw bytes". Any encoding/decoding (with associated headers) are the responsibility of the caller. The C method returns a hashref containing the response. The hashref will have the following keys: =over 4 =item * C — Boolean indicating whether the operation returned a 2XX status code =item * C — URL that provided the response. This is the URL of the request unless there were redirections, in which case it is the last URL queried in a redirection chain =item * C — The HTTP status code of the response =item * C — The response phrase returned by the server =item * C — The body of the response. If the response does not have any content or if a data callback is provided to consume the response body, this will be the empty string =item * C — A hashref of header fields. All header field names will be normalized to be lower case. If a header is repeated, the value will be an arrayref; it will otherwise be a scalar string containing the value =item * C - If this field exists, it is the protocol of the response such as HTTP/1.0 or HTTP/1.1 =item * C If this field exists, it is an arrayref of response hash references from redirects in the same order that redirections occurred. If it does not exist, then no redirections occurred. =back On an error during the execution of the request, the C field will contain 599, and the C field will contain the text of the error. =head2 www_form_urlencode $params = $http->www_form_urlencode( $data ); $response = $http->get("http://example.com/query?$params"); This method converts the key/value pairs from a data hash or array reference into a C string. The keys and values from the data reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an array reference, the key will be repeated with each of the values of the array reference. If data is provided as a hash reference, the key/value pairs in the resulting string will be sorted by key and value for consistent ordering. =head2 can_ssl $ok = HTTP::Tiny->can_ssl; ($ok, $why) = HTTP::Tiny->can_ssl; ($ok, $why) = $http->can_ssl; Indicates if SSL support is available. When called as a class object, it checks for the correct version of L and L. When called as an object methods, if C is true or if C is set in C, it checks that a CA file is available. In scalar context, returns a boolean indicating if SSL is available. In list context, returns the boolean and a (possibly multi-line) string of errors indicating why SSL isn't available. =head2 connected $host = $http->connected; ($host, $port) = $http->connected; Indicates if a connection to a peer is being kept alive, per the C option. In scalar context, returns the peer host and port, joined with a colon, or C (if no peer is connected). In list context, returns the peer host and port or an empty list (if no peer is connected). B: This method cannot reliably be used to discover whether the remote host has closed its end of the socket. =for Pod::Coverage SSL_options agent cookie_jar default_headers http_proxy https_proxy keep_alive local_address max_redirect max_size no_proxy proxy timeout verify_SSL =head1 TLS/SSL SUPPORT Direct C connections are supported only if L 1.56 or greater and L 1.49 or greater are installed. An error will occur if new enough versions of these modules are not installed or if the TLS encryption fails. You can also use C utility function that returns boolean to see if the required modules are installed. An C connection may be made via an C proxy that supports the CONNECT command (i.e. RFC 2817). You may not proxy C via a proxy that itself requires C to communicate. TLS/SSL provides two distinct capabilities: =over 4 =item * Encrypted communication channel =item * Verification of server identity =back B. This was changed in version 0.083 due to security concerns. The previous default behavior can be enabled by setting C<$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}> to 1. Verification is done by checking that that the TLS/SSL connection has a valid certificate corresponding to the host name of the connection and that the certificate has been verified by a CA. Assuming you trust the CA, this will protect against L. Certificate verification requires a file containing trusted CA certificates. If the environment variable C is present, HTTP::Tiny will try to find a CA certificate file in that location. If the L module is installed, HTTP::Tiny will use the CA file included with it as a source of trusted CA's. If that module is not available, then HTTP::Tiny will search several system-specific default locations for a CA certificate file: =over 4 =item * /etc/ssl/certs/ca-certificates.crt =item * /etc/pki/tls/certs/ca-bundle.crt =item * /etc/ssl/ca-bundle.pem =item * /etc/openssl/certs/ca-certificates.crt =item * /etc/ssl/cert.pem =item * /usr/local/share/certs/ca-root-nss.crt =item * /etc/pki/tls/cacert.pem =item * /etc/certs/ca-certificates.crt =back An error will be occur if C is true and no CA certificate file is available. If you desire complete control over TLS/SSL connections, the C attribute lets you provide a hash reference that will be passed through to C, overriding any options set by HTTP::Tiny. For example, to provide your own trusted CA file: SSL_options => { SSL_ca_file => $file_path, } The C attribute could also be used for such things as providing a client certificate for authentication to a server or controlling the choice of cipher used for the TLS/SSL connection. See L documentation for details. =head1 PROXY SUPPORT HTTP::Tiny can proxy both C and C requests. Only Basic proxy authorization is supported and it must be provided as part of the proxy URL: C. HTTP::Tiny supports the following proxy environment variables: =over 4 =item * http_proxy or HTTP_PROXY =item * https_proxy or HTTPS_PROXY =item * all_proxy or ALL_PROXY =back If the C environment variable is set, then this might be a CGI process and C would be set from the C header, which is a security risk. If C is set, C (the upper case variant only) is ignored, but C is considered instead. Tunnelling C over an C proxy using the CONNECT method is supported. If your proxy uses C itself, you can not tunnel C over it. Be warned that proxying an C connection opens you to the risk of a man-in-the-middle attack by the proxy server. The C environment variable is supported in the format of a comma-separated list of domain extensions proxy should not be used for. Proxy arguments passed to C will override their corresponding environment variables. =head1 LIMITATIONS HTTP::Tiny is I with the L: =over 4 =item * "Message Syntax and Routing" [RFC7230] =item * "Semantics and Content" [RFC7231] =item * "Conditional Requests" [RFC7232] =item * "Range Requests" [RFC7233] =item * "Caching" [RFC7234] =item * "Authentication" [RFC7235] =back It attempts to meet all "MUST" requirements of the specification, but does not implement all "SHOULD" requirements. (Note: it was developed against the earlier RFC 2616 specification and may not yet meet the revised RFC 7230-7235 spec.) Additionally, HTTP::Tiny supports the C method of RFC 5789. Some particular limitations of note include: =over =item * HTTP::Tiny focuses on correct transport. Users are responsible for ensuring that user-defined headers and content are compliant with the HTTP/1.1 specification. =item * Users must ensure that URLs are properly escaped for unsafe characters and that international domain names are properly encoded to ASCII. See L, L and L. =item * Redirection is very strict against the specification. Redirection is only automatic for response codes 301, 302, 307 and 308 if the request method is 'GET' or 'HEAD'. Response code 303 is always converted into a 'GET' redirection, as mandated by the specification. There is no automatic support for status 305 ("Use proxy") redirections. =item * There is no provision for delaying a request body using an C header. Unexpected C<1XX> responses are silently ignored as per the specification. =item * Only 'chunked' C is supported. =item * There is no support for a Request-URI of '*' for the 'OPTIONS' request. =item * Headers mentioned in the RFCs and some other, well-known headers are generated with their canonical case. Other headers are sent in the case provided by the user. Except for control headers (which are sent first), headers are sent in arbitrary order. =back Despite the limitations listed above, HTTP::Tiny is considered feature-complete. New feature requests should be directed to L. =head1 SEE ALSO =over 4 =item * L - Higher level UA features for HTTP::Tiny =item * L - HTTP::Tiny wrapper with L/L compatibility =item * L - Wrap L instance in HTTP::Tiny compatible interface =item * L - Required for IPv6 support =item * L - Required for SSL support =item * L - If HTTP::Tiny isn't enough for you, this is the "standard" way to do things =item * L - Required if you want to validate SSL certificates =item * L - Required for SSL support =back =for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone https://github.com/Perl-Toolchain-Gang/HTTP-Tiny.git =head1 AUTHORS =over 4 =item * Christian Hansen =item * David Golden =back =head1 CONTRIBUTORS =for stopwords Alan Gardner Alessandro Ghedini A. Sinan Unur Brad Gilbert brian m. carlson Chris Nehren Weyl Claes Jakobsson Clinton Gormley Craig Berry David Golden Mitchell Dean Pearce Edward Zborowski Felipe Gasper Graham Knop Greg Kennedy James E Keenan Raspass Jeremy Mates Jess Robinson Karen Etheridge Lukas Eklund Martin J. Evans Martin-Louis Bright Matthew Horsfall Michael R. Davis Mike Doherty Nicolas Rochelemagne Olaf Alders Olivier Mengué Petr PísaÅ™ sanjay-cpu Serguei Trouchelle Shoichi Kaji SkyMarshal Sören Kornetzki Steve Grazzini Stig Palmquist Syohei YOSHIDA Tatsuhiko Miyagawa Tom Hukins Tony Cook Xavier Guimard =over 4 =item * Alan Gardner =item * Alessandro Ghedini =item * A. Sinan Unur =item * Brad Gilbert =item * brian m. carlson =item * Chris Nehren =item * Chris Weyl =item * Claes Jakobsson =item * Clinton Gormley =item * Craig A. Berry =item * Craig Berry =item * David Golden =item * David Mitchell =item * Dean Pearce =item * Edward Zborowski =item * Felipe Gasper =item * Graham Knop =item * Greg Kennedy =item * James E Keenan =item * James Raspass =item * Jeremy Mates =item * Jess Robinson =item * Karen Etheridge =item * Lukas Eklund =item * Martin J. Evans =item * Martin-Louis Bright =item * Matthew Horsfall =item * Michael R. Davis =item * Mike Doherty =item * Nicolas Rochelemagne =item * Olaf Alders =item * Olivier Mengué =item * Petr PísaÅ™ =item * sanjay-cpu =item * Serguei Trouchelle =item * Shoichi Kaji =item * SkyMarshal =item * Sören Kornetzki =item * Steve Grazzini =item * Stig Palmquist =item * Syohei YOSHIDA =item * Tatsuhiko Miyagawa =item * Tom Hukins =item * Tony Cook =item * Xavier Guimard =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2023 by Christian Hansen. 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 PK!¦�?dBbBbperl5/HTTP/Headers.pmnuÏÃ6Ç$package HTTP::Headers; use strict; use warnings; our $VERSION = '6.26'; use Carp (); # The $TRANSLATE_UNDERSCORE variable controls whether '_' can be used # as a replacement for '-' in header field names. our $TRANSLATE_UNDERSCORE = 1 unless defined $TRANSLATE_UNDERSCORE; # "Good Practice" order of HTTP message headers: # - General-Headers # - Request-Headers # - Response-Headers # - Entity-Headers my @general_headers = qw( Cache-Control Connection Date Pragma Trailer Transfer-Encoding Upgrade Via Warning ); my @request_headers = qw( Accept Accept-Charset Accept-Encoding Accept-Language Authorization Expect From Host If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since Max-Forwards Proxy-Authorization Range Referer TE User-Agent ); my @response_headers = qw( Accept-Ranges Age ETag Location Proxy-Authenticate Retry-After Server Vary WWW-Authenticate ); my @entity_headers = qw( Allow Content-Encoding Content-Language Content-Length Content-Location Content-MD5 Content-Range Content-Type Expires Last-Modified ); my %entity_header = map { lc($_) => 1 } @entity_headers; my @header_order = ( @general_headers, @request_headers, @response_headers, @entity_headers, ); # Make alternative representations of @header_order. This is used # for sorting and case matching. my %header_order; my %standard_case; { my $i = 0; for (@header_order) { my $lc = lc $_; $header_order{$lc} = ++$i; $standard_case{$lc} = $_; } } sub new { my($class) = shift; my $self = bless {}, $class; $self->header(@_) if @_; # set up initial headers $self; } sub header { my $self = shift; Carp::croak('Usage: $h->header($field, ...)') unless @_; my(@old); my %seen; while (@_) { my $field = shift; my $op = @_ ? ($seen{lc($field)}++ ? 'PUSH' : 'SET') : 'GET'; @old = $self->_header($field, shift, $op); } return @old if wantarray; return $old[0] if @old <= 1; join(", ", @old); } sub clear { my $self = shift; %$self = (); } sub push_header { my $self = shift; return $self->_header(@_, 'PUSH_H') if @_ == 2; while (@_) { $self->_header(splice(@_, 0, 2), 'PUSH_H'); } } sub init_header { Carp::croak('Usage: $h->init_header($field, $val)') if @_ != 3; shift->_header(@_, 'INIT'); } sub remove_header { my($self, @fields) = @_; my $field; my @values; foreach $field (@fields) { $field =~ tr/_/-/ if $field !~ /^:/ && $TRANSLATE_UNDERSCORE; my $v = delete $self->{lc $field}; push(@values, ref($v) eq 'ARRAY' ? @$v : $v) if defined $v; } return @values; } sub remove_content_headers { my $self = shift; unless (defined(wantarray)) { # fast branch that does not create return object delete @$self{grep $entity_header{$_} || /^content-/, keys %$self}; return; } my $c = ref($self)->new; for my $f (grep $entity_header{$_} || /^content-/, keys %$self) { $c->{$f} = delete $self->{$f}; } if (exists $self->{'::std_case'}) { $c->{'::std_case'} = $self->{'::std_case'}; } $c; } sub _header { my($self, $field, $val, $op) = @_; Carp::croak("Illegal field name '$field'") if rindex($field, ':') > 1 || !length($field); unless ($field =~ /^:/) { $field =~ tr/_/-/ if $TRANSLATE_UNDERSCORE; my $old = $field; $field = lc $field; unless($standard_case{$field} || $self->{'::std_case'}{$field}) { # generate a %std_case entry for this field $old =~ s/\b(\w)/\u$1/g; $self->{'::std_case'}{$field} = $old; } } $op ||= defined($val) ? 'SET' : 'GET'; if ($op eq 'PUSH_H') { # Like PUSH but where we don't care about the return value if (exists $self->{$field}) { my $h = $self->{$field}; if (ref($h) eq 'ARRAY') { push(@$h, ref($val) eq "ARRAY" ? @$val : $val); } else { $self->{$field} = [$h, ref($val) eq "ARRAY" ? @$val : $val] } return; } $self->{$field} = $val; return; } my $h = $self->{$field}; my @old = ref($h) eq 'ARRAY' ? @$h : (defined($h) ? ($h) : ()); unless ($op eq 'GET' || ($op eq 'INIT' && @old)) { if (defined($val)) { my @new = ($op eq 'PUSH') ? @old : (); if (ref($val) ne 'ARRAY') { push(@new, $val); } else { push(@new, @$val); } $self->{$field} = @new > 1 ? \@new : $new[0]; } elsif ($op ne 'PUSH') { delete $self->{$field}; } } @old; } sub _sorted_field_names { my $self = shift; return [ sort { ($header_order{$a} || 999) <=> ($header_order{$b} || 999) || $a cmp $b } grep !/^::/, keys %$self ]; } sub header_field_names { my $self = shift; return map $standard_case{$_} || $self->{'::std_case'}{$_} || $_, @{ $self->_sorted_field_names }, if wantarray; return grep !/^::/, keys %$self; } sub scan { my($self, $sub) = @_; my $key; for $key (@{ $self->_sorted_field_names }) { my $vals = $self->{$key}; if (ref($vals) eq 'ARRAY') { my $val; for $val (@$vals) { $sub->($standard_case{$key} || $self->{'::std_case'}{$key} || $key, $val); } } else { $sub->($standard_case{$key} || $self->{'::std_case'}{$key} || $key, $vals); } } } sub flatten { my($self)=@_; ( map { my $k = $_; map { ( $k => $_ ) } $self->header($_); } $self->header_field_names ); } sub as_string { my($self, $endl) = @_; $endl = "\n" unless defined $endl; my @result = (); for my $key (@{ $self->_sorted_field_names }) { next if index($key, '_') == 0; my $vals = $self->{$key}; if ( ref($vals) eq 'ARRAY' ) { for my $val (@$vals) { $val = '' if not defined $val; my $field = $standard_case{$key} || $self->{'::std_case'}{$key} || $key; $field =~ s/^://; if ( index($val, "\n") >= 0 ) { $val = _process_newline($val, $endl); } push @result, $field . ': ' . $val; } } else { $vals = '' if not defined $vals; my $field = $standard_case{$key} || $self->{'::std_case'}{$key} || $key; $field =~ s/^://; if ( index($vals, "\n") >= 0 ) { $vals = _process_newline($vals, $endl); } push @result, $field . ': ' . $vals; } } join($endl, @result, ''); } sub _process_newline { local $_ = shift; my $endl = shift; # must handle header values with embedded newlines with care s/\s+$//; # trailing newlines and space must go s/\n(\x0d?\n)+/\n/g; # no empty lines s/\n([^\040\t])/\n $1/g; # initial space for continuation s/\n/$endl/g; # substitute with requested line ending $_; } if (eval { require Clone; 1 }) { *clone = \&Clone::clone; } else { *clone = sub { my $self = shift; my $clone = HTTP::Headers->new; $self->scan(sub { $clone->push_header(@_);} ); $clone; }; } sub _date_header { require HTTP::Date; my($self, $header, $time) = @_; my($old) = $self->_header($header); if (defined $time) { $self->_header($header, HTTP::Date::time2str($time)); } $old =~ s/;.*// if defined($old); HTTP::Date::str2time($old); } sub date { shift->_date_header('Date', @_); } sub expires { shift->_date_header('Expires', @_); } sub if_modified_since { shift->_date_header('If-Modified-Since', @_); } sub if_unmodified_since { shift->_date_header('If-Unmodified-Since', @_); } sub last_modified { shift->_date_header('Last-Modified', @_); } # This is used as a private LWP extension. The Client-Date header is # added as a timestamp to a response when it has been received. sub client_date { shift->_date_header('Client-Date', @_); } # The retry_after field is dual format (can also be a expressed as # number of seconds from now), so we don't provide an easy way to # access it until we have know how both these interfaces can be # addressed. One possibility is to return a negative value for # relative seconds and a positive value for epoch based time values. #sub retry_after { shift->_date_header('Retry-After', @_); } sub content_type { my $self = shift; my $ct = $self->{'content-type'}; $self->{'content-type'} = shift if @_; $ct = $ct->[0] if ref($ct) eq 'ARRAY'; return '' unless defined($ct) && length($ct); my @ct = split(/;\s*/, $ct, 2); for ($ct[0]) { s/\s+//g; $_ = lc($_); } wantarray ? @ct : $ct[0]; } sub content_type_charset { my $self = shift; require HTTP::Headers::Util; my $h = $self->{'content-type'}; $h = $h->[0] if ref($h); $h = "" unless defined $h; my @v = HTTP::Headers::Util::split_header_words($h); if (@v) { my($ct, undef, %ct_param) = @{$v[0]}; my $charset = $ct_param{charset}; if ($ct) { $ct = lc($ct); $ct =~ s/\s+//; } if ($charset) { $charset = uc($charset); $charset =~ s/^\s+//; $charset =~ s/\s+\z//; undef($charset) if $charset eq ""; } return $ct, $charset if wantarray; return $charset; } return undef, undef if wantarray; return undef; } sub content_is_text { my $self = shift; return $self->content_type =~ m,^text/,; } sub content_is_html { my $self = shift; return $self->content_type eq 'text/html' || $self->content_is_xhtml; } sub content_is_xhtml { my $ct = shift->content_type; return $ct eq "application/xhtml+xml" || $ct eq "application/vnd.wap.xhtml+xml"; } sub content_is_xml { my $ct = shift->content_type; return 1 if $ct eq "text/xml"; return 1 if $ct eq "application/xml"; return 1 if $ct =~ /\+xml$/; return 0; } sub referer { my $self = shift; if (@_ && $_[0] =~ /#/) { # Strip fragment per RFC 2616, section 14.36. my $uri = shift; if (ref($uri)) { $uri = $uri->clone; $uri->fragment(undef); } else { $uri =~ s/\#.*//; } unshift @_, $uri; } ($self->_header('Referer', @_))[0]; } *referrer = \&referer; # on tchrist's request sub title { (shift->_header('Title', @_))[0] } sub content_encoding { (shift->_header('Content-Encoding', @_))[0] } sub content_language { (shift->_header('Content-Language', @_))[0] } sub content_length { (shift->_header('Content-Length', @_))[0] } sub user_agent { (shift->_header('User-Agent', @_))[0] } sub server { (shift->_header('Server', @_))[0] } sub from { (shift->_header('From', @_))[0] } sub warning { (shift->_header('Warning', @_))[0] } sub www_authenticate { (shift->_header('WWW-Authenticate', @_))[0] } sub authorization { (shift->_header('Authorization', @_))[0] } sub proxy_authenticate { (shift->_header('Proxy-Authenticate', @_))[0] } sub proxy_authorization { (shift->_header('Proxy-Authorization', @_))[0] } sub authorization_basic { shift->_basic_auth("Authorization", @_) } sub proxy_authorization_basic { shift->_basic_auth("Proxy-Authorization", @_) } sub _basic_auth { require MIME::Base64; my($self, $h, $user, $passwd) = @_; my($old) = $self->_header($h); if (defined $user) { Carp::croak("Basic authorization user name can't contain ':'") if $user =~ /:/; $passwd = '' unless defined $passwd; $self->_header($h => 'Basic ' . MIME::Base64::encode("$user:$passwd", '')); } if (defined $old && $old =~ s/^\s*Basic\s+//) { my $val = MIME::Base64::decode($old); return $val unless wantarray; return split(/:/, $val, 2); } return; } 1; =pod =encoding UTF-8 =head1 NAME HTTP::Headers - Class encapsulating HTTP Message headers =head1 VERSION version 6.26 =head1 SYNOPSIS require HTTP::Headers; $h = HTTP::Headers->new; $h->header('Content-Type' => 'text/plain'); # set $ct = $h->header('Content-Type'); # get $h->remove_header('Content-Type'); # delete =head1 DESCRIPTION The C class encapsulates HTTP-style message headers. The headers consist of attribute-value pairs also called fields, which may be repeated, and which are printed in a particular order. The field names are cases insensitive. Instances of this class are usually created as member variables of the C and C classes, internal to the library. The following methods are available: =over 4 =item $h = HTTP::Headers->new Constructs a new C object. You might pass some initial attribute-value pairs as parameters to the constructor. I: $h = HTTP::Headers->new( Date => 'Thu, 03 Feb 1994 00:00:00 GMT', Content_Type => 'text/html; version=3.2', Content_Base => 'http://www.perl.org/'); The constructor arguments are passed to the C
method which is described below. =item $h->clone Returns a copy of this C object. =item $h->header( $field ) =item $h->header( $field => $value ) =item $h->header( $f1 => $v1, $f2 => $v2, ... ) Get or set the value of one or more header fields. The header field name ($field) is not case sensitive. To make the life easier for perl users who wants to avoid quoting before the => operator, you can use '_' as a replacement for '-' in header names. The header() method accepts multiple ($field => $value) pairs, which means that you can update several fields with a single invocation. The $value argument may be a plain string or a reference to an array of strings for a multi-valued field. If the $value is provided as C then the field is removed. If the $value is not given, then that header field will remain unchanged. In addition to being a string, $value may be something that stringifies. The old value (or values) of the last of the header fields is returned. If no such field exists C will be returned. A multi-valued field will be returned as separate values in list context and will be concatenated with ", " as separator in scalar context. The HTTP spec (RFC 2616) promises that joining multiple values in this way will not change the semantic of a header field, but in practice there are cases like old-style Netscape cookies (see L) where "," is used as part of the syntax of a single field value. Examples: $header->header(MIME_Version => '1.0', User_Agent => 'My-Web-Client/0.01'); $header->header(Accept => "text/html, text/plain, image/*"); $header->header(Accept => [qw(text/html text/plain image/*)]); @accepts = $header->header('Accept'); # get multiple values $accepts = $header->header('Accept'); # get values as a single string =item $h->push_header( $field => $value ) =item $h->push_header( $f1 => $v1, $f2 => $v2, ... ) Add a new field value for the specified header field. Previous values for the same field are retained. As for the header() method, the field name ($field) is not case sensitive and '_' can be used as a replacement for '-'. The $value argument may be a scalar or a reference to a list of scalars. $header->push_header(Accept => 'image/jpeg'); $header->push_header(Accept => [map "image/$_", qw(gif png tiff)]); =item $h->init_header( $field => $value ) Set the specified header to the given value, but only if no previous value for that field is set. The header field name ($field) is not case sensitive and '_' can be used as a replacement for '-'. The $value argument may be a scalar or a reference to a list of scalars. =item $h->remove_header( $field, ... ) This function removes the header fields with the specified names. The header field names ($field) are not case sensitive and '_' can be used as a replacement for '-'. The return value is the values of the fields removed. In scalar context the number of fields removed is returned. Note that if you pass in multiple field names then it is generally not possible to tell which of the returned values belonged to which field. =item $h->remove_content_headers This will remove all the header fields used to describe the content of a message. All header field names prefixed with C fall into this category, as well as C, C and C. RFC 2616 denotes these fields as I. The return value is a new C object that contains the removed headers only. =item $h->clear This will remove all header fields. =item $h->header_field_names Returns the list of distinct names for the fields present in the header. The field names have case as suggested by HTTP spec, and the names are returned in the recommended "Good Practice" order. In scalar context return the number of distinct field names. =item $h->scan( \&process_header_field ) Apply a subroutine to each header field in turn. The callback routine is called with two parameters; the name of the field and a single value (a string). If a header field is multi-valued, then the routine is called once for each value. The field name passed to the callback routine has case as suggested by HTTP spec, and the headers will be visited in the recommended "Good Practice" order. Any return values of the callback routine are ignored. The loop can be broken by raising an exception (C), but the caller of scan() would have to trap the exception itself. =item $h->flatten() Returns the list of pairs of keys and values. =item $h->as_string =item $h->as_string( $eol ) Return the header fields as a formatted MIME header. Since it internally uses the C method to build the string, the result will use case as suggested by HTTP spec, and it will follow recommended "Good Practice" of ordering the header fields. Long header values are not folded. The optional $eol parameter specifies the line ending sequence to use. The default is "\n". Embedded "\n" characters in header field values will be substituted with this line ending sequence. =back =head1 CONVENIENCE METHODS The most frequently used headers can also be accessed through the following convenience methods. Most of these methods can both be used to read and to set the value of a header. The header value is set if you pass an argument to the method. The old header value is always returned. If the given header did not exist then C is returned. Methods that deal with dates/times always convert their value to system time (seconds since Jan 1, 1970) and they also expect this kind of value when the header value is set. =over 4 =item $h->date This header represents the date and time at which the message was originated. I: $h->date(time); # set current date =item $h->expires This header gives the date and time after which the entity should be considered stale. =item $h->if_modified_since =item $h->if_unmodified_since These header fields are used to make a request conditional. If the requested resource has (or has not) been modified since the time specified in this field, then the server will return a C<304 Not Modified> response instead of the document itself. =item $h->last_modified This header indicates the date and time at which the resource was last modified. I: # check if document is more than 1 hour old if (my $last_mod = $h->last_modified) { if ($last_mod < time - 60*60) { ... } } =item $h->content_type The Content-Type header field indicates the media type of the message content. I: $h->content_type('text/html'); The value returned will be converted to lower case, and potential parameters will be chopped off and returned as a separate value if in an array context. If there is no such header field, then the empty string is returned. This makes it safe to do the following: if ($h->content_type eq 'text/html') { # we enter this place even if the real header value happens to # be 'TEXT/HTML; version=3.0' ... } =item $h->content_type_charset Returns the upper-cased charset specified in the Content-Type header. In list context return the lower-cased bare content type followed by the upper-cased charset. Both values will be C if not specified in the header. =item $h->content_is_text Returns TRUE if the Content-Type header field indicate that the content is textual. =item $h->content_is_html Returns TRUE if the Content-Type header field indicate that the content is some kind of HTML (including XHTML). This method can't be used to set Content-Type. =item $h->content_is_xhtml Returns TRUE if the Content-Type header field indicate that the content is XHTML. This method can't be used to set Content-Type. =item $h->content_is_xml Returns TRUE if the Content-Type header field indicate that the content is XML. This method can't be used to set Content-Type. =item $h->content_encoding The Content-Encoding header field is used as a modifier to the media type. When present, its value indicates what additional encoding mechanism has been applied to the resource. =item $h->content_length A decimal number indicating the size in bytes of the message content. =item $h->content_language The natural language(s) of the intended audience for the message content. The value is one or more language tags as defined by RFC 1766. Eg. "no" for some kind of Norwegian and "en-US" for English the way it is written in the US. =item $h->title The title of the document. In libwww-perl this header will be initialized automatically from the ETITLE>...E/TITLE> element of HTML documents. I =item $h->user_agent This header field is used in request messages and contains information about the user agent originating the request. I: $h->user_agent('Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0)'); =item $h->server The server header field contains information about the software being used by the originating server program handling the request. =item $h->from This header should contain an Internet e-mail address for the human user who controls the requesting user agent. The address should be machine-usable, as defined by RFC822. E.g.: $h->from('King Kong '); I =item $h->referer Used to specify the address (URI) of the document from which the requested resource address was obtained. The "Free On-line Dictionary of Computing" as this to say about the word I: A misspelling of "referrer" which somehow made it into the {HTTP} standard. A given {web page}'s referer (sic) is the {URL} of whatever web page contains the link that the user followed to the current page. Most browsers pass this information as part of a request. (1998-10-19) By popular demand C exists as an alias for this method so you can avoid this misspelling in your programs and still send the right thing on the wire. When setting the referrer, this method removes the fragment from the given URI if it is present, as mandated by RFC2616. Note that the removal does I happen automatically if using the header(), push_header() or init_header() methods to set the referrer. =item $h->www_authenticate This header must be included as part of a C<401 Unauthorized> response. The field value consist of a challenge that indicates the authentication scheme and parameters applicable to the requested URI. =item $h->proxy_authenticate This header must be included in a C<407 Proxy Authentication Required> response. =item $h->authorization =item $h->proxy_authorization A user agent that wishes to authenticate itself with a server or a proxy, may do so by including these headers. =item $h->authorization_basic This method is used to get or set an authorization header that use the "Basic Authentication Scheme". In array context it will return two values; the user name and the password. In scalar context it will return I<"uname:password"> as a single string value. When used to set the header value, it expects two arguments. I: $h->authorization_basic($uname, $password); The method will croak if the $uname contains a colon ':'. =item $h->proxy_authorization_basic Same as authorization_basic() but will set the "Proxy-Authorization" header instead. =back =head1 NON-CANONICALIZED FIELD NAMES The header field name spelling is normally canonicalized including the '_' to '-' translation. There are some application where this is not appropriate. Prefixing field names with ':' allow you to force a specific spelling. For example if you really want a header field name to show up as C instead of "Foo-Bar", you might set it like this: $h->header(":foo_bar" => 1); These field names are returned with the ':' intact for $h->header_field_names and the $h->scan callback, but the colons do not show in $h->as_string. =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 1994 by Gisle Aas. 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 __END__ #ABSTRACT: Class encapsulating HTTP Message headers PK! Û Š¤‹¤‹perl5/Expect.pmnuƒ7�æm# -*-cperl-*- # This module is copyrighted as per the usual perl legalese: # Copyright (c) 1997 Austin Schutz. # expect() interface & functionality enhancements (c) 1999 Roland Giersig. # # All rights reserved. This program is free software; you can # redistribute it and/or modify it under the same terms as Perl # itself. # # Don't blame/flame me if you bust your stuff. # Austin Schutz # # This module now is maintained by # Dave Jacoby # use 5.006; package Expect; use strict; use warnings; use IO::Pty 1.11; # We need make_slave_controlling_terminal() use IO::Tty; use POSIX qw(:sys_wait_h :unistd_h); # For WNOHANG and isatty use Fcntl qw(:DEFAULT); # For checking file handle settings. use Carp qw(cluck croak carp confess); use IO::Handle (); use Exporter qw(import); use Errno; use Scalar::Util qw/ looks_like_number /; # This is necessary to make routines within Expect work. @Expect::ISA = qw(IO::Pty); @Expect::EXPORT = qw(expect exp_continue exp_continue_timeout); BEGIN { $Expect::VERSION = '1.38'; # These are defaults which may be changed per object, or set as # the user wishes. # This will be unset, since the default behavior differs between # spawned processes and initialized filehandles. # $Expect::Log_Stdout = 1; $Expect::Log_Group = 1; $Expect::Debug = 0; $Expect::Exp_Max_Accum = 0; # unlimited $Expect::Exp_Internal = 0; $Expect::IgnoreEintr = 0; $Expect::Manual_Stty = 0; $Expect::Multiline_Matching = 1; $Expect::Do_Soft_Close = 0; @Expect::Before_List = (); @Expect::After_List = (); %Expect::Spawned_PIDs = (); } sub version { my ($version) = @_; warn "Version $version is later than $Expect::VERSION. It may not be supported" if ( defined($version) && ( $version > $Expect::VERSION ) ); die "Versions before 1.03 are not supported in this release" if ( ( defined($version) ) && ( $version < 1.03 ) ); return $Expect::VERSION; } sub new { my ($class, @args) = @_; $class = ref($class) if ref($class); # so we can be called as $exp->new() # Create the pty which we will use to pass process info. my ($self) = IO::Pty->new; die "$class: Could not assign a pty" unless $self; bless $self => $class; $self->autoflush(1); # This is defined here since the default is different for # initialized handles as opposed to spawned processes. ${*$self}{exp_Log_Stdout} = 1; $self->_init_vars(); if (@args) { # we got add'l parms, so pass them to spawn return $self->spawn(@args); } return $self; } sub timeout { my $self = shift; ${*$self}{expect_timeout} = shift if @_; return ${*$self}{expect_timeout}; } sub spawn { my ($class, @cmd) = @_; # spawn is passed command line args. my $self; if ( ref($class) ) { $self = $class; } else { $self = $class->new(); } croak "Cannot reuse an object with an already spawned command" if exists ${*$self}{"exp_Command"}; ${*$self}{"exp_Command"} = \@cmd; # set up pipe to detect childs exec error pipe( FROM_CHILD, TO_PARENT ) or die "Cannot open pipe: $!"; pipe( FROM_PARENT, TO_CHILD ) or die "Cannot open pipe: $!"; TO_PARENT->autoflush(1); TO_CHILD->autoflush(1); eval { fcntl( TO_PARENT, Fcntl::F_SETFD, Fcntl::FD_CLOEXEC ); }; my $pid = fork; unless ( defined($pid) ) { warn "Cannot fork: $!" if $^W; return; } if ($pid) { # parent my $errno; ${*$self}{exp_Pid} = $pid; close TO_PARENT; close FROM_PARENT; $self->close_slave(); $self->set_raw() if $self->raw_pty and isatty($self); close TO_CHILD; # so child gets EOF and can go ahead # now wait for child exec (eof due to close-on-exit) or exec error my $errstatus = sysread( FROM_CHILD, $errno, 256 ); die "Cannot sync with child: $!" if not defined $errstatus; close FROM_CHILD; if ($errstatus) { $! = $errno + 0; warn "Cannot exec(@cmd): $!\n" if $^W; return; } } else { # child close FROM_CHILD; close TO_CHILD; $self->make_slave_controlling_terminal(); my $slv = $self->slave() or die "Cannot get slave: $!"; $slv->set_raw() if $self->raw_pty; close($self); # wait for parent before we detach my $buffer; my $errstatus = sysread( FROM_PARENT, $buffer, 256 ); die "Cannot sync with parent: $!" if not defined $errstatus; close FROM_PARENT; close(STDIN); open( STDIN, "<&" . $slv->fileno() ) or die "Couldn't reopen STDIN for reading, $!\n"; close(STDOUT); open( STDOUT, ">&" . $slv->fileno() ) or die "Couldn't reopen STDOUT for writing, $!\n"; close(STDERR); open( STDERR, ">&" . $slv->fileno() ) or die "Couldn't reopen STDERR for writing, $!\n"; { exec(@cmd) }; print TO_PARENT $! + 0; die "Cannot exec(@cmd): $!\n"; } # This is sort of for code compatibility, and to make debugging a little # easier. By code compatibility I mean that previously the process's # handle was referenced by $process{Pty_Handle} instead of just $process. # This is almost like 'naming' the handle to the process. # I think this also reflects Tcl Expect-like behavior. ${*$self}{exp_Pty_Handle} = "spawn id(" . $self->fileno() . ")"; if ( ( ${*$self}{"exp_Debug"} ) or ( ${*$self}{"exp_Exp_Internal"} ) ) { cluck( "Spawned '@cmd'\r\n", "\t${*$self}{exp_Pty_Handle}\r\n", "\tPid: ${*$self}{exp_Pid}\r\n", "\tTty: " . $self->SUPER::ttyname() . "\r\n", ); } $Expect::Spawned_PIDs{ ${*$self}{exp_Pid} } = undef; return $self; } sub exp_init { my ($class, $self) = @_; # take a filehandle, for use later with expect() or interconnect() . # All the functions are written for reading from a tty, so if the naming # scheme looks odd, that's why. bless $self, $class; croak "exp_init not passed a file object, stopped" unless defined( $self->fileno() ); $self->autoflush(1); # Define standard variables.. debug states, etc. $self->_init_vars(); # Turn of logging. By default we don't want crap from a file to get spewed # on screen as we read it. ${*$self}{exp_Log_Stdout} = 0; ${*$self}{exp_Pty_Handle} = "handle id(" . $self->fileno() . ")"; ${*$self}{exp_Pty_Handle} = "STDIN" if $self->fileno() == fileno(STDIN); print STDERR "Initialized ${*$self}{exp_Pty_Handle}.'\r\n" if ${*$self}{"exp_Debug"}; return $self; } # make an alias *init = \&exp_init; ###################################################################### # We're happy OOP people. No direct access to stuff. # For standard read-writeable parameters, we define some autoload magic... my %Writeable_Vars = ( debug => 'exp_Debug', exp_internal => 'exp_Exp_Internal', do_soft_close => 'exp_Do_Soft_Close', max_accum => 'exp_Max_Accum', match_max => 'exp_Max_Accum', notransfer => 'exp_NoTransfer', log_stdout => 'exp_Log_Stdout', log_user => 'exp_Log_Stdout', log_group => 'exp_Log_Group', manual_stty => 'exp_Manual_Stty', restart_timeout_upon_receive => 'exp_Continue', raw_pty => 'exp_Raw_Pty', ); my %Readable_Vars = ( pid => 'exp_Pid', exp_pid => 'exp_Pid', exp_match_number => 'exp_Match_Number', match_number => 'exp_Match_Number', exp_error => 'exp_Error', error => 'exp_Error', exp_command => 'exp_Command', command => 'exp_Command', exp_match => 'exp_Match', match => 'exp_Match', exp_matchlist => 'exp_Matchlist', matchlist => 'exp_Matchlist', exp_before => 'exp_Before', before => 'exp_Before', exp_after => 'exp_After', after => 'exp_After', exp_exitstatus => 'exp_Exit', exitstatus => 'exp_Exit', exp_pty_handle => 'exp_Pty_Handle', pty_handle => 'exp_Pty_Handle', exp_logfile => 'exp_Log_File', logfile => 'exp_Log_File', %Writeable_Vars, ); sub AUTOLOAD { my ($self, @args) = @_; my $type = ref($self) or croak "$self is not an object"; use vars qw($AUTOLOAD); my $name = $AUTOLOAD; $name =~ s/.*:://; # strip fully-qualified portion unless ( exists $Readable_Vars{$name} ) { croak "ERROR: cannot find method `$name' in class $type"; } my $varname = $Readable_Vars{$name}; my $tmp; $tmp = ${*$self}{$varname} if exists ${*$self}{$varname}; if (@args) { if ( exists $Writeable_Vars{$name} ) { my $ref = ref($tmp); if ( $ref eq 'ARRAY' ) { ${*$self}{$varname} = [@args]; } elsif ( $ref eq 'HASH' ) { ${*$self}{$varname} = {@args}; } else { ${*$self}{$varname} = shift @args; } } else { carp "Trying to set read-only variable `$name'" if $^W; } } my $ref = ref($tmp); return ( wantarray ? @{$tmp} : $tmp ) if ( $ref eq 'ARRAY' ); return ( wantarray ? %{$tmp} : $tmp ) if ( $ref eq 'HASH' ); return $tmp; } ###################################################################### sub set_seq { my ( $self, $escape_sequence, $function, $params, @args ) = @_; # Set an escape sequence/function combo for a read handle for interconnect. # Ex: $read_handle->set_seq('',\&function,\@parameters); ${ ${*$self}{exp_Function} }{$escape_sequence} = $function; if ( ( !defined($function) ) || ( $function eq 'undef' ) ) { ${ ${*$self}{exp_Function} }{$escape_sequence} = \&_undef; } ${ ${*$self}{exp_Parameters} }{$escape_sequence} = $params; # This'll be a joy to execute. :) if ( ${*$self}{"exp_Debug"} ) { print STDERR "Escape seq. '" . $escape_sequence; print STDERR "' function for ${*$self}{exp_Pty_Handle} set to '"; print STDERR ${ ${*$self}{exp_Function} }{$escape_sequence}; print STDERR "(" . join( ',', @args ) . ")'\r\n"; } } sub set_group { my ($self, @args) = @_; # Make sure we can read from the read handle if ( !defined( $args[0] ) ) { if ( defined( ${*$self}{exp_Listen_Group} ) ) { return @{ ${*$self}{exp_Listen_Group} }; } else { # Refrain from referencing an undef return; } } @{ ${*$self}{exp_Listen_Group} } = (); if ( $self->_get_mode() !~ 'r' ) { warn( "Attempting to set a handle group on ${*$self}{exp_Pty_Handle}, ", "a non-readable handle!\r\n" ); } while ( my $write_handle = shift @args ) { if ( $write_handle->_get_mode() !~ 'w' ) { warn( "Attempting to set a non-writeable listen handle ", "${*$write_handle}{exp_Pty_handle} for ", "${*$self}{exp_Pty_Handle}!\r\n" ); } push( @{ ${*$self}{exp_Listen_Group} }, $write_handle ); } } sub log_file { my ($self, $file, $mode) = @_; $mode ||= "a"; return ( ${*$self}{exp_Log_File} ) if @_ < 2; # we got no param, return filehandle # $e->log_file(undef) is an acceptable call hence we need to check the number of parameters here if ( ${*$self}{exp_Log_File} and ref( ${*$self}{exp_Log_File} ) ne 'CODE' ) { close( ${*$self}{exp_Log_File} ); } ${*$self}{exp_Log_File} = undef; return if ( not $file ); my $fh = $file; if ( not ref($file) ) { # it's a filename $fh = IO::File->new( $file, $mode ) or croak "Cannot open logfile $file: $!"; } if ( ref($file) ne 'CODE' ) { croak "Given logfile doesn't have a 'print' method" if not $fh->can("print"); $fh->autoflush(1); # so logfile is up to date } ${*$self}{exp_Log_File} = $fh; return $fh; } # I'm going to leave this here in case I might need to change something. # Previously this was calling `stty`, in a most bastardized manner. sub exp_stty { my ($self) = shift; my ($mode) = "@_"; return unless defined $mode; if ( not defined $INC{"IO/Stty.pm"} ) { carp "IO::Stty not installed, cannot change mode"; return; } if ( ${*$self}{"exp_Debug"} ) { print STDERR "Setting ${*$self}{exp_Pty_Handle} to tty mode '$mode'\r\n"; } unless ( POSIX::isatty($self) ) { if ( ${*$self}{"exp_Debug"} or $^W ) { warn "${*$self}{exp_Pty_Handle} is not a tty. Not changing mode"; } return ''; # No undef to avoid warnings elsewhere. } IO::Stty::stty( $self, split( /\s/, $mode ) ); } *stty = \&exp_stty; # If we want to clear the buffer. Otherwise Accum will grow during send_slow # etc. and contain the remainder after matches. sub clear_accum { my ($self) = @_; return $self->set_accum(''); } sub set_accum { my ($self, $accum) = @_; my $old_accum = ${*$self}{exp_Accum}; ${*$self}{exp_Accum} = $accum; # return the contents of the accumulator. return $old_accum; } sub get_accum { my ($self) = @_; return ${*$self}{exp_Accum}; } ###################################################################### # define constants for pattern subs sub exp_continue {"exp_continue"} sub exp_continue_timeout {"exp_continue_timeout"} ###################################################################### # Expect on multiple objects at once. # # Call as Expect::expect($timeout, -i => \@exp_list, @patternlist, # -i => $exp, @pattern_list, ...); # or $exp->expect($timeout, @patternlist, -i => \@exp_list, @patternlist, # -i => $exp, @pattern_list, ...); # # Patterns are arrays that consist of # [ $pattern_type, $pattern, $sub, @subparms ] # # Optional $pattern_type is '-re' (RegExp, default) or '-ex' (exact); # # $sub is optional CODE ref, which is called as &{$sub}($exp, @subparms) # if pattern matched; may return exp_continue or exp_continue_timeout. # # Old-style syntax (pure pattern strings with optional type) also supported. # sub expect { my $self; print STDERR ("expect(@_) called...\n") if $Expect::Debug; if ( defined( $_[0] ) ) { if ( ref( $_[0] ) and $_[0]->isa('Expect') ) { $self = shift; } elsif ( $_[0] eq 'Expect' ) { shift; # or as Expect->expect } } croak "expect(): not enough arguments, should be expect(timeout, [patterns...])" if @_ < 1; my $timeout; if ( looks_like_number($_[0]) or not defined $_[0] ) { $timeout = shift; } else { $timeout = $self->timeout; } my $timeout_hook = undef; my @object_list; my %patterns; my @pattern_list; my @timeout_list; my $curr_list; if ($self) { $curr_list = [$self]; } else { # called directly, so first parameter must be '-i' to establish # object list. $curr_list = []; croak "expect(): ERROR: if called directly (not as \$obj->expect(...), but as Expect::expect(...), first parameter MUST be '-i' to set an object (list) for the patterns to work on." if ( $_[0] ne '-i' ); } # Let's make a list of patterns wanting to be evaled as regexps. my $parm; my $parm_nr = 1; while ( defined( $parm = shift ) ) { print STDERR ("expect(): handling param '$parm'...\n") if $Expect::Debug; if ( ref($parm) ) { if ( ref($parm) eq 'Regexp' ) { push @pattern_list, [ $parm_nr, '-re', $parm, undef ]; } elsif ( ref($parm) eq 'ARRAY' ) { # if ( ref($parm) eq 'ARRAY' ) { my $err = _add_patterns_to_list( \@pattern_list, \@timeout_list, $parm_nr, $parm ); carp( "expect(): Warning: multiple `timeout' patterns (", scalar(@timeout_list), ").\r\n" ) if @timeout_list > 1; $timeout_hook = $timeout_list[-1] if $timeout_list[-1]; croak $err if $err; $parm_nr++; } else { croak("expect(): Unknown pattern ref $parm"); } } else { # not a ref, is an option or raw pattern if ( substr( $parm, 0, 1 ) eq '-' ) { # it's an option print STDERR ("expect(): handling option '$parm'...\n") if $Expect::Debug; if ( $parm eq '-i' ) { # first add collected patterns to object list if ( scalar(@$curr_list) ) { push @object_list, $curr_list if not exists $patterns{"$curr_list"}; push @{ $patterns{"$curr_list"} }, @pattern_list; @pattern_list = (); } # now put parm(s) into current object list if ( ref( $_[0] ) eq 'ARRAY' ) { $curr_list = shift; } else { $curr_list = [shift]; } } elsif ( $parm eq '-re' or $parm eq '-ex' ) { if ( ref( $_[1] ) eq 'CODE' ) { push @pattern_list, [ $parm_nr, $parm, shift, shift ]; } else { push @pattern_list, [ $parm_nr, $parm, shift, undef ]; } $parm_nr++; } else { croak("Unknown option $parm"); } } else { # a plain pattern, check if it is followed by a CODE ref if ( ref( $_[0] ) eq 'CODE' ) { if ( $parm eq 'timeout' ) { push @timeout_list, shift; carp( "expect(): Warning: multiple `timeout' patterns (", scalar(@timeout_list), ").\r\n" ) if @timeout_list > 1; $timeout_hook = $timeout_list[-1] if $timeout_list[-1]; } elsif ( $parm eq 'eof' ) { push @pattern_list, [ $parm_nr, "-$parm", undef, shift ]; } else { push @pattern_list, [ $parm_nr, '-ex', $parm, shift ]; } } else { print STDERR ("expect(): exact match '$parm'...\n") if $Expect::Debug; push @pattern_list, [ $parm_nr, '-ex', $parm, undef ]; } $parm_nr++; } } } # add rest of collected patterns to object list carp "expect(): Empty object list" unless $curr_list; push @object_list, $curr_list if not exists $patterns{"$curr_list"}; push @{ $patterns{"$curr_list"} }, @pattern_list; my $debug = $self ? ${*$self}{exp_Debug} : $Expect::Debug; my $internal = $self ? ${*$self}{exp_Exp_Internal} : $Expect::Exp_Internal; # now start matching... if (@Expect::Before_List) { print STDERR ("Starting BEFORE pattern matching...\r\n") if ( $debug or $internal ); _multi_expect( 0, undef, @Expect::Before_List ); } cluck("Starting EXPECT pattern matching...\r\n") if ( $debug or $internal ); my @ret; @ret = _multi_expect( $timeout, $timeout_hook, map { [ $_, @{ $patterns{"$_"} } ] } @object_list ); if (@Expect::After_List) { print STDERR ("Starting AFTER pattern matching...\r\n") if ( $debug or $internal ); _multi_expect( 0, undef, @Expect::After_List ); } return wantarray ? @ret : $ret[0]; } ###################################################################### # the real workhorse # sub _multi_expect { my ($timeout, $timeout_hook, @params) = @_; if ($timeout_hook) { croak "Unknown timeout_hook type $timeout_hook" unless ( ref($timeout_hook) eq 'CODE' or ref($timeout_hook) eq 'ARRAY' ); } foreach my $pat (@params) { my @patterns = @{$pat}[ 1 .. $#{$pat} ]; foreach my $exp ( @{ $pat->[0] } ) { ${*$exp}{exp_New_Data} = 1; # first round we always try to match if ( exists ${*$exp}{"exp_Max_Accum"} and ${*$exp}{"exp_Max_Accum"} ) { ${*$exp}{exp_Accum} = $exp->_trim_length( ${*$exp}{exp_Accum}, ${*$exp}{exp_Max_Accum} ); } print STDERR ( "${*$exp}{exp_Pty_Handle}: beginning expect.\r\n", "\tTimeout: ", ( defined($timeout) ? $timeout : "unlimited" ), " seconds.\r\n", "\tCurrent time: " . localtime() . "\r\n", ) if $Expect::Debug; # What are we expecting? What do you expect? :-) if ( ${*$exp}{exp_Exp_Internal} ) { print STDERR "${*$exp}{exp_Pty_Handle}: list of patterns:\r\n"; foreach my $pattern (@patterns) { print STDERR ( ' ', defined( $pattern->[0] ) ? '#' . $pattern->[0] . ': ' : '', $pattern->[1], " `", _make_readable( $pattern->[2] ), "'\r\n" ); } print STDERR "\r\n"; } } } my $successful_pattern; my $exp_matched; my $err; my $before; my $after; my $match; my @matchlist; # Set the last loop time to now for time comparisons at end of loop. my $start_loop_time = time(); my $exp_cont = 1; READLOOP: while ($exp_cont) { $exp_cont = 1; $err = ""; my $rmask = ''; my $time_left = undef; if ( defined $timeout ) { $time_left = $timeout - ( time() - $start_loop_time ); $time_left = 0 if $time_left < 0; } $exp_matched = undef; # Test for a match first so we can test the current Accum w/out # worrying about an EOF. foreach my $pat (@params) { my @patterns = @{$pat}[ 1 .. $#{$pat} ]; foreach my $exp ( @{ $pat->[0] } ) { # build mask for select in next section... my $fn = $exp->fileno(); vec( $rmask, $fn, 1 ) = 1 if defined $fn; next unless ${*$exp}{exp_New_Data}; # clear error status ${*$exp}{exp_Error} = undef; ${*$exp}{exp_After} = undef; ${*$exp}{exp_Match_Number} = undef; ${*$exp}{exp_Match} = undef; # This could be huge. We should attempt to do something # about this. Because the output is used for debugging # I'm of the opinion that showing smaller amounts if the # total is huge should be ok. # Thus the 'trim_length' print STDERR ( "\r\n${*$exp}{exp_Pty_Handle}: Does `", $exp->_trim_length( _make_readable( ${*$exp}{exp_Accum} ) ), "'\r\nmatch:\r\n" ) if ${*$exp}{exp_Exp_Internal}; # we don't keep the parameter number anymore # (clashes with before & after), instead the parameter number is # stored inside the pattern; we keep the pattern ref # and look up the number later. foreach my $pattern (@patterns) { print STDERR ( " pattern", defined( $pattern->[0] ) ? ' #' . $pattern->[0] : '', ": ", $pattern->[1], " `", _make_readable( $pattern->[2] ), "'? " ) if ( ${*$exp}{exp_Exp_Internal} ); # Matching exactly if ( $pattern->[1] eq '-ex' ) { my $match_index = index( ${*$exp}{exp_Accum}, $pattern->[2] ); # We matched if $match_index > -1 if ( $match_index > -1 ) { $before = substr( ${*$exp}{exp_Accum}, 0, $match_index ); $match = substr( ${*$exp}{exp_Accum}, $match_index, length( $pattern->[2] ) ); $after = substr( ${*$exp}{exp_Accum}, $match_index + length( $pattern->[2] ) ); ${*$exp}{exp_Before} = $before; ${*$exp}{exp_Match} = $match; ${*$exp}{exp_After} = $after; ${*$exp}{exp_Match_Number} = $pattern->[0]; $exp_matched = $exp; } } elsif ( $pattern->[1] eq '-re' ) { if ($Expect::Multiline_Matching) { @matchlist = ( ${*$exp}{exp_Accum} =~ m/($pattern->[2])/m); } else { @matchlist = ( ${*$exp}{exp_Accum} =~ m/($pattern->[2])/); } if (@matchlist) { # Matching regexp $match = shift @matchlist; my $start = index ${*$exp}{exp_Accum}, $match; die 'The match could not be found' if $start == -1; $before = substr ${*$exp}{exp_Accum}, 0, $start; $after = substr ${*$exp}{exp_Accum}, $start + length($match); ${*$exp}{exp_Before} = $before; ${*$exp}{exp_Match} = $match; ${*$exp}{exp_After} = $after; #pop @matchlist; # remove kludged empty bracket from end @{ ${*$exp}{exp_Matchlist} } = @matchlist; ${*$exp}{exp_Match_Number} = $pattern->[0]; $exp_matched = $exp; } } else { # 'timeout' or 'eof' } if ($exp_matched) { ${*$exp}{exp_Accum} = $after unless ${*$exp}{exp_NoTransfer}; print STDERR "YES!!\r\n" if ${*$exp}{exp_Exp_Internal}; print STDERR ( " Before match string: `", $exp->_trim_length( _make_readable( ($before) ) ), "'\r\n", " Match string: `", _make_readable($match), "'\r\n", " After match string: `", $exp->_trim_length( _make_readable( ($after) ) ), "'\r\n", " Matchlist: (", join( ", ", map { "`" . $exp->_trim_length( _make_readable( ($_) ) ) . "'" } @matchlist, ), ")\r\n", ) if ( ${*$exp}{exp_Exp_Internal} ); # call hook function if defined if ( $pattern->[3] ) { print STDERR ( "Calling hook $pattern->[3]...\r\n", ) if ( ${*$exp}{exp_Exp_Internal} or $Expect::Debug ); if ( $#{$pattern} > 3 ) { # call with parameters if given $exp_cont = &{ $pattern->[3] }( $exp, @{$pattern}[ 4 .. $#{$pattern} ] ); } else { $exp_cont = &{ $pattern->[3] }($exp); } } if ( $exp_cont and $exp_cont eq exp_continue ) { print STDERR ("Continuing expect, restarting timeout...\r\n") if ( ${*$exp}{exp_Exp_Internal} or $Expect::Debug ); $start_loop_time = time(); # restart timeout count next READLOOP; } elsif ( $exp_cont and $exp_cont eq exp_continue_timeout ) { print STDERR ("Continuing expect...\r\n") if ( ${*$exp}{exp_Exp_Internal} or $Expect::Debug ); next READLOOP; } last READLOOP; } print STDERR "No.\r\n" if ${*$exp}{exp_Exp_Internal}; } print STDERR "\r\n" if ${*$exp}{exp_Exp_Internal}; # don't have to match again until we get new data ${*$exp}{exp_New_Data} = 0; } } # End of matching section # No match, let's see what is pending on the filehandles... print STDERR ( "Waiting for new data (", defined($time_left) ? $time_left : 'unlimited', " seconds)...\r\n", ) if ( $Expect::Exp_Internal or $Expect::Debug ); my $nfound; SELECT: { $nfound = select( $rmask, undef, undef, $time_left ); if ( $nfound < 0 ) { if ( $!{EINTR} and $Expect::IgnoreEintr ) { print STDERR ("ignoring EINTR, restarting select()...\r\n") if ( $Expect::Exp_Internal or $Expect::Debug ); next SELECT; } print STDERR ("select() returned error code '$!'\r\n") if ( $Expect::Exp_Internal or $Expect::Debug ); # returned error $err = "4:$!"; last READLOOP; } } # go until we don't find something (== timeout). if ( $nfound == 0 ) { # No pattern, no EOF. Did we time out? $err = "1:TIMEOUT"; foreach my $pat (@params) { foreach my $exp ( @{ $pat->[0] } ) { $before = ${*$exp}{exp_Before} = ${*$exp}{exp_Accum}; next if not defined $exp->fileno(); # skip already closed ${*$exp}{exp_Error} = $err unless ${*$exp}{exp_Error}; } } print STDERR ("TIMEOUT\r\n") if ( $Expect::Debug or $Expect::Exp_Internal ); if ($timeout_hook) { my $ret; print STDERR ("Calling timeout function $timeout_hook...\r\n") if ( $Expect::Debug or $Expect::Exp_Internal ); if ( ref($timeout_hook) eq 'CODE' ) { $ret = &{$timeout_hook}( $params[0]->[0] ); } else { if ( $#{$timeout_hook} > 3 ) { $ret = &{ $timeout_hook->[3] }( $params[0]->[0], @{$timeout_hook}[ 4 .. $#{$timeout_hook} ] ); } else { $ret = &{ $timeout_hook->[3] }( $params[0]->[0] ); } } if ( $ret and $ret eq exp_continue ) { $start_loop_time = time(); # restart timeout count next READLOOP; } } last READLOOP; } my @bits = split( //, unpack( 'b*', $rmask ) ); foreach my $pat (@params) { foreach my $exp ( @{ $pat->[0] } ) { next if not defined $exp->fileno(); # skip already closed if ( $bits[ $exp->fileno() ] ) { print STDERR ("${*$exp}{exp_Pty_Handle}: new data.\r\n") if $Expect::Debug; # read in what we found. my $buffer; my $nread = sysread( $exp, $buffer, 2048 ); # Make errors (nread undef) show up as EOF. $nread = 0 unless defined($nread); if ( $nread == 0 ) { print STDERR ("${*$exp}{exp_Pty_Handle}: EOF\r\n") if ($Expect::Debug); $before = ${*$exp}{exp_Before} = $exp->clear_accum(); $err = "2:EOF"; ${*$exp}{exp_Error} = $err; ${*$exp}{exp_Has_EOF} = 1; $exp_cont = undef; foreach my $eof_pat ( grep { $_->[1] eq '-eof' } @{$pat}[ 1 .. $#{$pat} ] ) { my $ret; print STDERR ( "Calling EOF hook $eof_pat->[3]...\r\n", ) if ($Expect::Debug); if ( $#{$eof_pat} > 3 ) { # call with parameters if given $ret = &{ $eof_pat->[3] }( $exp, @{$eof_pat}[ 4 .. $#{$eof_pat} ] ); } else { $ret = &{ $eof_pat->[3] }($exp); } if ($ret and ( $ret eq exp_continue or $ret eq exp_continue_timeout ) ) { $exp_cont = $ret; } } # is it dead? if ( defined( ${*$exp}{exp_Pid} ) ) { my $ret = waitpid( ${*$exp}{exp_Pid}, POSIX::WNOHANG ); if ( $ret == ${*$exp}{exp_Pid} ) { printf STDERR ( "%s: exit(0x%02X)\r\n", ${*$exp}{exp_Pty_Handle}, $? ) if ($Expect::Debug); $err = "3:Child PID ${*$exp}{exp_Pid} exited with status $?"; ${*$exp}{exp_Error} = $err; ${*$exp}{exp_Exit} = $?; delete $Expect::Spawned_PIDs{ ${*$exp}{exp_Pid} }; ${*$exp}{exp_Pid} = undef; } } print STDERR ("${*$exp}{exp_Pty_Handle}: closing...\r\n") if ($Expect::Debug); $exp->hard_close(); next; } print STDERR ("${*$exp}{exp_Pty_Handle}: read $nread byte(s).\r\n") if ($Expect::Debug); # ugly hack for broken solaris ttys that spew # into our pretty output $buffer =~ s/ \cH//g if not ${*$exp}{exp_Raw_Pty}; # Append it to the accumulator. ${*$exp}{exp_Accum} .= $buffer; if ( exists ${*$exp}{exp_Max_Accum} and ${*$exp}{exp_Max_Accum} ) { ${*$exp}{exp_Accum} = $exp->_trim_length( ${*$exp}{exp_Accum}, ${*$exp}{exp_Max_Accum} ); } ${*$exp}{exp_New_Data} = 1; # next round we try to match again $exp_cont = exp_continue if ( exists ${*$exp}{exp_Continue} and ${*$exp}{exp_Continue} ); # Now propagate what we have read to other listeners... $exp->_print_handles($buffer); # End handle reading section. } } } # end read loop $start_loop_time = time() # restart timeout count if ( $exp_cont and $exp_cont eq exp_continue ); } # End READLOOP # Post loop. Do we have anything? # Tell us status if ( $Expect::Debug or $Expect::Exp_Internal ) { if ($exp_matched) { print STDERR ( "Returning from expect ", ${*$exp_matched}{exp_Error} ? 'un' : '', "successfully.", ${*$exp_matched}{exp_Error} ? "\r\n Error: ${*$exp_matched}{exp_Error}." : '', "\r\n" ); } else { print STDERR ("Returning from expect with TIMEOUT or EOF\r\n"); } if ( $Expect::Debug and $exp_matched ) { print STDERR " ${*$exp_matched}{exp_Pty_Handle}: accumulator: `"; if ( ${*$exp_matched}{exp_Error} ) { print STDERR ( $exp_matched->_trim_length( _make_readable( ${*$exp_matched}{exp_Before} ) ), "'\r\n" ); } else { print STDERR ( $exp_matched->_trim_length( _make_readable( ${*$exp_matched}{exp_Accum} ) ), "'\r\n" ); } } } if ($exp_matched) { return wantarray ? ( ${*$exp_matched}{exp_Match_Number}, ${*$exp_matched}{exp_Error}, ${*$exp_matched}{exp_Match}, ${*$exp_matched}{exp_Before}, ${*$exp_matched}{exp_After}, $exp_matched, ) : ${*$exp_matched}{exp_Match_Number}; } return wantarray ? ( undef, $err, undef, $before, undef, undef ) : undef; } # Patterns are arrays that consist of # [ $pattern_type, $pattern, $sub, @subparms ] # optional $pattern_type is '-re' (RegExp, default) or '-ex' (exact); # $sub is optional CODE ref, which is called as &{$sub}($exp, @subparms) # if pattern matched; # the $parm_nr gets unshifted onto the array for reporting purposes. sub _add_patterns_to_list { my ($listref, $timeoutlistref,$store_parm_nr, @params) = @_; # $timeoutlistref gets timeout patterns my $parm_nr = $store_parm_nr || 1; foreach my $parm (@params) { if ( not ref($parm) eq 'ARRAY' ) { return "Parameter #$parm_nr is not an ARRAY ref."; } $parm = [@$parm]; # make copy if ( $parm->[0] =~ m/\A-/ ) { # it's an option if ( $parm->[0] ne '-re' and $parm->[0] ne '-ex' ) { return "Unknown option $parm->[0] in pattern #$parm_nr"; } } else { if ( $parm->[0] eq 'timeout' ) { if ( defined $timeoutlistref ) { splice @$parm, 0, 1, ( "-$parm->[0]", undef ); unshift @$parm, $store_parm_nr ? $parm_nr : undef; push @$timeoutlistref, $parm; } next; } elsif ( $parm->[0] eq 'eof' ) { splice @$parm, 0, 1, ( "-$parm->[0]", undef ); } else { unshift @$parm, '-re'; # defaults to RegExp } } if ( @$parm > 2 ) { if ( ref( $parm->[2] ) ne 'CODE' ) { croak( "Pattern #$parm_nr doesn't have a CODE reference", "after the pattern." ); } } else { push @$parm, undef; # make sure we have three elements } unshift @$parm, $store_parm_nr ? $parm_nr : undef; push @$listref, $parm; $parm_nr++; } return; } ###################################################################### # $process->interact([$in_handle],[$escape sequence]) # If you don't specify in_handle STDIN will be used. sub interact { my ($self, $infile, $escape_sequence) = @_; my $outfile; my @old_group = $self->set_group(); # If the handle is STDIN we'll # $infile->fileno == 0 should be stdin.. follow stdin rules. no strict 'subs'; # Allow bare word 'STDIN' unless ( defined($infile) ) { # We need a handle object Associated with STDIN. $infile = IO::File->new; $infile->IO::File::fdopen( STDIN, 'r' ); $outfile = IO::File->new; $outfile->IO::File::fdopen( STDOUT, 'w' ); } elsif ( fileno($infile) == fileno(STDIN) ) { # With STDIN we want output to go to stdout. $outfile = IO::File->new; $outfile->IO::File::fdopen( STDOUT, 'w' ); } else { undef($outfile); } # Here we assure ourselves we have an Expect object. my $in_object = Expect->exp_init($infile); if ( defined($outfile) ) { # as above.. we want output to go to stdout if we're given stdin. my $out_object = Expect->exp_init($outfile); $out_object->manual_stty(1); $self->set_group($out_object); } else { $self->set_group($in_object); } $in_object->set_group($self); $in_object->set_seq( $escape_sequence, undef ) if defined($escape_sequence); # interconnect normally sets stty -echo raw. Interact really sort # of implies we don't do that by default. If anyone wanted to they could # set it before calling interact, of use interconnect directly. my $old_manual_stty_val = $self->manual_stty(); $self->manual_stty(1); # I think this is right. Don't send stuff from in_obj to stdout by default. # in theory whatever 'self' is should echo what's going on. my $old_log_stdout_val = $self->log_stdout(); $self->log_stdout(0); $in_object->log_stdout(0); # Allow for the setting of an optional EOF escape function. # $in_object->set_seq('EOF',undef); # $self->set_seq('EOF',undef); Expect::interconnect( $self, $in_object ); $self->log_stdout($old_log_stdout_val); $self->set_group(@old_group); # If old_group was undef, make sure that occurs. This is a slight hack since # it modifies the value directly. # Normally an undef passed to set_group will return the current groups. # It is possible that it may be of worth to make it possible to undef # The current group without doing this. unless (@old_group) { @{ ${*$self}{exp_Listen_Group} } = (); } $self->manual_stty($old_manual_stty_val); return; } sub interconnect { my (@handles) = @_; # my ($handle)=(shift); call as Expect::interconnect($spawn1,$spawn2,...) my ( $nread ); my ( $rout, $emask, $eout ); my ( $escape_character_buffer ); my ( $read_mask, $temp_mask ) = ( '', '' ); # Get read/write handles foreach my $handle (@handles) { $temp_mask = ''; vec( $temp_mask, $handle->fileno(), 1 ) = 1; # Under Linux w/ 5.001 the next line comes up w/ 'Uninit var.'. # It appears to be impossible to make the warning go away. # doing something like $temp_mask='' unless defined ($temp_mask) # has no effect whatsoever. This may be a bug in 5.001. $read_mask = $read_mask | $temp_mask; } if ($Expect::Debug) { print STDERR "Read handles:\r\n"; foreach my $handle (@handles) { print STDERR "\tRead handle: "; print STDERR "'${*$handle}{exp_Pty_Handle}'\r\n"; print STDERR "\t\tListen Handles:"; foreach my $write_handle ( @{ ${*$handle}{exp_Listen_Group} } ) { print STDERR " '${*$write_handle}{exp_Pty_Handle}'"; } print STDERR ".\r\n"; } } # I think if we don't set raw/-echo here we may have trouble. We don't # want a bunch of echoing crap making all the handles jabber at each other. foreach my $handle (@handles) { unless ( ${*$handle}{"exp_Manual_Stty"} ) { # This is probably O/S specific. ${*$handle}{exp_Stored_Stty} = $handle->exp_stty('-g'); print STDERR "Setting tty for ${*$handle}{exp_Pty_Handle} to 'raw -echo'.\r\n" if ${*$handle}{"exp_Debug"}; $handle->exp_stty("raw -echo"); } foreach my $write_handle ( @{ ${*$handle}{exp_Listen_Group} } ) { unless ( ${*$write_handle}{"exp_Manual_Stty"} ) { ${*$write_handle}{exp_Stored_Stty} = $write_handle->exp_stty('-g'); print STDERR "Setting ${*$write_handle}{exp_Pty_Handle} to 'raw -echo'.\r\n" if ${*$handle}{"exp_Debug"}; $write_handle->exp_stty("raw -echo"); } } } print STDERR "Attempting interconnection\r\n" if $Expect::Debug; # Wait until the process dies or we get EOF # In the case of !${*$handle}{exp_Pid} it means # the handle was exp_inited instead of spawned. CONNECT_LOOP: # Go until we have a reason to stop while (1) { # test each handle to see if it's still alive. foreach my $read_handle (@handles) { waitpid( ${*$read_handle}{exp_Pid}, WNOHANG ) if ( exists( ${*$read_handle}{exp_Pid} ) and ${*$read_handle}{exp_Pid} ); if ( exists( ${*$read_handle}{exp_Pid} ) and ( ${*$read_handle}{exp_Pid} ) and ( !kill( 0, ${*$read_handle}{exp_Pid} ) ) ) { print STDERR "Got EOF (${*$read_handle}{exp_Pty_Handle} died) reading ${*$read_handle}{exp_Pty_Handle}\r\n" if ${*$read_handle}{"exp_Debug"}; last CONNECT_LOOP unless defined( ${ ${*$read_handle}{exp_Function} }{"EOF"} ); last CONNECT_LOOP unless &{ ${ ${*$read_handle}{exp_Function} }{"EOF"} } ( @{ ${ ${*$read_handle}{exp_Parameters} }{"EOF"} } ); } } # Every second? No, go until we get something from someone. my $nfound = select( $rout = $read_mask, undef, $eout = $emask, undef ); # Is there anything to share? May be -1 if interrupted by a signal... next CONNECT_LOOP if not defined $nfound or $nfound < 1; # Which handles have stuff? my @bits = split( //, unpack( 'b*', $rout ) ); $eout = 0 unless defined($eout); my @ebits = split( //, unpack( 'b*', $eout ) ); # print "Ebits: $eout\r\n"; foreach my $read_handle (@handles) { if ( $bits[ $read_handle->fileno() ] ) { $nread = sysread( $read_handle, ${*$read_handle}{exp_Pty_Buffer}, 1024 ); # Appease perl -w $nread = 0 unless defined($nread); print STDERR "interconnect: read $nread byte(s) from ${*$read_handle}{exp_Pty_Handle}.\r\n" if ${*$read_handle}{"exp_Debug"} > 1; # Test for escape seq. before printing. # Appease perl -w $escape_character_buffer = '' unless defined($escape_character_buffer); $escape_character_buffer .= ${*$read_handle}{exp_Pty_Buffer}; foreach my $escape_sequence ( keys( %{ ${*$read_handle}{exp_Function} } ) ) { print STDERR "Tested escape sequence $escape_sequence from ${*$read_handle}{exp_Pty_Handle}" if ${*$read_handle}{"exp_Debug"} > 1; # Make sure it doesn't grow out of bounds. $escape_character_buffer = $read_handle->_trim_length( $escape_character_buffer, ${*$read_handle}{"exp_Max_Accum"} ) if ( ${*$read_handle}{"exp_Max_Accum"} ); if ( $escape_character_buffer =~ /($escape_sequence)/ ) { my $match = $1; if ( ${*$read_handle}{"exp_Debug"} ) { print STDERR "\r\ninterconnect got escape sequence from ${*$read_handle}{exp_Pty_Handle}.\r\n"; # I'm going to make the esc. seq. pretty because it will # probably contain unprintable characters. print STDERR "\tEscape Sequence: '" . _trim_length( undef, _make_readable($escape_sequence) ) . "'\r\n"; print STDERR "\tMatched by string: '" . _trim_length( undef, _make_readable($match) ) . "'\r\n"; } # Print out stuff before the escape. # Keep in mind that the sequence may have been split up # over several reads. # Let's get rid of it from this read. If part of it was # in the last read there's not a lot we can do about it now. if ( ${*$read_handle}{exp_Pty_Buffer} =~ /([\w\W]*)($escape_sequence)/ ) { $read_handle->_print_handles($1); } else { $read_handle->_print_handles( ${*$read_handle}{exp_Pty_Buffer} ); } # Clear the buffer so no more matches can be made and it will # only be printed one time. ${*$read_handle}{exp_Pty_Buffer} = ''; $escape_character_buffer = ''; # Do the function here. Must return non-zero to continue. # More cool syntax. Maybe I should turn these in to objects. last CONNECT_LOOP unless &{ ${ ${*$read_handle}{exp_Function} }{$escape_sequence} } ( @{ ${ ${*$read_handle}{exp_Parameters} }{$escape_sequence} } ); } } $nread = 0 unless defined($nread); # Appease perl -w? waitpid( ${*$read_handle}{exp_Pid}, WNOHANG ) if ( defined( ${*$read_handle}{exp_Pid} ) && ${*$read_handle}{exp_Pid} ); if ( $nread == 0 ) { print STDERR "Got EOF reading ${*$read_handle}{exp_Pty_Handle}\r\n" if ${*$read_handle}{"exp_Debug"}; last CONNECT_LOOP unless defined( ${ ${*$read_handle}{exp_Function} }{"EOF"} ); last CONNECT_LOOP unless &{ ${ ${*$read_handle}{exp_Function} }{"EOF"} } ( @{ ${ ${*$read_handle}{exp_Parameters} }{"EOF"} } ); } last CONNECT_LOOP if ( $nread < 0 ); # This would be an error $read_handle->_print_handles( ${*$read_handle}{exp_Pty_Buffer} ); } # I'm removing this because I haven't determined what causes exceptions # consistently. if (0) #$ebits[$read_handle->fileno()]) { print STDERR "Got Exception reading ${*$read_handle}{exp_Pty_Handle}\r\n" if ${*$read_handle}{"exp_Debug"}; last CONNECT_LOOP unless defined( ${ ${*$read_handle}{exp_Function} }{"EOF"} ); last CONNECT_LOOP unless &{ ${ ${*$read_handle}{exp_Function} }{"EOF"} } ( @{ ${ ${*$read_handle}{exp_Parameters} }{"EOF"} } ); } } } foreach my $handle (@handles) { unless ( ${*$handle}{"exp_Manual_Stty"} ) { $handle->exp_stty( ${*$handle}{exp_Stored_Stty} ); } foreach my $write_handle ( @{ ${*$handle}{exp_Listen_Group} } ) { unless ( ${*$write_handle}{"exp_Manual_Stty"} ) { $write_handle->exp_stty( ${*$write_handle}{exp_Stored_Stty} ); } } } return; } # user can decide if log output gets also sent to logfile sub print_log_file { my ($self, @params) = @_; if ( ${*$self}{exp_Log_File} ) { if ( ref( ${*$self}{exp_Log_File} ) eq 'CODE' ) { ${*$self}{exp_Log_File}->(@params); } else { ${*$self}{exp_Log_File}->print(@params); } } return; } # we provide our own print so we can debug what gets sent to the # processes... sub print { my ( $self, @args ) = @_; return if not defined $self->fileno(); # skip if closed if ( ${*$self}{exp_Exp_Internal} ) { my $args = _make_readable( join( '', @args ) ); cluck "Sending '$args' to ${*$self}{exp_Pty_Handle}\r\n"; } foreach my $arg (@args) { while ( length($arg) > 80 ) { $self->SUPER::print( substr( $arg, 0, 80 ) ); $arg = substr( $arg, 80 ); } $self->SUPER::print($arg); } return; } # make an alias for Tcl/Expect users for a DWIM experience... *send = \&print; # This is an Expect standard. It's nice for talking to modems and the like # where from time to time they get unhappy if you send items too quickly. sub send_slow { my ($self, $sleep_time, @chunks) = @_; return if not defined $self->fileno(); # skip if closed # Flushing makes it so each character can be seen separately. my $chunk; while ( $chunk = shift @chunks ) { my @linechars = split( '', $chunk ); foreach my $char (@linechars) { # How slow? select( undef, undef, undef, $sleep_time ); print $self $char; print STDERR "Printed character \'" . _make_readable($char) . "\' to ${*$self}{exp_Pty_Handle}.\r\n" if ${*$self}{"exp_Debug"} > 1; # I think I can get away with this if I save it in accum if ( ${*$self}{"exp_Log_Stdout"} || ${*$self}{exp_Log_Group} ) { my $rmask = ""; vec( $rmask, $self->fileno(), 1 ) = 1; # .01 sec granularity should work. If we miss something it will # probably get flushed later, maybe in an expect call. while ( select( $rmask, undef, undef, .01 ) ) { my $ret = sysread( $self, ${*$self}{exp_Pty_Buffer}, 1024 ); last if not defined $ret or $ret == 0; # Is this necessary to keep? Probably.. # # if you need to expect it later. ${*$self}{exp_Accum} .= ${*$self}{exp_Pty_Buffer}; ${*$self}{exp_Accum} = $self->_trim_length( ${*$self}{exp_Accum}, ${*$self}{"exp_Max_Accum"} ) if ( ${*$self}{"exp_Max_Accum"} ); $self->_print_handles( ${*$self}{exp_Pty_Buffer} ); print STDERR "Received \'" . $self->_trim_length( _make_readable($char) ) . "\' from ${*$self}{exp_Pty_Handle}\r\n" if ${*$self}{"exp_Debug"} > 1; } } } } return; } sub test_handles { my ($timeout, @handle_list) = @_; # This should be called by Expect::test_handles($timeout,@objects); my ( $allmask, $rout ); foreach my $handle (@handle_list) { my $rmask = ''; vec( $rmask, $handle->fileno(), 1 ) = 1; $allmask = '' unless defined($allmask); $allmask = $allmask | $rmask; } my $nfound = select( $rout = $allmask, undef, undef, $timeout ); return () unless $nfound; # Which handles have stuff? my @bits = split( //, unpack( 'b*', $rout ) ); my $handle_num = 0; my @return_list = (); foreach my $handle (@handle_list) { # I go to great lengths to get perl -w to shut the hell up. if ( defined( $bits[ $handle->fileno() ] ) and ( $bits[ $handle->fileno() ] ) ) { push( @return_list, $handle_num ); } } continue { $handle_num++; } return @return_list; } # Be nice close. This should emulate what an interactive shell does after a # command finishes... sort of. We're not as patient as a shell. sub soft_close { my ($self) = @_; my ( $nfound, $nread, $rmask, $end_time, $temp_buffer ); # Give it 15 seconds to cough up an eof. cluck "Closing ${*$self}{exp_Pty_Handle}.\r\n" if ${*$self}{exp_Debug}; return -1 if not defined $self->fileno(); # skip if handle already closed unless ( exists ${*$self}{exp_Has_EOF} and ${*$self}{exp_Has_EOF} ) { $end_time = time() + 15; while ( $end_time > time() ) { my $select_time = $end_time - time(); # Sanity check. $select_time = 0 if $select_time < 0; $rmask = ''; vec( $rmask, $self->fileno(), 1 ) = 1; ($nfound) = select( $rmask, undef, undef, $select_time ); last unless ( defined($nfound) && $nfound ); $nread = sysread( $self, $temp_buffer, 8096 ); # 0 = EOF. unless ( defined($nread) && $nread ) { print STDERR "Got EOF from ${*$self}{exp_Pty_Handle}.\r\n" if ${*$self}{exp_Debug}; last; } $self->_print_handles($temp_buffer); } if ( ( $end_time <= time() ) && ${*$self}{exp_Debug} ) { print STDERR "Timed out waiting for an EOF from ${*$self}{exp_Pty_Handle}.\r\n"; } } my $close_status = $self->close(); if ( $close_status && ${*$self}{exp_Debug} ) { print STDERR "${*$self}{exp_Pty_Handle} closed.\r\n"; } # quit now if it isn't a process. return $close_status unless defined( ${*$self}{exp_Pid} ); # Now give it 15 seconds to die. $end_time = time() + 15; while ( $end_time > time() ) { my $returned_pid = waitpid( ${*$self}{exp_Pid}, &WNOHANG ); # Stop here if the process dies. if ( defined($returned_pid) && $returned_pid ) { delete $Expect::Spawned_PIDs{$returned_pid}; if ( ${*$self}{exp_Debug} ) { printf STDERR ( "Pid %d of %s exited, Status: 0x%02X\r\n", ${*$self}{exp_Pid}, ${*$self}{exp_Pty_Handle}, $? ); } ${*$self}{exp_Pid} = undef; ${*$self}{exp_Exit} = $?; return ${*$self}{exp_Exit}; } sleep 1; # Keep loop nice. } # Send it a term if it isn't dead. if ( ${*$self}{exp_Debug} ) { print STDERR "${*$self}{exp_Pty_Handle} not exiting, sending TERM.\r\n"; } kill TERM => ${*$self}{exp_Pid}; # Now to be anal retentive.. wait 15 more seconds for it to die. $end_time = time() + 15; while ( $end_time > time() ) { my $returned_pid = waitpid( ${*$self}{exp_Pid}, &WNOHANG ); if ( defined($returned_pid) && $returned_pid ) { delete $Expect::Spawned_PIDs{$returned_pid}; if ( ${*$self}{exp_Debug} ) { printf STDERR ( "Pid %d of %s terminated, Status: 0x%02X\r\n", ${*$self}{exp_Pid}, ${*$self}{exp_Pty_Handle}, $? ); } ${*$self}{exp_Pid} = undef; ${*$self}{exp_Exit} = $?; return $?; } sleep 1; } # Since this is a 'soft' close, sending it a -9 would be inappropriate. return; } # 'Make it go away' close. sub hard_close { my ($self) = @_; cluck "Closing ${*$self}{exp_Pty_Handle}.\r\n" if ${*$self}{exp_Debug}; # Don't wait for an EOF. my $close_status = $self->close(); if ( $close_status && ${*$self}{exp_Debug} ) { print STDERR "${*$self}{exp_Pty_Handle} closed.\r\n"; } # Return now if handle. return $close_status unless defined( ${*$self}{exp_Pid} ); # Now give it 5 seconds to die. Less patience here if it won't die. my $end_time = time() + 5; while ( $end_time > time() ) { my $returned_pid = waitpid( ${*$self}{exp_Pid}, &WNOHANG ); # Stop here if the process dies. if ( defined($returned_pid) && $returned_pid ) { delete $Expect::Spawned_PIDs{$returned_pid}; if ( ${*$self}{exp_Debug} ) { printf STDERR ( "Pid %d of %s terminated, Status: 0x%02X\r\n", ${*$self}{exp_Pid}, ${*$self}{exp_Pty_Handle}, $? ); } ${*$self}{exp_Pid} = undef; ${*$self}{exp_Exit} = $?; return ${*$self}{exp_Exit}; } sleep 1; # Keep loop nice. } # Send it a term if it isn't dead. if ( ${*$self}{exp_Debug} ) { print STDERR "${*$self}{exp_Pty_Handle} not exiting, sending TERM.\r\n"; } kill TERM => ${*$self}{exp_Pid}; # wait 15 more seconds for it to die. $end_time = time() + 15; while ( $end_time > time() ) { my $returned_pid = waitpid( ${*$self}{exp_Pid}, &WNOHANG ); if ( defined($returned_pid) && $returned_pid ) { delete $Expect::Spawned_PIDs{$returned_pid}; if ( ${*$self}{exp_Debug} ) { printf STDERR ( "Pid %d of %s terminated, Status: 0x%02X\r\n", ${*$self}{exp_Pid}, ${*$self}{exp_Pty_Handle}, $? ); } ${*$self}{exp_Pid} = undef; ${*$self}{exp_Exit} = $?; return ${*$self}{exp_Exit}; } sleep 1; } kill KILL => ${*$self}{exp_Pid}; # wait 5 more seconds for it to die. $end_time = time() + 5; while ( $end_time > time() ) { my $returned_pid = waitpid( ${*$self}{exp_Pid}, &WNOHANG ); if ( defined($returned_pid) && $returned_pid ) { delete $Expect::Spawned_PIDs{$returned_pid}; if ( ${*$self}{exp_Debug} ) { printf STDERR ( "Pid %d of %s killed, Status: 0x%02X\r\n", ${*$self}{exp_Pid}, ${*$self}{exp_Pty_Handle}, $? ); } ${*$self}{exp_Pid} = undef; ${*$self}{exp_Exit} = $?; return ${*$self}{exp_Exit}; } sleep 1; } warn "Pid ${*$self}{exp_Pid} of ${*$self}{exp_Pty_Handle} is HUNG.\r\n"; ${*$self}{exp_Pid} = undef; return; } # These should not be called externally. sub _init_vars { my ($self) = @_; # for every spawned process or filehandle. ${*$self}{exp_Log_Stdout} = $Expect::Log_Stdout if defined($Expect::Log_Stdout); ${*$self}{exp_Log_Group} = $Expect::Log_Group; ${*$self}{exp_Debug} = $Expect::Debug; ${*$self}{exp_Exp_Internal} = $Expect::Exp_Internal; ${*$self}{exp_Manual_Stty} = $Expect::Manual_Stty; ${*$self}{exp_Stored_Stty} = 'sane'; ${*$self}{exp_Do_Soft_Close} = $Expect::Do_Soft_Close; # sysread doesn't like my or local vars. ${*$self}{exp_Pty_Buffer} = ''; # Initialize accumulator. ${*$self}{exp_Max_Accum} = $Expect::Exp_Max_Accum; ${*$self}{exp_Accum} = ''; ${*$self}{exp_NoTransfer} = 0; # create empty expect_before & after lists ${*$self}{exp_expect_before_list} = []; ${*$self}{exp_expect_after_list} = []; return; } sub _make_readable { my ($s) = @_; $s = '' if not defined($s); study $s; # Speed things up? $s =~ s/\\/\\\\/g; # So we can tell easily(?) what is a backslash $s =~ s/\n/\\n/g; $s =~ s/\r/\\r/g; $s =~ s/\t/\\t/g; $s =~ s/\'/\\\'/g; # So we can tell whassa quote and whassa notta quote. $s =~ s/\"/\\\"/g; # Formfeed (does anyone use formfeed?) $s =~ s/\f/\\f/g; $s =~ s/\010/\\b/g; # escape control chars high/low, but allow ISO 8859-1 chars $s =~ s/([\000-\037\177-\237\377])/sprintf("\\%03lo",ord($1))/ge; return $s; } sub _trim_length { my ($self, $string, $length) = @_; # This is sort of a reverse truncation function # Mostly so we don't have to see the full output when we're using # Also used if Max_Accum gets set to limit the size of the accumulator # for matching functions. # exp_internal croak('No string passed') if not defined $string; # If we're not passed a length (_trim_length is being used for debugging # purposes) AND debug >= 3, don't trim. return ($string) if (defined($self) and ${*$self}{"exp_Debug"} >= 3 and ( !( defined($length) ) ) ); my $indicate_truncation = ($length ? '' : '...'); $length ||= 1021; return $string if $length >= length $string; # We wouldn't want the accumulator to begin with '...' if max_accum is passed # This is because this funct. gets called internally w/ max_accum # and is also used to print information back to the user. return $indicate_truncation . substr( $string, ( length($string) - $length ), $length ); } sub _print_handles { my ($self, $print_this) = @_; # Given crap from 'self' and the handles self wants to print to, print to # them. these are indicated by the handle's 'group' if ( ${*$self}{exp_Log_Group} ) { foreach my $handle ( @{ ${*$self}{exp_Listen_Group} } ) { $print_this = '' unless defined($print_this); # Appease perl -w print STDERR "Printed '" . $self->_trim_length( _make_readable($print_this) ) . "' to ${*$handle}{exp_Pty_Handle} from ${*$self}{exp_Pty_Handle}.\r\n" if ( ${*$handle}{"exp_Debug"} > 1 ); print $handle $print_this; } } # If ${*$self}{exp_Pty_Handle} is STDIN this would make it echo. print STDOUT $print_this if ${*$self}{"exp_Log_Stdout"}; $self->print_log_file($print_this); $| = 1; # This should not be necessary but autoflush() doesn't always work. return; } sub _get_mode { my ($handle) = @_; my ($fcntl_flags) = ''; # What mode are we opening with? use fcntl to find out. $fcntl_flags = fcntl( \*{$handle}, Fcntl::F_GETFL, $fcntl_flags ); die "fcntl returned undef during exp_init of $handle, $!\r\n" unless defined($fcntl_flags); if ( $fcntl_flags | (Fcntl::O_RDWR) ) { return 'rw'; } elsif ( $fcntl_flags | (Fcntl::O_WRONLY) ) { return 'w'; } else { # Under Solaris (among others?) O_RDONLY is implemented as 0. so |O_RDONLY would fail. return 'r'; } } sub _undef { return undef; # Seems a little retarded but &CORE::undef fails in interconnect. # This is used for the default escape sequence function. # w/out the leading & it won't compile. } # clean up child processes sub DESTROY { my ($self) = @_; my $status = $?; # save this as it gets mangled by the terminating spawned children if ( ${*$self}{exp_Do_Soft_Close} ) { $self->soft_close(); } $self->hard_close(); $? = $status; # restore it. otherwise deleting an Expect object may mangle $?, which is unintuitive return; } 1; __END__ =head1 NAME Expect - automate interactions with command line programs that expose a text terminal interface. =head1 SYNOPSIS use Expect; # create an Expect object by spawning another process my $exp = Expect->spawn($command, @params) or die "Cannot spawn $command: $!\n"; # or by using an already opened filehandle (e.g. from Net::Telnet) my $exp = Expect->exp_init(\*FILEHANDLE); # if you prefer the OO mindset: my $exp = Expect->new; $exp->raw_pty(1); $exp->spawn($command, @parameters) or die "Cannot spawn $command: $!\n"; # send some string there: $exp->send("string\n"); # or, for the filehandle mindset: print $exp "string\n"; # then do some pattern matching with either the simple interface $patidx = $exp->expect($timeout, @match_patterns); # or multi-match on several spawned commands with callbacks, # just like the Tcl version $exp->expect($timeout, [ qr/regex1/ => sub { my $exp = shift; $exp->send("response\n"); exp_continue; } ], [ "regexp2" , \&callback, @cbparms ], ); # if no longer needed, do a soft_close to nicely shut down the command $exp->soft_close(); # or be less patient with $exp->hard_close(); Expect.pm is built to either spawn a process or take an existing filehandle and interact with it such that normally interactive tasks can be done without operator assistance. This concept makes more sense if you are already familiar with the versatile Tcl version of Expect. The public functions that make up Expect.pm are: Expect->new() Expect::interconnect(@objects_to_be_read_from) Expect::test_handles($timeout, @objects_to_test) Expect::version($version_requested | undef); $object->spawn(@command) $object->clear_accum() $object->set_accum($value) $object->debug($debug_level) $object->exp_internal(0 | 1) $object->notransfer(0 | 1) $object->raw_pty(0 | 1) $object->stty(@stty_modes) # See the IO::Stty docs $object->slave() $object->before(); $object->match(); $object->after(); $object->matchlist(); $object->match_number(); $object->error(); $object->command(); $object->exitstatus(); $object->pty_handle(); $object->do_soft_close(); $object->restart_timeout_upon_receive(0 | 1); $object->interact($other_object, $escape_sequence) $object->log_group(0 | 1 | undef) $object->log_user(0 | 1 | undef) $object->log_file("filename" | $filehandle | \&coderef | undef) $object->manual_stty(0 | 1 | undef) $object->match_max($max_buffersize or undef) $object->pid(); $object->send_slow($delay, @strings_to_send) $object->set_group(@listen_group_objects | undef) $object->set_seq($sequence,\&function,\@parameters); There are several configurable package variables that affect the behavior of Expect. They are: $Expect::Debug; $Expect::Exp_Internal; $Expect::IgnoreEintr; $Expect::Log_Group; $Expect::Log_Stdout; $Expect::Manual_Stty; $Expect::Multiline_Matching; $Expect::Do_Soft_Close; =head1 DESCRIPTION See an explanation of L The Expect module is a successor of Comm.pl and a descendent of Chat.pl. It more closely resembles the Tcl Expect language than its predecessors. It does not contain any of the networking code found in Comm.pl. I suspect this would be obsolete anyway given the advent of IO::Socket and external tools such as netcat. Expect.pm is an attempt to have more of a switch() & case feeling to make decision processing more fluid. Three separate types of debugging have been implemented to make code production easier. It is possible to interconnect multiple file handles (and processes) much like Tcl's Expect. An attempt was made to enable all the features of Tcl's Expect without forcing Tcl on the victim programmer :-) . Please, before you consider using Expect, read the FAQs about L and L =head1 USAGE =over 4 =item new Creates a new Expect object, i.e. a pty. You can change parameters on it before actually spawning a command. This is important if you want to modify the terminal settings for the slave. See slave() below. The object returned is actually a reblessed IO::Pty filehandle, so see there for additional methods. =item Expect->exp_init(\*FILEHANDLE) I =item Expect->init(\*FILEHANDLE) Initializes $new_handle_object for use with other Expect functions. It must be passed a B<_reference_> to FILEHANDLE if you want it to work properly. IO::File objects are preferable. Returns a reference to the newly created object. You can use only real filehandles, certain tied filehandles (e.g. Net::SSH2) that lack a fileno() will not work. Net::Telnet objects can be used but have been reported to work only for certain hosts. YMMV. =item Expect->spawn($command, @parameters) I =item $object->spawn($command, @parameters) I =item Expect->new($command, @parameters) Forks and execs $command. Returns an Expect object upon success or C if the fork was unsuccessful or the command could not be found. spawn() passes its parameters unchanged to Perls exec(), so look there for detailed semantics. Note that if spawn cannot exec() the given command, the Expect object is still valid and the next expect() will see "Cannot exec", so you can use that for error handling. Also note that you cannot reuse an object with an already spawned command, even if that command has exited. Sorry, but you have to allocate a new object... =item $object->debug(0 | 1 | 2 | 3 | undef) Sets debug level for $object. 1 refers to general debugging information, 2 refers to verbose debugging and 0 refers to no debugging. If you call debug() with no parameters it will return the current debugging level. When the object is created the debugging level will match that $Expect::Debug, normally 0. The '3' setting is new with 1.05, and adds the additional functionality of having the _full_ accumulated buffer printed every time data is read from an Expect object. This was implemented by request. I recommend against using this unless you think you need it as it can create quite a quantity of output under some circumstances.. =item $object->exp_internal(1 | 0) Sets/unsets 'exp_internal' debugging. This is similar in nature to its Tcl counterpart. It is extremely valuable when debugging expect() sequences. When the object is created the exp_internal setting will match the value of $Expect::Exp_Internal, normally 0. Returns the current setting if called without parameters. It is highly recommended that you make use of the debugging features lest you have angry code. =item $object->raw_pty(1 | 0) Set pty to raw mode before spawning. This disables echoing, CR->LF translation and an ugly hack for broken Solaris TTYs (which send to slow things down) and thus gives a more pipe-like behaviour (which is important if you want to transfer binary content). Note that this must be set I spawning the program. =item $object->stty(qw(mode1 mode2...)) Sets the tty mode for $object's associated terminal to the given modes. Note that on many systems the master side of the pty is not a tty, so you have to modify the slave pty instead, see next item. This needs IO::Stty installed, which is no longer required. =item $object->slave() Returns a filehandle to the slave part of the pty. Very useful in modifying the terminal settings: $object->slave->stty(qw(raw -echo)); Typical values are 'sane', 'raw', and 'raw -echo'. Note that I recommend setting the terminal to 'raw' or 'raw -echo', as this avoids a lot of hassle and gives pipe-like (i.e. transparent) behaviour (without the buffering issue). =item $object->print(@strings) I =item $object->send(@strings) Sends the given strings to the spawned command. Note that the strings are not logged in the logfile (see print_log_file) but will probably be echoed back by the pty, depending on pty settings (default is echo) and thus end up there anyway. This must also be taken into account when expect()ing for an answer: the next string will be the command just sent. I suggest setting the pty to raw, which disables echo and makes the pty transparently act like a bidirectional pipe. =item $object->expect($timeout, @match_patterns) =over 4 =item Simple interface Given $timeout in seconds Expect will wait for $object's handle to produce one of the match_patterns, which are matched exactly by default. If you want a regexp match, use a regexp object (C) or prefix the pattern with '-re'. $object->expect(15, 'match me exactly', qr/match\s+me\s+exactly/); $object->expect(15, 'match me exactly','-re','match\s+me\s+exactly'); Due to o/s limitations $timeout should be a round number. If $timeout is 0 Expect will check one time to see if $object's handle contains any of the match_patterns. If $timeout is undef Expect will wait forever for a pattern to match. If you don't want to explicitly put the timeout on all calls to C, you can set it via the C method . If the first argument of C doesn't look like a number, that value will be used. $object->timeout(15); $object->expect('match me exactly','-re','match\s+me\s+exactly'); If called in a scalar context, expect() will return the position of the matched pattern within @matched_patterns, or undef if no pattern was matched. This is a position starting from 1, so if you want to know which of an array of @matched_patterns matched you should subtract one from the return value. If called in an array context expect() will return ($matched_pattern_position, $error, $successfully_matching_string, $before_match, and $after_match). C<$matched_pattern_position> will contain the value that would have been returned if expect() had been called in a scalar context. C<$error> is the error that occurred that caused expect() to return. $error will contain a number followed by a string equivalent expressing the nature of the error. Possible values are undef, indicating no error, '1:TIMEOUT' indicating that $timeout seconds had elapsed without a match, '2:EOF' indicating an eof was read from $object, '3: spawn id($fileno) died' indicating that the process exited before matching and '4:$!' indicating whatever error was set in $ERRNO during the last read on $object's handle or during select(). All handles indicated by set_group plus STDOUT will have all data to come out of $object printed to them during expect() if log_group and log_stdout are set. C<$successfully_matching_string> C<$before_match> C<$after_match> Changed from older versions is the regular expression handling. By default now all strings passed to expect() are treated as literals. To match a regular expression pass '-re' as a parameter in front of the pattern you want to match as a regexp. This change makes it possible to match literals and regular expressions in the same expect() call. Also new is multiline matching. ^ will now match the beginning of lines. Unfortunately, because perl doesn't use $/ in determining where lines break using $ to find the end of a line frequently doesn't work. This is because your terminal is returning "\r\n" at the end of every line. One way to check for a pattern at the end of a line would be to use \r?$ instead of $. Example: Spawning telnet to a host, you might look for the escape character. telnet would return to you "\r\nEscape character is '^]'.\r\n". To find this you might use $match='^Escape char.*\.\r?$'; $telnet->expect(10,'-re',$match); =item New more Tcl/Expect-like interface expect($timeout, '-i', [ $obj1, $obj2, ... ], [ $re_pattern, sub { ...; exp_continue; }, @subparms, ], [ 'eof', sub { ... } ], [ 'timeout', sub { ... }, \$subparm1 ], '-i', [ $objn, ...], '-ex', $exact_pattern, sub { ... }, $exact_pattern, sub { ...; exp_continue_timeout; }, '-re', $re_pattern, sub { ... }, '-i', \@object_list, @pattern_list, ...); It's now possible to expect on more than one connection at a time by specifying 'C<-i>' and a single Expect object or a ref to an array containing Expect objects, e.g. expect($timeout, '-i', $exp1, @patterns_1, '-i', [ $exp2, $exp3 ], @patterns_2_3, ) Furthermore, patterns can now be specified as array refs containing [$regexp, sub { ...}, @optional_subprams] . When the pattern matches, the subroutine is called with parameters ($matched_expect_obj, @optional_subparms). The subroutine can return the symbol `exp_continue' to continue the expect matching with timeout starting anew or return the symbol `exp_continue_timeout' for continuing expect without resetting the timeout count. $exp->expect($timeout, [ qr/username: /i, sub { my $self = shift; $self->send("$username\n"); exp_continue; }], [ qr/password: /i, sub { my $self = shift; $self->send("$password\n"); exp_continue; }], $shell_prompt); `expect' is now exported by default. =back =item $object->exp_before() I =item $object->before() before() returns the 'before' part of the last expect() call. If the last expect() call didn't match anything, exp_before() will return the entire output of the object accumulated before the expect() call finished. Note that this is something different than Tcl Expects before()!! =item $object->exp_after() I =item $object->after() returns the 'after' part of the last expect() call. If the last expect() call didn't match anything, exp_after() will return undef(). =item $object->exp_match() I =item $object->match() returns the string matched by the last expect() call, undef if no string was matched. =item $object->exp_match_number() I =item $object->match_number() exp_match_number() returns the number of the pattern matched by the last expect() call. Keep in mind that the first pattern in a list of patterns is 1, not 0. Returns undef if no pattern was matched. =item $object->exp_matchlist() I =item $object->matchlist() exp_matchlist() returns a list of matched substrings from the brackets () inside the regexp that last matched. ($object->matchlist)[0] thus corresponds to $1, ($object->matchlist)[1] to $2, etc. =item $object->exp_error() I =item $object->error() exp_error() returns the error generated by the last expect() call if no pattern was matched. It is typically useful to examine the value returned by before() to find out what the output of the object was in determining why it didn't match any of the patterns. =item $object->clear_accum() Clear the contents of the accumulator for $object. This gets rid of any residual contents of a handle after expect() or send_slow() such that the next expect() call will only see new data from $object. The contents of the accumulator are returned. =item $object->set_accum($value) Sets the content of the accumulator for $object to $value. The previous content of the accumulator is returned. =item $object->exp_command() I =item $object->command() exp_command() returns the string that was used to spawn the command. Helpful for debugging and for reused patternmatch subroutines. =item $object->exp_exitstatus() I =item $object->exitstatus() Returns the exit status of $object (if it already exited). =item $object->exp_pty_handle() I =item $object->pty_handle() Returns a string representation of the attached pty, for example: `spawn id(5)' (pty has fileno 5), `handle id(7)' (pty was initialized from fileno 7) or `STDIN'. Useful for debugging. =item $object->restart_timeout_upon_receive(0 | 1) If this is set to 1, the expect timeout is retriggered whenever something is received from the spawned command. This allows to perform some aliveness testing and still expect for patterns. $exp->restart_timeout_upon_receive(1); $exp->expect($timeout, [ timeout => \&report_timeout ], [ qr/pattern/ => \&handle_pattern], ); Now the timeout isn't triggered if the command produces any kind of output, i.e. is still alive, but you can act upon patterns in the output. =item $object->notransfer(1 | 0) Do not truncate the content of the accumulator after a match. Normally, the accumulator is set to the remains that come after the matched string. Note that this setting is per object and not per pattern, so if you want to have normal acting patterns that truncate the accumulator, you have to add a $exp->set_accum($exp->after); to their callback, e.g. $exp->notransfer(1); $exp->expect($timeout, # accumulator not truncated, pattern1 will match again [ "pattern1" => sub { my $self = shift; ... } ], # accumulator truncated, pattern2 will not match again [ "pattern2" => sub { my $self = shift; ... $self->set_accum($self->after()); } ], ); This is only a temporary fix until I can rewrite the pattern matching part so it can take that additional -notransfer argument. =item Expect::interconnect(@objects); Read from @objects and print to their @listen_groups until an escape sequence is matched from one of @objects and the associated function returns 0 or undef. The special escape sequence 'EOF' is matched when an object's handle returns an end of file. Note that it is not necessary to include objects that only accept data in @objects since the escape sequence is _read_ from an object. Further note that the listen_group for a write-only object is always empty. Why would you want to have objects listening to STDOUT (for example)? By default every member of @objects _as well as every member of its listen group_ will be set to 'raw -echo' for the duration of interconnection. Setting $object->manual_stty() will stop this behavior per object. The original tty settings will be restored as interconnect exits. For a generic way to interconnect processes, take a look at L. =item Expect::test_handles(@objects) Given a set of objects determines which objects' handles have data ready to be read. B who's members are positions in @objects that have ready handles. Returns undef if there are no such handles ready. =item Expect::version($version_requested or undef); Returns current version of Expect. As of .99 earlier versions are not supported. Too many things were changed to make versioning possible. =item $object->interact( C<\*FILEHANDLE, $escape_sequence>) interact() is essentially a macro for calling interconnect() for connecting 2 processes together. \*FILEHANDLE defaults to \*STDIN and $escape_sequence defaults to undef. Interaction ceases when $escape_sequence is read from B, not $object. $object's listen group will consist solely of \*FILEHANDLE for the duration of the interaction. \*FILEHANDLE will not be echoed on STDOUT. =item $object->log_group(0 | 1 | undef) Set/unset logging of $object to its 'listen group'. If set all objects in the listen group will have output from $object printed to them during $object->expect(), $object->send_slow(), and C. Default value is on. During creation of $object the setting will match the value of $Expect::Log_Group, normally 1. =item $object->log_user(0 | 1 | undef) I =item $object->log_stdout(0 | 1 | undef) Set/unset logging of object's handle to STDOUT. This corresponds to Tcl's log_user variable. Returns current setting if called without parameters. Default setting is off for initialized handles. When a process object is created (not a filehandle initialized with exp_init) the log_stdout setting will match the value of $Expect::Log_Stdout variable, normally 1. If/when you initialize STDIN it is usually associated with a tty which will by default echo to STDOUT anyway, so be careful or you will have multiple echoes. =item $object->log_file("filename" | $filehandle | \&coderef | undef) Log session to a file. All characters send to or received from the spawned process are written to the file. Normally appends to the logfile, but you can pass an additional mode of "w" to truncate the file upon open(): $object->log_file("filename", "w"); Returns the logfilehandle. If called with an undef value, stops logging and closes logfile: $object->log_file(undef); If called without argument, returns the logfilehandle: $fh = $object->log_file(); Can be set to a code ref, which will be called instead of printing to the logfile: $object->log_file(\&myloggerfunc); =item $object->print_log_file(@strings) Prints to logfile (if opened) or calls the logfile hook function. This allows the user to add arbitrary text to the logfile. Note that this could also be done as $object->log_file->print() but would only work for log files, not code hooks. =item $object->set_seq($sequence, \&function, \@function_parameters) During Expect->interconnect() if $sequence is read from $object &function will be executed with parameters @function_parameters. It is B<_highly recommended_> that the escape sequence be a single character since the likelihood is great that the sequence will be broken into to separate reads from the $object's handle, making it impossible to strip $sequence from getting printed to $object's listen group. \&function should be something like 'main::control_w_function' and @function_parameters should be an array defined by the caller, passed by reference to set_seq(). Your function should return a non-zero value if execution of interconnect() is to resume after the function returns, zero or undefined if interconnect() should return after your function returns. The special sequence 'EOF' matches the end of file being reached by $object. See interconnect() for details. =item $object->set_group(@listener_objects) @listener_objects is the list of objects that should have their handles printed to by $object when Expect::interconnect, $object->expect() or $object->send_slow() are called. Calling w/out parameters will return the current list of the listener objects. =item $object->manual_stty(0 | 1 | undef) Sets/unsets whether or not Expect should make reasonable guesses as to when and how to set tty parameters for $object. Will match $Expect::Manual_Stty value (normally 0) when $object is created. If called without parameters manual_stty() will return the current manual_stty setting. =item $object->match_max($maximum_buffer_length | undef) I =item $object->max_accum($maximum_buffer_length | undef) Set the maximum accumulator size for object. This is useful if you think that the accumulator will grow out of hand during expect() calls. Since the buffer will be matched by every match_pattern it may get slow if the buffer gets too large. Returns current value if called without parameters. Not defined by default. =item $object->notransfer(0 | 1) If set, matched strings will not be deleted from the accumulator. Returns current value if called without parameters. False by default. =item $object->exp_pid() I =item $object->pid() Return pid of $object, if one exists. Initialized filehandles will not have pids (of course). =item $object->send_slow($delay, @strings); print each character from each string of @strings one at a time with $delay seconds before each character. This is handy for devices such as modems that can be annoying if you send them data too fast. After each character $object will be checked to determine whether or not it has any new data ready and if so update the accumulator for future expect() calls and print the output to STDOUT and @listen_group if log_stdout and log_group are appropriately set. =back =head2 Configurable Package Variables: =over 4 =item $Expect::Debug Defaults to 0. Newly created objects have a $object->debug() value of $Expect::Debug. See $object->debug(); =item $Expect::Do_Soft_Close Defaults to 0. When destroying objects, soft_close may take up to half a minute to shut everything down. From now on, only hard_close will be called, which is less polite but still gives the process a chance to terminate properly. Set this to '1' for old behaviour. =item $Expect::Exp_Internal Defaults to 0. Newly created objects have a $object->exp_internal() value of $Expect::Exp_Internal. See $object->exp_internal(). =item $Expect::IgnoreEintr Defaults to 0. If set to 1, when waiting for new data, Expect will ignore EINTR errors and restart the select() call instead. =item $Expect::Log_Group Defaults to 1. Newly created objects have a $object->log_group() value of $Expect::Log_Group. See $object->log_group(). =item $Expect::Log_Stdout Defaults to 1 for spawned commands, 0 for file handles attached with exp_init(). Newly created objects have a $object->log_stdout() value of $Expect::Log_Stdout. See $object->log_stdout(). =item $Expect::Manual_Stty Defaults to 0. Newly created objects have a $object->manual_stty() value of $Expect::Manual_Stty. See $object->manual_stty(). =item $Expect::Multiline_Matching Defaults to 1. Affects whether or not expect() uses the /m flag for doing regular expression matching. If set to 1 /m is used. This makes a difference when you are trying to match ^ and $. If you have this on you can match lines in the middle of a page of output using ^ and $ instead of it matching the beginning and end of the entire expression. I think this is handy. The $Expect::Multiline_Matching turns on and off Expect's multi-line matching mode. But this only has an effect if you pass in a string, and then use '-re' mode. If you pass in a regular expression value (via qr//), then the qr//'s own flags are preserved irrespective of what it gets interpolated into. There was a bug in Perl 5.8.x where interpolating a regex without /m into a match with /m would incorrectly apply the /m to the inner regex too, but this was fixed in Perl 5.10. The correct behavior, as seen in Perl 5.10, is that if you pass in a regex (via qr//), then $Expect::Multiline_Matching has no effect. So if you pass in a regex, then you must use the qr's flags to control whether it is multiline (which by default it is not, opposite of the default behavior of Expect). =back =head1 CONTRIBUTIONS Lee Eakin has ported the kibitz script from Tcl/Expect to Perl/Expect. Jeff Carr provided a simple example of how handle terminal window resize events (transmitted via the WINCH signal) in a ssh session. You can find both scripts in the examples/ subdir. Thanks to both! Historical notes: There are still a few lines of code dating back to the inspirational Comm.pl and Chat.pl modules without which this would not have been possible. Kudos to Eric Arnold and Randal 'Nuke your NT box with one line of perl code' Schwartz for making these available to the perl public. As of .98 I think all the old code is toast. No way could this have been done without it though. Special thanks to Graham Barr for helping make sense of the IO::Handle stuff as well as providing the highly recommended IO::Tty module. =head1 REFERENCES Mark Rogaski wrote: "I figured that you'd like to know that Expect.pm has been very useful to AT&T Labs over the past couple of years (since I first talked to Austin about design decisions). We use Expect.pm for managing the switches in our network via the telnet interface, and such automation has significantly increased our reliability. So, you can honestly say that one of the largest digital networks in existence (AT&T Frame Relay) uses Expect.pm quite extensively." =head1 FAQ - Frequently Asked Questions This is a growing collection of things that might help. Please send you questions that are not answered here to RGiersig@cpan.org =head2 What systems does Expect run on? Expect itself doesn't have real system dependencies, but the underlying IO::Tty needs pseudoterminals. IO::Stty uses POSIX.pm and Fcntl.pm. I have used it on Solaris, Linux and AIX, others report *BSD and OSF as working. Generally, any modern POSIX Unix should do, but there are exceptions to every rule. Feedback is appreciated. See L for a list of verified systems. =head2 Can I use this module with ActivePerl on Windows? Up to now, the answer was 'No', but this has changed. You still cannot use ActivePerl, but if you use the Cygwin environment (http://sources.redhat.com), which brings its own perl, and have the latest IO::Tty (v0.05 or later) installed, it should work (feedback appreciated). =head2 The examples in the tutorial don't work! The tutorial is hopelessly out of date and needs a serious overhaul. I apologize for this, I have concentrated my efforts mainly on the functionality. Volunteers welcomed. =head2 How can I find out what Expect is doing? If you set $Expect::Exp_Internal = 1; Expect will tell you very verbosely what it is receiving and sending, what matching it is trying and what it found. You can do this on a per-command base with $exp->exp_internal(1); You can also set $Expect::Debug = 1; # or 2, 3 for more verbose output or $exp->debug(1); which gives you even more output. =head2 I am seeing the output of the command I spawned. Can I turn that off? Yes, just set $Expect::Log_Stdout = 0; to globally disable it or $exp->log_stdout(0); for just that command. 'log_user' is provided as an alias so Tcl/Expect user get a DWIM experience... :-) =head2 No, I mean that when I send some text to the spawned process, it gets echoed back and I have to deal with it in the next expect. This is caused by the pty, which has probably 'echo' enabled. A solution would be to set the pty to raw mode, which in general is cleaner for communication between two programs (no more unexpected character translations). Unfortunately this would break a lot of old code that sends "\r" to the program instead of "\n" (translating this is also handled by the pty), so I won't add this to Expect just like that. But feel free to experiment with C<$exp-Eraw_pty(1)>. =head2 How do I send control characters to a process? A: You can send any characters to a process with the print command. To represent a control character in Perl, use \c followed by the letter. For example, control-G can be represented with "\cG" . Note that this will not work if you single-quote your string. So, to send control-C to a process in $exp, do: print $exp "\cC"; Or, if you prefer: $exp->send("\cC"); The ability to include control characters in a string like this is provided by Perl, not by Expect.pm . Trying to learn Expect.pm without a thorough grounding in Perl can be very daunting. We suggest you look into some of the excellent Perl learning material, such as the books _Programming Perl_ and _Learning Perl_ by O'Reilly, as well as the extensive online Perl documentation available through the perldoc command. =head2 My script fails from time to time without any obvious reason. It seems that I am sometimes loosing output from the spawned program. You could be exiting too fast without giving the spawned program enough time to finish. Try adding $exp->soft_close() to terminate the program gracefully or do an expect() for 'eof'. Alternatively, try adding a 'sleep 1' after you spawn() the program. It could be that pty creation on your system is just slow (but this is rather improbable if you are using the latest IO-Tty). =head2 I want to automate password entry for su/ssh/scp/rsh/... You shouldn't use Expect for this. Putting passwords, especially root passwords, into scripts in clear text can mean severe security problems. I strongly recommend using other means. For 'su', consider switching to 'sudo', which gives you root access on a per-command and per-user basis without the need to enter passwords. 'ssh'/'scp' can be set up with RSA authentication without passwords. 'rsh' can use the .rhost mechanism, but I'd strongly suggest to switch to 'ssh'; to mention 'rsh' and 'security' in the same sentence makes an oxymoron. It will work for 'telnet', though, and there are valid uses for it, but you still might want to consider using 'ssh', as keeping cleartext passwords around is very insecure. =head2 I want to use Expect to automate [anything with a buzzword]... Are you sure there is no other, easier way? As a rule of thumb, Expect is useful for automating things that expect to talk to a human, where no formal standard applies. For other tasks that do follow a well-defined protocol, there are often better-suited modules that already can handle those protocols. Don't try to do HTTP requests by spawning telnet to port 80, use LWP instead. To automate FTP, take a look at L or C (http://www.ncftp.org). You don't use a screwdriver to hammer in your nails either, or do you? =head2 Is it possible to use threads with Expect? Basically yes, with one restriction: you must spawn() your programs in the main thread and then pass the Expect objects to the handling threads. The reason is that spawn() uses fork(), and L: "Thinking of mixing fork() and threads? Please lie down and wait until the feeling passes." =head2 I want to log the whole session to a file. Use $exp->log_file("filename"); or $exp->log_file($filehandle); or even $exp->log_file(\&log_procedure); for maximum flexibility. Note that the logfile is appended to by default, but you can specify an optional mode "w" to truncate the logfile: $exp->log_file("filename", "w"); To stop logging, just call it with a false argument: $exp->log_file(undef); =head2 How can I turn off multi-line matching for my regexps? To globally unset multi-line matching for all regexps: $Expect::Multiline_Matching = 0; You can do that on a per-regexp basis by stating C<(?-m)> inside the regexp (you need perl5.00503 or later for that). =head2 How can I expect on multiple spawned commands? You can use the B<-i> parameter to specify a single object or a list of Expect objects. All following patterns will be evaluated against that list. You can specify B<-i> multiple times to create groups of objects and patterns to match against within the same expect statement. This works just like in Tcl/Expect. See the source example below. =head2 I seem to have problems with ptys! Well, pty handling is really a black magic, as it is extremely system dependent. I have extensively revised IO-Tty, so these problems should be gone. If your system is listed in the "verified" list of IO::Tty, you probably have some non-standard setup, e.g. you compiled your Linux-kernel yourself and disabled ptys. Please ask your friendly sysadmin for help. If your system is not listed, unpack the latest version of IO::Tty, do a 'perl Makefile.PL; make; make test; uname C<-a>' and send me the results and I'll see what I can deduce from that. =head2 I just want to read the output of a process without expect()ing anything. How can I do this? [ Are you sure you need Expect for this? How about qx() or open("prog|")? ] By using expect without any patterns to match. $process->expect(undef); # Forever until EOF $process->expect($timeout); # For a few seconds $process->expect(0); # Is there anything ready on the handle now? =head2 Ok, so now how do I get what was read on the handle? $read = $process->before(); =head2 Where's IO::Pty? Find it on CPAN as IO-Tty, which provides both. =head2 How come when I automate the passwd program to change passwords for me passwd dies before changing the password sometimes/every time? What's happening is you are closing the handle before passwd exits. When you close the handle to a process, it is sent a signal (SIGPIPE?) telling it that STDOUT has gone away. The default behavior for processes is to die in this circumstance. Two ways you can make this not happen are: $process->soft_close(); This will wait 15 seconds for a process to come up with an EOF by itself before killing it. $process->expect(undef); This will wait forever for the process to match an empty set of patterns. It will return when the process hits an EOF. As a rule, you should always expect() the result of your transaction before you continue with processing. =head2 How come when I try to make a logfile with log_file() or set_group() it doesn't print anything after the last time I run expect()? Output is only printed to the logfile/group when Expect reads from the process, during expect(), send_slow() and interconnect(). One way you can force this is to make use of $process->expect(undef); and $process->expect(0); which will make expect() run with an empty pattern set forever or just for an instant to capture the output of $process. The output is available in the accumulator, so you can grab it using $process->before(). =head2 I seem to have problems with terminal settings, double echoing, etc. Tty settings are a major pain to keep track of. If you find unexpected behavior such as double-echoing or a frozen session, doublecheck the documentation for default settings. When in doubt, handle them yourself using $exp->stty() and manual_stty() functions. As of .98 you shouldn't have to worry about stty settings getting fouled unless you use interconnect or intentionally change them (like doing -echo to get a password). If you foul up your terminal's tty settings, kill any hung processes and enter 'stty sane' at a shell prompt. This should make your terminal manageable again. Note that IO::Tty returns ptys with your systems default setting regarding echoing, CRLF translation etc. and Expect does not change them. I have considered setting the ptys to 'raw' without any translation whatsoever, but this would break a lot of existing things, as '\r' translation would not work anymore. On the other hand, a raw pty works much like a pipe and is more WYGIWYE (what you get is what you expect), so I suggest you set it to 'raw' by yourself: $exp = Expect->new; $exp->raw_pty(1); $exp->spawn(...); To disable echo: $exp->slave->stty(qw(-echo)); =head2 I'm spawning a telnet/ssh session and then let the user interact with it. But screen-oriented applications on the other side don't work properly. You have to set the terminal screen size for that. Luckily, IO::Pty already has a method for that, so modify your code to look like this: my $exp = Expect->new; $exp->slave->clone_winsize_from(\*STDIN); $exp->spawn("telnet somehost); Also, some applications need the TERM shell variable set so they know how to move the cursor across the screen. When logging in, the remote shell sends a query (Ctrl-Z I think) and expects the terminal to answer with a string, e.g. 'xterm'. If you really want to go that way (be aware, madness lies at its end), you can handle that and send back the value in $ENV{TERM}. This is only a hand-waving explanation, please figure out the details by yourself. =head2 I set the terminal size as explained above, but if I resize the window, the application does not notice this. You have to catch the signal WINCH ("window size changed"), change the terminal size and propagate the signal to the spawned application: my $exp = Expect->new; $exp->slave->clone_winsize_from(\*STDIN); $exp->spawn("ssh somehost); $SIG{WINCH} = \&winch; sub winch { $exp->slave->clone_winsize_from(\*STDIN); kill WINCH => $exp->pid if $exp->pid; $SIG{WINCH} = \&winch; } $exp->interact(); There is an example file ssh.pl in the examples/ subdir that shows how this works with ssh. Please note that I do strongly object against using Expect to automate ssh login, as there are better way to do that (see L). =head2 I noticed that the test uses a string that resembles, but not exactly matches, a well-known sentence that contains every character. What does that mean? That means you are anal-retentive. :-) [Gotcha there!] =head2 I get a "Could not assign a pty" error when running as a non-root user on an IRIX box? The OS may not be configured to grant additional pty's (pseudo terminals) to non-root users. /usr/sbin/mkpts should be 4755, not 700 for this to work. I don't know about security implications if you do this. =head2 How come I don't notice when the spawned process closes its stdin/out/err?? You are probably on one of the systems where the master doesn't get an EOF when the slave closes stdin/out/err. One possible solution is when you spawn a process, follow it with a unique string that would indicate the process is finished. $process = Expect->spawn('telnet somehost; echo ____END____'); And then $process->expect($timeout,'____END____','other','patterns'); =head1 Source Examples =head2 How to automate login my $telnet = Net::Telnet->new("remotehost") # see Net::Telnet or die "Cannot telnet to remotehost: $!\n";; my $exp = Expect->exp_init($telnet); # deprecated use of spawned telnet command # my $exp = Expect->spawn("telnet localhost") # or die "Cannot spawn telnet: $!\n";; my $spawn_ok; $exp->expect($timeout, [ qr'login: $', sub { $spawn_ok = 1; my $fh = shift; $fh->send("$username\n"); exp_continue; } ], [ 'Password: $', sub { my $fh = shift; print $fh "$password\n"; exp_continue; } ], [ eof => sub { if ($spawn_ok) { die "ERROR: premature EOF in login.\n"; } else { die "ERROR: could not spawn telnet.\n"; } } ], [ timeout => sub { die "No login.\n"; } ], '-re', qr'[#>:] $', #' wait for shell prompt, then exit expect ); =head2 How to expect on multiple spawned commands foreach my $cmd (@list_of_commands) { push @commands, Expect->spawn($cmd); } expect($timeout, '-i', \@commands, [ qr"pattern", # find this pattern in output of all commands sub { my $obj = shift; # object that matched print $obj "something\n"; exp_continue; # we don't want to terminate the expect call } ], '-i', $some_other_command, [ "some other pattern", sub { my ($obj, $parmref) = @_; # ... # now we exit the expect command }, \$parm ], ); =head2 How to propagate terminal sizes my $exp = Expect->new; $exp->slave->clone_winsize_from(\*STDIN); $exp->spawn("ssh somehost); $SIG{WINCH} = \&winch; sub winch { $exp->slave->clone_winsize_from(\*STDIN); kill WINCH => $exp->pid if $exp->pid; $SIG{WINCH} = \&winch; } $exp->interact(); =head1 HOMEPAGE L though the source code is now in GitHub: L =head1 MAILING LISTS There are two mailing lists available, expectperl-announce and expectperl-discuss, at http://lists.sourceforge.net/lists/listinfo/expectperl-announce and http://lists.sourceforge.net/lists/listinfo/expectperl-discuss =head1 BUG TRACKING You can use the CPAN Request Tracker http://rt.cpan.org/ and submit new bugs under http://rt.cpan.org/Ticket/Create.html?Queue=Expect =head1 AUTHORS (c) 1997 Austin Schutz EFE (retired) expect() interface & functionality enhancements (c) 1999-2006 Roland Giersig. This module is now maintained by Dave Jacoby EFE =head1 LICENSE This module can be used under the same terms as Perl. =head1 DISCLAIMER THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. In other words: Use at your own risk. Provided as is. Your mileage may vary. Read the source, Luke! And finally, just to be sure: Any Use of This Product, in Any Manner Whatsoever, Will Increase the Amount of Disorder in the Universe. Although No Liability Is Implied Herein, the Consumer Is Warned That This Process Will Ultimately Lead to the Heat Death of the Universe. =cut PK!´~ò " "perl5/Parse/CPAN/Meta.pmnuÏÃ6Ç$use 5.008001; use strict; package Parse::CPAN::Meta; # ABSTRACT: Parse META.yml and META.json CPAN metadata files our $VERSION = '1.4414'; # VERSION use Exporter; use Carp 'croak'; our @ISA = qw/Exporter/; our @EXPORT_OK = qw/Load LoadFile/; sub load_file { my ($class, $filename) = @_; my $meta = _slurp($filename); if ($filename =~ /\.ya?ml$/) { return $class->load_yaml_string($meta); } elsif ($filename =~ /\.json$/) { return $class->load_json_string($meta); } else { $class->load_string($meta); # try to detect yaml/json } } sub load_string { my ($class, $string) = @_; if ( $string =~ /^---/ ) { # looks like YAML return $class->load_yaml_string($string); } elsif ( $string =~ /^\s*\{/ ) { # looks like JSON return $class->load_json_string($string); } else { # maybe doc-marker-free YAML return $class->load_yaml_string($string); } } sub load_yaml_string { my ($class, $string) = @_; my $backend = $class->yaml_backend(); my $data = eval { no strict 'refs'; &{"$backend\::Load"}($string) }; croak $@ if $@; return $data || {}; # in case document was valid but empty } sub load_json_string { my ($class, $string) = @_; my $data = eval { $class->json_backend()->new->decode($string) }; croak $@ if $@; return $data || {}; } sub yaml_backend { if (! defined $ENV{PERL_YAML_BACKEND} ) { _can_load( 'CPAN::Meta::YAML', 0.011 ) or croak "CPAN::Meta::YAML 0.011 is not available\n"; return "CPAN::Meta::YAML"; } else { my $backend = $ENV{PERL_YAML_BACKEND}; _can_load( $backend ) or croak "Could not load PERL_YAML_BACKEND '$backend'\n"; $backend->can("Load") or croak "PERL_YAML_BACKEND '$backend' does not implement Load()\n"; return $backend; } } sub json_backend { if (! $ENV{PERL_JSON_BACKEND} or $ENV{PERL_JSON_BACKEND} eq 'JSON::PP') { _can_load( 'JSON::PP' => 2.27103 ) or croak "JSON::PP 2.27103 is not available\n"; return 'JSON::PP'; } else { _can_load( 'JSON' => 2.5 ) or croak "JSON 2.5 is required for " . "\$ENV{PERL_JSON_BACKEND} = '$ENV{PERL_JSON_BACKEND}'\n"; return "JSON"; } } sub _slurp { require Encode; open my $fh, "<:raw", "$_[0]" ## no critic or die "can't open $_[0] for reading: $!"; my $content = do { local $/; <$fh> }; $content = Encode::decode('UTF-8', $content, Encode::PERLQQ()); return $content; } sub _can_load { my ($module, $version) = @_; (my $file = $module) =~ s{::}{/}g; $file .= ".pm"; return 1 if $INC{$file}; return 0 if exists $INC{$file}; # prior load failed eval { require $file; 1 } or return 0; if ( defined $version ) { eval { $module->VERSION($version); 1 } or return 0; } return 1; } # Kept for backwards compatibility only # Create an object from a file sub LoadFile ($) { return Load(_slurp(shift)); } # Parse a document from a string. sub Load ($) { require CPAN::Meta::YAML; my $object = eval { CPAN::Meta::YAML::Load(shift) }; croak $@ if $@; return $object; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Parse::CPAN::Meta - Parse META.yml and META.json CPAN metadata files =head1 VERSION version 1.4414 =head1 SYNOPSIS ############################################# # In your file --- name: My-Distribution version: 1.23 resources: homepage: "http://example.com/dist/My-Distribution" ############################################# # In your program use Parse::CPAN::Meta; my $distmeta = Parse::CPAN::Meta->load_file('META.yml'); # Reading properties my $name = $distmeta->{name}; my $version = $distmeta->{version}; my $homepage = $distmeta->{resources}{homepage}; =head1 DESCRIPTION B is a parser for F and F files, using L and/or L. B provides three methods: C, C, and C. These will read and deserialize CPAN metafiles, and are described below in detail. B provides a legacy API of only two functions, based on the YAML functions of the same name. Wherever possible, identical calling semantics are used. These may only be used with YAML sources. All error reporting is done with exceptions (die'ing). Note that META files are expected to be in UTF-8 encoding, only. When converted string data, it must first be decoded from UTF-8. =begin Pod::Coverage =end Pod::Coverage =head1 METHODS =head2 load_file my $metadata_structure = Parse::CPAN::Meta->load_file('META.json'); my $metadata_structure = Parse::CPAN::Meta->load_file('META.yml'); This method will read the named file and deserialize it to a data structure, determining whether it should be JSON or YAML based on the filename. The file will be read using the ":utf8" IO layer. =head2 load_yaml_string my $metadata_structure = Parse::CPAN::Meta->load_yaml_string($yaml_string); This method deserializes the given string of YAML and returns the first document in it. (CPAN metadata files should always have only one document.) If the source was UTF-8 encoded, the string must be decoded before calling C. =head2 load_json_string my $metadata_structure = Parse::CPAN::Meta->load_json_string($json_string); This method deserializes the given string of JSON and the result. If the source was UTF-8 encoded, the string must be decoded before calling C. =head2 load_string my $metadata_structure = Parse::CPAN::Meta->load_string($some_string); If you don't know whether a string contains YAML or JSON data, this method will use some heuristics and guess. If it can't tell, it assumes YAML. =head2 yaml_backend my $backend = Parse::CPAN::Meta->yaml_backend; Returns the module name of the YAML serializer. See L for details. =head2 json_backend my $backend = Parse::CPAN::Meta->json_backend; Returns the module name of the JSON serializer. This will either be L or L. Even if C is set, this will return L as further delegation is handled by the L module. See L for details. =head1 FUNCTIONS For maintenance clarity, no functions are exported by default. These functions are available for backwards compatibility only and are best avoided in favor of C. =head2 Load my @yaml = Parse::CPAN::Meta::Load( $string ); Parses a string containing a valid YAML stream into a list of Perl data structures. =head2 LoadFile my @yaml = Parse::CPAN::Meta::LoadFile( 'META.yml' ); Reads the YAML stream from a file instead of a string. =head1 ENVIRONMENT =head2 PERL_JSON_BACKEND By default, L will be used for deserializing JSON data. If the C environment variable exists, is true and is not "JSON::PP", then the L module (version 2.5 or greater) will be loaded and used to interpret C. If L is not installed or is too old, an exception will be thrown. =head2 PERL_YAML_BACKEND By default, L will be used for deserializing YAML data. If the C environment variable is defined, then it is interpreted as a module to use for deserialization. The given module must be installed, must load correctly and must implement the C function or an exception will be thrown. =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone https://github.com/Perl-Toolchain-Gang/Parse-CPAN-Meta.git =head1 AUTHORS =over 4 =item * Adam Kennedy =item * David Golden =back =head1 CONTRIBUTORS =over 4 =item * Graham Knop =item * Joshua ben Jore =item * Neil Bowers =item * Ricardo Signes =item * Steffen Mueller =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014 by Adam Kennedy and Contributors. 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 PK!ÏsIµCµCperl5/Net/HTTP/Methods.pmnuÏÃ6Ç$package Net::HTTP::Methods; our $VERSION = '6.19'; use strict; use warnings; use URI; my $CRLF = "\015\012"; # "\r\n" is not portable *_bytes = defined(&utf8::downgrade) ? sub { unless (utf8::downgrade($_[0], 1)) { require Carp; Carp::croak("Wide character in HTTP request (bytes required)"); } return $_[0]; } : sub { return $_[0]; }; sub new { my $class = shift; unshift(@_, "Host") if @_ == 1; my %cnf = @_; require Symbol; my $self = bless Symbol::gensym(), $class; return $self->http_configure(\%cnf); } sub http_configure { my($self, $cnf) = @_; die "Listen option not allowed" if $cnf->{Listen}; my $explicit_host = (exists $cnf->{Host}); my $host = delete $cnf->{Host}; my $peer = $cnf->{PeerAddr} || $cnf->{PeerHost}; if (!$peer) { die "No Host option provided" unless $host; $cnf->{PeerAddr} = $peer = $host; } # CONNECTIONS # PREFER: port number from PeerAddr, then PeerPort, then http_default_port my $peer_uri = URI->new("http://$peer"); $cnf->{"PeerPort"} = $peer_uri->_port || $cnf->{PeerPort} || $self->http_default_port; $cnf->{"PeerAddr"} = $peer_uri->host; # HOST header: # If specified but blank, ignore. # If specified with a value, add the port number # If not specified, set to PeerAddr and port number # ALWAYS: If IPv6 address, use [brackets] (thanks to the URI package) # ALWAYS: omit port number if http_default_port if (($host) || (! $explicit_host)) { my $uri = ($explicit_host) ? URI->new("http://$host") : $peer_uri->clone; if (!$uri->_port) { # Always use *our* $self->http_default_port instead of URI's (Covers HTTP, HTTPS) $uri->port( $cnf->{PeerPort} || $self->http_default_port); } my $host_port = $uri->host_port; # Returns host:port or [ipv6]:port my $remove = ":" . $self->http_default_port; # we want to remove the default port number if (substr($host_port,0-length($remove)) eq $remove) { substr($host_port,0-length($remove)) = ""; } $host = $host_port; } $cnf->{Proto} = 'tcp'; my $keep_alive = delete $cnf->{KeepAlive}; my $http_version = delete $cnf->{HTTPVersion}; $http_version = "1.1" unless defined $http_version; my $peer_http_version = delete $cnf->{PeerHTTPVersion}; $peer_http_version = "1.0" unless defined $peer_http_version; my $send_te = delete $cnf->{SendTE}; my $max_line_length = delete $cnf->{MaxLineLength}; $max_line_length = 8*1024 unless defined $max_line_length; my $max_header_lines = delete $cnf->{MaxHeaderLines}; $max_header_lines = 128 unless defined $max_header_lines; return undef unless $self->http_connect($cnf); $self->host($host); $self->keep_alive($keep_alive); $self->send_te($send_te); $self->http_version($http_version); $self->peer_http_version($peer_http_version); $self->max_line_length($max_line_length); $self->max_header_lines($max_header_lines); ${*$self}{'http_buf'} = ""; return $self; } sub http_default_port { 80; } # set up property accessors for my $method (qw(host keep_alive send_te max_line_length max_header_lines peer_http_version)) { my $prop_name = "http_" . $method; no strict 'refs'; *$method = sub { my $self = shift; my $old = ${*$self}{$prop_name}; ${*$self}{$prop_name} = shift if @_; return $old; }; } # we want this one to be a bit smarter sub http_version { my $self = shift; my $old = ${*$self}{'http_version'}; if (@_) { my $v = shift; $v = "1.0" if $v eq "1"; # float unless ($v eq "1.0" or $v eq "1.1") { require Carp; Carp::croak("Unsupported HTTP version '$v'"); } ${*$self}{'http_version'} = $v; } $old; } sub format_request { my $self = shift; my $method = shift; my $uri = shift; my $content = (@_ % 2) ? pop : ""; for ($method, $uri) { require Carp; Carp::croak("Bad method or uri") if /\s/ || !length; } push(@{${*$self}{'http_request_method'}}, $method); my $ver = ${*$self}{'http_version'}; my $peer_ver = ${*$self}{'http_peer_http_version'} || "1.0"; my @h; my @connection; my %given = (host => 0, "content-length" => 0, "te" => 0); while (@_) { my($k, $v) = splice(@_, 0, 2); my $lc_k = lc($k); if ($lc_k eq "connection") { $v =~ s/^\s+//; $v =~ s/\s+$//; push(@connection, split(/\s*,\s*/, $v)); next; } if (exists $given{$lc_k}) { $given{$lc_k}++; } push(@h, "$k: $v"); } if (length($content) && !$given{'content-length'}) { push(@h, "Content-Length: " . length($content)); } my @h2; if ($given{te}) { push(@connection, "TE") unless grep lc($_) eq "te", @connection; } elsif ($self->send_te && gunzip_ok()) { # gzip is less wanted since the IO::Uncompress::Gunzip interface for # it does not really allow chunked decoding to take place easily. push(@h2, "TE: deflate,gzip;q=0.3"); push(@connection, "TE"); } unless (grep lc($_) eq "close", @connection) { if ($self->keep_alive) { if ($peer_ver eq "1.0") { # from looking at Netscape's headers push(@h2, "Keep-Alive: 300"); unshift(@connection, "Keep-Alive"); } } else { push(@connection, "close") if $ver ge "1.1"; } } push(@h2, "Connection: " . join(", ", @connection)) if @connection; unless ($given{host}) { my $h = ${*$self}{'http_host'}; push(@h2, "Host: $h") if $h; } return _bytes(join($CRLF, "$method $uri HTTP/$ver", @h2, @h, "", $content)); } sub write_request { my $self = shift; $self->print($self->format_request(@_)); } sub format_chunk { my $self = shift; return $_[0] unless defined($_[0]) && length($_[0]); return _bytes(sprintf("%x", length($_[0])) . $CRLF . $_[0] . $CRLF); } sub write_chunk { my $self = shift; return 1 unless defined($_[0]) && length($_[0]); $self->print(_bytes(sprintf("%x", length($_[0])) . $CRLF . $_[0] . $CRLF)); } sub format_chunk_eof { my $self = shift; my @h; while (@_) { push(@h, sprintf "%s: %s$CRLF", splice(@_, 0, 2)); } return _bytes(join("", "0$CRLF", @h, $CRLF)); } sub write_chunk_eof { my $self = shift; $self->print($self->format_chunk_eof(@_)); } sub my_read { die if @_ > 3; my $self = shift; my $len = $_[1]; for (${*$self}{'http_buf'}) { if (length) { $_[0] = substr($_, 0, $len, ""); return length($_[0]); } else { die "read timeout" unless $self->can_read; return $self->sysread($_[0], $len); } } } sub my_readline { my $self = shift; my $what = shift; for (${*$self}{'http_buf'}) { my $max_line_length = ${*$self}{'http_max_line_length'}; my $pos; while (1) { # find line ending $pos = index($_, "\012"); last if $pos >= 0; die "$what line too long (limit is $max_line_length)" if $max_line_length && length($_) > $max_line_length; # need to read more data to find a line ending my $new_bytes = 0; READ: { # wait until bytes start arriving $self->can_read or die "read timeout"; # consume all incoming bytes my $bytes_read = $self->sysread($_, 1024, length); if(defined $bytes_read) { $new_bytes += $bytes_read; } elsif($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) { redo READ; } else { # if we have already accumulated some data let's at # least return that as a line length or die "$what read failed: $!"; } # no line-ending, no new bytes return length($_) ? substr($_, 0, length($_), "") : undef if $new_bytes==0; } } die "$what line too long ($pos; limit is $max_line_length)" if $max_line_length && $pos > $max_line_length; my $line = substr($_, 0, $pos+1, ""); $line =~ s/(\015?\012)\z// || die "Assert"; return wantarray ? ($line, $1) : $line; } } sub can_read { my $self = shift; return 1 unless defined(fileno($self)); return 1 if $self->isa('IO::Socket::SSL') && $self->pending; return 1 if $self->isa('Net::SSL') && $self->can('pending') && $self->pending; # With no timeout, wait forever. An explicit timeout of 0 can be # used to just check if the socket is readable without waiting. my $timeout = @_ ? shift : (${*$self}{io_socket_timeout} || undef); my $fbits = ''; vec($fbits, fileno($self), 1) = 1; SELECT: { my $before; $before = time if $timeout; my $nfound = select($fbits, undef, undef, $timeout); if ($nfound < 0) { if ($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) { # don't really think EAGAIN/EWOULDBLOCK can happen here if ($timeout) { $timeout -= time - $before; $timeout = 0 if $timeout < 0; } redo SELECT; } die "select failed: $!"; } return $nfound > 0; } } sub _rbuf { my $self = shift; if (@_) { for (${*$self}{'http_buf'}) { my $old; $old = $_ if defined wantarray; $_ = shift; return $old; } } else { return ${*$self}{'http_buf'}; } } sub _rbuf_length { my $self = shift; return length ${*$self}{'http_buf'}; } sub _read_header_lines { my $self = shift; my $junk_out = shift; my @headers; my $line_count = 0; my $max_header_lines = ${*$self}{'http_max_header_lines'}; while (my $line = my_readline($self, 'Header')) { if ($line =~ /^(\S+?)\s*:\s*(.*)/s) { push(@headers, $1, $2); } elsif (@headers && $line =~ s/^\s+//) { $headers[-1] .= " " . $line; } elsif ($junk_out) { push(@$junk_out, $line); } else { die "Bad header: '$line'\n"; } if ($max_header_lines) { $line_count++; if ($line_count >= $max_header_lines) { die "Too many header lines (limit is $max_header_lines)"; } } } return @headers; } sub read_response_headers { my($self, %opt) = @_; my $laxed = $opt{laxed}; my($status, $eol) = my_readline($self, 'Status'); unless (defined $status) { die "Server closed connection without sending any data back"; } my($peer_ver, $code, $message) = split(/\s+/, $status, 3); if (!$peer_ver || $peer_ver !~ s,^HTTP/,, || $code !~ /^[1-5]\d\d$/) { die "Bad response status line: '$status'" unless $laxed; # assume HTTP/0.9 ${*$self}{'http_peer_http_version'} = "0.9"; ${*$self}{'http_status'} = "200"; substr(${*$self}{'http_buf'}, 0, 0) = $status . ($eol || ""); return 200 unless wantarray; return (200, "Assumed OK"); }; ${*$self}{'http_peer_http_version'} = $peer_ver; ${*$self}{'http_status'} = $code; my $junk_out; if ($laxed) { $junk_out = $opt{junk_out} || []; } my @headers = $self->_read_header_lines($junk_out); # pick out headers that read_entity_body might need my @te; my $content_length; for (my $i = 0; $i < @headers; $i += 2) { my $h = lc($headers[$i]); if ($h eq 'transfer-encoding') { my $te = $headers[$i+1]; $te =~ s/^\s+//; $te =~ s/\s+$//; push(@te, $te) if length($te); } elsif ($h eq 'content-length') { # ignore bogus and overflow values if ($headers[$i+1] =~ /^\s*(\d{1,15})(?:\s|$)/) { $content_length = $1; } } } ${*$self}{'http_te'} = join(",", @te); ${*$self}{'http_content_length'} = $content_length; ${*$self}{'http_first_body'}++; delete ${*$self}{'http_trailers'}; return $code unless wantarray; return ($code, $message, @headers); } sub read_entity_body { my $self = shift; my $buf_ref = \$_[0]; my $size = $_[1]; die "Offset not supported yet" if $_[2]; my $chunked; my $bytes; if (${*$self}{'http_first_body'}) { ${*$self}{'http_first_body'} = 0; delete ${*$self}{'http_chunked'}; delete ${*$self}{'http_bytes'}; my $method = shift(@{${*$self}{'http_request_method'}}); my $status = ${*$self}{'http_status'}; if ($method eq "HEAD") { # this response is always empty regardless of other headers $bytes = 0; } elsif (my $te = ${*$self}{'http_te'}) { my @te = split(/\s*,\s*/, lc($te)); die "Chunked must be last Transfer-Encoding '$te'" unless pop(@te) eq "chunked"; pop(@te) while @te && $te[-1] eq "chunked"; # ignore repeated chunked spec for (@te) { if ($_ eq "deflate" && inflate_ok()) { #require Compress::Raw::Zlib; my ($i, $status) = Compress::Raw::Zlib::Inflate->new(); die "Can't make inflator: $status" unless $i; $_ = sub { my $out; $i->inflate($_[0], \$out); $out } } elsif ($_ eq "gzip" && gunzip_ok()) { #require IO::Uncompress::Gunzip; my @buf; $_ = sub { push(@buf, $_[0]); return "" unless $_[1]; my $input = join("", @buf); my $output; IO::Uncompress::Gunzip::gunzip(\$input, \$output, Transparent => 0) or die "Can't gunzip content: $IO::Uncompress::Gunzip::GunzipError"; return \$output; }; } elsif ($_ eq "identity") { $_ = sub { $_[0] }; } else { die "Can't handle transfer encoding '$te'"; } } @te = reverse(@te); ${*$self}{'http_te2'} = @te ? \@te : ""; $chunked = -1; } elsif (defined(my $content_length = ${*$self}{'http_content_length'})) { $bytes = $content_length; } elsif ($status =~ /^(?:1|[23]04)/) { # RFC 2616 says that these responses should always be empty # but that does not appear to be true in practice [RT#17907] $bytes = 0; } else { # XXX Multi-Part types are self delimiting, but RFC 2616 says we # only has to deal with 'multipart/byteranges' # Read until EOF } } else { $chunked = ${*$self}{'http_chunked'}; $bytes = ${*$self}{'http_bytes'}; } if (defined $chunked) { # The state encoded in $chunked is: # $chunked == 0: read CRLF after chunk, then chunk header # $chunked == -1: read chunk header # $chunked > 0: bytes left in current chunk to read if ($chunked <= 0) { my $line = my_readline($self, 'Entity body'); if ($chunked == 0) { die "Missing newline after chunk data: '$line'" if !defined($line) || $line ne ""; $line = my_readline($self, 'Entity body'); } die "EOF when chunk header expected" unless defined($line); my $chunk_len = $line; $chunk_len =~ s/;.*//; # ignore potential chunk parameters unless ($chunk_len =~ /^([\da-fA-F]+)\s*$/) { die "Bad chunk-size in HTTP response: $line"; } $chunked = hex($1); ${*$self}{'http_chunked'} = $chunked; if ($chunked == 0) { ${*$self}{'http_trailers'} = [$self->_read_header_lines]; $$buf_ref = ""; my $n = 0; if (my $transforms = delete ${*$self}{'http_te2'}) { for (@$transforms) { $$buf_ref = &$_($$buf_ref, 1); } $n = length($$buf_ref); } # in case somebody tries to read more, make sure we continue # to return EOF delete ${*$self}{'http_chunked'}; ${*$self}{'http_bytes'} = 0; return $n; } } my $n = $chunked; $n = $size if $size && $size < $n; $n = my_read($self, $$buf_ref, $n); return undef unless defined $n; ${*$self}{'http_chunked'} = $chunked - $n; if ($n > 0) { if (my $transforms = ${*$self}{'http_te2'}) { for (@$transforms) { $$buf_ref = &$_($$buf_ref, 0); } $n = length($$buf_ref); $n = -1 if $n == 0; } } return $n; } elsif (defined $bytes) { unless ($bytes) { $$buf_ref = ""; return 0; } my $n = $bytes; $n = $size if $size && $size < $n; $n = my_read($self, $$buf_ref, $n); ${*$self}{'http_bytes'} = defined $n ? $bytes - $n : $bytes; return $n; } else { # read until eof $size ||= 8*1024; return my_read($self, $$buf_ref, $size); } } sub get_trailers { my $self = shift; @{${*$self}{'http_trailers'} || []}; } BEGIN { my $gunzip_ok; my $inflate_ok; sub gunzip_ok { return $gunzip_ok if defined $gunzip_ok; # Try to load IO::Uncompress::Gunzip. local $@; local $SIG{__DIE__}; $gunzip_ok = 0; eval { require IO::Uncompress::Gunzip; $gunzip_ok++; }; return $gunzip_ok; } sub inflate_ok { return $inflate_ok if defined $inflate_ok; # Try to load Compress::Raw::Zlib. local $@; local $SIG{__DIE__}; $inflate_ok = 0; eval { require Compress::Raw::Zlib; $inflate_ok++; }; return $inflate_ok; } } # BEGIN 1; =pod =encoding UTF-8 =head1 NAME Net::HTTP::Methods - Methods shared by Net::HTTP and Net::HTTPS =head1 VERSION version 6.19 =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2001-2017 by Gisle Aas. 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 __END__ # ABSTRACT: Methods shared by Net::HTTP and Net::HTTPS PK!ç´ cÙ Ù perl5/Net/HTTP/NB.pmnuÏÃ6Ç$package Net::HTTP::NB; our $VERSION = '6.19'; use strict; use warnings; use base 'Net::HTTP'; sub can_read { return 1; } sub sysread { my $self = $_[0]; if (${*$self}{'httpnb_read_count'}++) { ${*$self}{'http_buf'} = ${*$self}{'httpnb_save'}; die "Multi-read\n"; } my $buf; my $offset = $_[3] || 0; my $n = sysread($self, $_[1], $_[2], $offset); ${*$self}{'httpnb_save'} .= substr($_[1], $offset); return $n; } sub read_response_headers { my $self = shift; ${*$self}{'httpnb_read_count'} = 0; ${*$self}{'httpnb_save'} = ${*$self}{'http_buf'}; my @h = eval { $self->SUPER::read_response_headers(@_) }; if ($@) { return if $@ eq "Multi-read\n"; die; } return @h; } sub read_entity_body { my $self = shift; ${*$self}{'httpnb_read_count'} = 0; ${*$self}{'httpnb_save'} = ${*$self}{'http_buf'}; # XXX I'm not so sure this does the correct thing in case of # transfer-encoding transforms my $n = eval { $self->SUPER::read_entity_body(@_); }; if ($@) { $_[0] = ""; return -1; } return $n; } 1; =pod =encoding UTF-8 =head1 NAME Net::HTTP::NB - Non-blocking HTTP client =head1 VERSION version 6.19 =head1 SYNOPSIS use Net::HTTP::NB; my $s = Net::HTTP::NB->new(Host => "www.perl.com") || die $@; $s->write_request(GET => "/"); use IO::Select; my $sel = IO::Select->new($s); READ_HEADER: { die "Header timeout" unless $sel->can_read(10); my($code, $mess, %h) = $s->read_response_headers; redo READ_HEADER unless $code; } while (1) { die "Body timeout" unless $sel->can_read(10); my $buf; my $n = $s->read_entity_body($buf, 1024); last unless $n; print $buf; } =head1 DESCRIPTION Same interface as C but it will never try multiple reads when the read_response_headers() or read_entity_body() methods are invoked. This make it possible to multiplex multiple Net::HTTP::NB using select without risk blocking. If read_response_headers() did not see enough data to complete the headers an empty list is returned. If read_entity_body() did not see new entity data in its read the value -1 is returned. =head1 SEE ALSO L =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2001-2017 by Gisle Aas. 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 __END__ #ABSTRACT: Non-blocking HTTP client PK!¿Y±fž'ž'perl5/Net/HTTP.pmnuÏÃ6Ç$package Net::HTTP; our $VERSION = '6.19'; use strict; use warnings; use vars qw($SOCKET_CLASS); unless ($SOCKET_CLASS) { # Try several, in order of capability and preference if (eval { require IO::Socket::IP }) { $SOCKET_CLASS = "IO::Socket::IP"; # IPv4+IPv6 } elsif (eval { require IO::Socket::INET6 }) { $SOCKET_CLASS = "IO::Socket::INET6"; # IPv4+IPv6 } elsif (eval { require IO::Socket::INET }) { $SOCKET_CLASS = "IO::Socket::INET"; # IPv4 only } else { require IO::Socket; $SOCKET_CLASS = "IO::Socket::INET"; } } require Net::HTTP::Methods; require Carp; our @ISA = ($SOCKET_CLASS, 'Net::HTTP::Methods'); sub new { my $class = shift; Carp::croak("No Host option provided") unless @_; $class->SUPER::new(@_); } sub configure { my($self, $cnf) = @_; $self->http_configure($cnf); } sub http_connect { my($self, $cnf) = @_; $self->SUPER::configure($cnf); } 1; =pod =encoding UTF-8 =head1 NAME Net::HTTP - Low-level HTTP connection (client) =head1 VERSION version 6.19 =head1 SYNOPSIS use Net::HTTP; my $s = Net::HTTP->new(Host => "www.perl.com") || die $@; $s->write_request(GET => "/", 'User-Agent' => "Mozilla/5.0"); my($code, $mess, %h) = $s->read_response_headers; while (1) { my $buf; my $n = $s->read_entity_body($buf, 1024); die "read failed: $!" unless defined $n; last unless $n; print $buf; } =head1 DESCRIPTION The C class is a low-level HTTP client. An instance of the C class represents a connection to an HTTP server. The HTTP protocol is described in RFC 2616. The C class supports C and C. C is a sub-class of one of C (IPv6+IPv4), C (IPv6+IPv4), or C (IPv4 only). You can mix the methods described below with reading and writing from the socket directly. This is not necessary a good idea, unless you know what you are doing. The following methods are provided (in addition to those of C): =over =item $s = Net::HTTP->new( %options ) The C constructor method takes the same options as C's as well as these: Host: Initial host attribute value KeepAlive: Initial keep_alive attribute value SendTE: Initial send_te attribute_value HTTPVersion: Initial http_version attribute value PeerHTTPVersion: Initial peer_http_version attribute value MaxLineLength: Initial max_line_length attribute value MaxHeaderLines: Initial max_header_lines attribute value The C option is also the default for C's C. The C defaults to 80 if not provided. The C specification can also be embedded in the C by preceding it with a ":", and closing the IPv6 address on brackets "[]" if necessary: "192.0.2.1:80","[2001:db8::1]:80","any.example.com:80". The C option provided by C's constructor method is not allowed. If unable to connect to the given HTTP server then the constructor returns C and $@ contains the reason. After a successful connect, a C object is returned. =item $s->host Get/set the default value of the C header to send. The $host must not be set to an empty string (or C) for HTTP/1.1. =item $s->keep_alive Get/set the I value. If this value is TRUE then the request will be sent with headers indicating that the server should try to keep the connection open so that multiple requests can be sent. The actual headers set will depend on the value of the C and C attributes. =item $s->send_te Get/set the a value indicating if the request will be sent with a "TE" header to indicate the transfer encodings that the server can choose to use. The list of encodings announced as accepted by this client depends on availability of the following modules: C for I, and C for I. =item $s->http_version Get/set the HTTP version number that this client should announce. This value can only be set to "1.0" or "1.1". The default is "1.1". =item $s->peer_http_version Get/set the protocol version number of our peer. This value will initially be "1.0", but will be updated by a successful read_response_headers() method call. =item $s->max_line_length Get/set a limit on the length of response line and response header lines. The default is 8192. A value of 0 means no limit. =item $s->max_header_length Get/set a limit on the number of header lines that a response can have. The default is 128. A value of 0 means no limit. =item $s->format_request($method, $uri, %headers, [$content]) Format a request message and return it as a string. If the headers do not include a C header, then a header is inserted with the value of the C attribute. Headers like C and C might also be added depending on the status of the C attribute. If $content is given (and it is non-empty), then a C header is automatically added unless it was already present. =item $s->write_request($method, $uri, %headers, [$content]) Format and send a request message. Arguments are the same as for format_request(). Returns true if successful. =item $s->format_chunk( $data ) Returns the string to be written for the given chunk of data. =item $s->write_chunk($data) Will write a new chunk of request entity body data. This method should only be used if the C header with a value of C was sent in the request. Note, writing zero-length data is a no-op. Use the write_chunk_eof() method to signal end of entity body data. Returns true if successful. =item $s->format_chunk_eof( %trailers ) Returns the string to be written for signaling EOF when a C of C is used. =item $s->write_chunk_eof( %trailers ) Will write eof marker for chunked data and optional trailers. Note that trailers should not really be used unless is was signaled with a C header. Returns true if successful. =item ($code, $mess, %headers) = $s->read_response_headers( %opts ) Read response headers from server and return it. The $code is the 3 digit HTTP status code (see L) and $mess is the textual message that came with it. Headers are then returned as key/value pairs. Since key letter casing is not normalized and the same key can even occur multiple times, assigning these values directly to a hash is not wise. Only the $code is returned if this method is called in scalar context. As a side effect this method updates the 'peer_http_version' attribute. Options might be passed in as key/value pairs. There are currently only two options supported; C and C. The C option will make read_response_headers() more forgiving towards servers that have not learned how to speak HTTP properly. The C option is a boolean flag, and is enabled by passing in a TRUE value. The C option can be used to capture bad header lines when C is enabled. The value should be an array reference. Bad header lines will be pushed onto the array. The C option must be specified in order to communicate with pre-HTTP/1.0 servers that don't describe the response outcome or the data they send back with a header block. For these servers peer_http_version is set to "0.9" and this method returns (200, "Assumed OK"). The method will raise an exception (die) if the server does not speak proper HTTP or if the C or C limits are reached. If the C option is turned on and C and C checks are turned off, then no exception will be raised and this method will always return a response code. =item $n = $s->read_entity_body($buf, $size); Reads chunks of the entity body content. Basically the same interface as for read() and sysread(), but the buffer offset argument is not supported yet. This method should only be called after a successful read_response_headers() call. The return value will be C on read errors, 0 on EOF, -1 if no data could be returned this time, otherwise the number of bytes assigned to $buf. The $buf is set to "" when the return value is -1. You normally want to retry this call if this function returns either -1 or C with C<$!> as EINTR or EAGAIN (see L). EINTR can happen if the application catches signals and EAGAIN can happen if you made the socket non-blocking. This method will raise exceptions (die) if the server does not speak proper HTTP. This can only happen when reading chunked data. =item %headers = $s->get_trailers After read_entity_body() has returned 0 to indicate end of the entity body, you might call this method to pick up any trailers. =item $s->_rbuf Get/set the read buffer content. The read_response_headers() and read_entity_body() methods use an internal buffer which they will look for data before they actually sysread more from the socket itself. If they read too much, the remaining data will be left in this buffer. =item $s->_rbuf_length Returns the number of bytes in the read buffer. This should always be the same as: length($s->_rbuf) but might be more efficient. =back =head1 SUBCLASSING The read_response_headers() and read_entity_body() will invoke the sysread() method when they need more data. Subclasses might want to override this method to control how reading takes place. The object itself is a glob. Subclasses should avoid using hash key names prefixed with C and C. =head1 SEE ALSO L, L, L =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2001-2017 by Gisle Aas. 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 __END__ # ABSTRACT: Low-level HTTP connection (client) PK! %§´9!9!perl5/Net/IP.pmnuÏÃ6Ç$# Copyright (c) 1999 - 2002 RIPE NCC # # All Rights Reserved # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of the author not be # used in advertising or publicity pertaining to distribution of the # software without specific, written prior permission. # # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL # AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN # AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #------------------------------------------------------------------------------ # Module Header # Filename : IP.pm # Purpose : Provide functions to manipulate IPv4/v6 addresses # Author : Manuel Valente # Date : 19991124 # Description : # Language Version : Perl 5 # OSs Tested : BSDI 3.1 - Linux # Command Line : ipcount # Input Files : # Output Files : # External Programs : Math::BigInt.pm # Problems : # To Do : # Comments : Based on ipv4pack.pm (Monica) and iplib.pm (Lee) # Math::BigInt is only loaded if int functions are used # $Id: IP.pm,v 1.23 2003/02/18 16:13:01 manuel Exp $ #------------------------------------------------------------------------------ package Net::IP; use strict; use Math::BigInt; # Global Variables definition use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $ERROR $ERRNO %IPv4ranges %IPv6ranges $useBigInt $IP_NO_OVERLAP $IP_PARTIAL_OVERLAP $IP_A_IN_B_OVERLAP $IP_B_IN_A_OVERLAP $IP_IDENTICAL); $VERSION = '1.26'; require Exporter; @ISA = qw(Exporter); # Functions and variables exported in all cases @EXPORT = qw(&Error &Errno $IP_NO_OVERLAP $IP_PARTIAL_OVERLAP $IP_A_IN_B_OVERLAP $IP_B_IN_A_OVERLAP $IP_IDENTICAL ); # Functions exported on demand (with :PROC) @EXPORT_OK = qw(&Error &Errno &ip_iptobin &ip_bintoip &ip_bintoint &ip_inttobin &ip_get_version &ip_is_ipv4 &ip_is_ipv6 &ip_expand_address &ip_get_mask &ip_last_address_bin &ip_splitprefix &ip_prefix_to_range &ip_is_valid_mask &ip_bincomp &ip_binadd &ip_get_prefix_length &ip_range_to_prefix &ip_compress_address &ip_is_overlap &ip_get_embedded_ipv4 &ip_aggregate &ip_iptype &ip_check_prefix &ip_reverse &ip_normalize &ip_normal_range &ip_iplengths $IP_NO_OVERLAP $IP_PARTIAL_OVERLAP $IP_A_IN_B_OVERLAP $IP_B_IN_A_OVERLAP $IP_IDENTICAL ); %EXPORT_TAGS = (PROC => [@EXPORT_OK],); # Definition of the Ranges for IPv4 IPs %IPv4ranges = ( '00000000' => 'PRIVATE', # 0/8 '00001010' => 'PRIVATE', # 10/8 '0110010001' => 'SHARED', # 100.64/10 '01111111' => 'LOOPBACK', # 127.0/8 '1010100111111110' => 'LINK-LOCAL', # 169.254/16 '101011000001' => 'PRIVATE', # 172.16/12 '110000000000000000000000' => 'RESERVED', # 192.0.0/24 '110000000000000000000010' => 'TEST-NET', # 192.0.2/24 '110000000101100001100011' => '6TO4-RELAY', # 192.88.99.0/24 '1100000010101000' => 'PRIVATE', # 192.168/16 '110001100001001' => 'RESERVED', # 198.18/15 '110001100011001101100100' => 'TEST-NET', # 198.51.100/24 '110010110000000001110001' => 'TEST-NET', # 203.0.113/24 '1110' => 'MULTICAST', # 224/4 '1111' => 'RESERVED', # 240/4 '11111111111111111111111111111111' => 'BROADCAST', # 255.255.255.255/32 ); # Definition of the Ranges for Ipv6 IPs %IPv6ranges = ( '00000000' => 'RESERVED', # ::/8 ('0' x 128) => 'UNSPECIFIED', # ::/128 ('0' x 127) . '1' => 'LOOPBACK', # ::1/128 ('0' x 80) . ('1' x 16) => 'IPV4MAP', # ::FFFF:0:0/96 '00000001' => 'RESERVED', # 0100::/8 '0000000100000000' . ('0' x 48) => 'DISCARD', # 0100::/64 '0000001' => 'RESERVED', # 0200::/7 '000001' => 'RESERVED', # 0400::/6 '00001' => 'RESERVED', # 0800::/5 '0001' => 'RESERVED', # 1000::/4 '001' => 'GLOBAL-UNICAST', # 2000::/3 '0010000000000001' . ('0' x 16) => 'TEREDO', # 2001::/32 '00100000000000010000000000000010' . ('0' x 16) => 'BMWG', # 2001:0002::/48 '00100000000000010000110110111000' => 'DOCUMENTATION', # 2001:DB8::/32 '0010000000000001000000000001' => 'ORCHID', # 2001:10::/28 '0010000000000010' => '6TO4', # 2002::/16 '010' => 'RESERVED', # 4000::/3 '011' => 'RESERVED', # 6000::/3 '100' => 'RESERVED', # 8000::/3 '101' => 'RESERVED', # A000::/3 '110' => 'RESERVED', # C000::/3 '1110' => 'RESERVED', # E000::/4 '11110' => 'RESERVED', # F000::/5 '111110' => 'RESERVED', # F800::/6 '1111110' => 'UNIQUE-LOCAL-UNICAST', # FC00::/7 '111111100' => 'RESERVED', # FE00::/9 '1111111010' => 'LINK-LOCAL-UNICAST', # FE80::/10 '1111111011' => 'RESERVED', # FEC0::/10 '11111111' => 'MULTICAST', # FF00::/8 ); # Overlap constants $IP_NO_OVERLAP = 0; $IP_PARTIAL_OVERLAP = 1; $IP_A_IN_B_OVERLAP = -1; $IP_B_IN_A_OVERLAP = -2; $IP_IDENTICAL = -3; # ---------------------------------------------------------- # OVERLOADING use overload ( '+' => 'ip_add_num', 'bool' => sub { @_ }, ); #------------------------------------------------------------------------------ # Subroutine ip_num_add # Purpose : Add an integer to an IP # Params : Number to add # Returns : New object or undef # Note : Used by overloading - returns undef when # the end of the range is reached sub ip_add_num { my $self = shift; my ($value) = @_; my $ip = $self->intip + $value; my $last = $self->last_int; # Reached the end of the range ? if ($ip > $self->last_int) { return; } my $newb = ip_inttobin($ip, $self->version); $newb = ip_bintoip($newb, $self->version); my $newe = ip_inttobin($last, $self->version); $newe = ip_bintoip($newe, $self->version); my $new = new Net::IP("$newb - $newe"); return ($new); } # ----------------------------------------------------------------------------- #------------------------------------------------------------------------------ # Subroutine new # Purpose : Create an instance of an IP object # Params : Class, IP prefix, IP version # Returns : Object reference or undef # Note : New just allocates a new object - set() does all the work sub new { my ($class, $data, $ipversion) = (@_); # Allocate new object my $self = {}; bless($self, $class); # Pass everything to set() unless ($self->set($data, $ipversion)) { return; } return $self; } #------------------------------------------------------------------------------ # Subroutine set # Purpose : Set the IP for an IP object # Params : Data, IP type # Returns : 1 (success) or undef (failure) sub set { my $self = shift; my ($data, $ipversion) = @_; # Normalize data as received - this should return 2 IPs my ($begin, $end) = ip_normalize($data, $ipversion) or do { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; }; # Those variables are set when the object methods are called # We need to reset everything for ( qw(ipversion errno prefixlen binmask reverse_ip last_ip iptype binip error ip intformat hexformat mask last_bin last_int prefix is_prefix) ) { delete($self->{$_}); } # Determine IP version for this object return unless ($self->{ipversion} = $ipversion || ip_get_version($begin)); # Set begin IP address $self->{ip} = $begin; # Set Binary IP address return unless ($self->{binip} = ip_iptobin($self->ip(), $self->version())); $self->{is_prefix} = 0; # Set end IP address # If single IP: begin and end IPs are identical $end ||= $begin; $self->{last_ip} = $end; # Try to determine the IP version my $ver = ip_get_version($end) || return; # Check if begin and end addresses have the same version if ($ver != $self->version()) { $ERRNO = 201; $ERROR = "Begin and End addresses have different IP versions - $begin - $end"; $self->{errno} = $ERRNO; $self->{error} = $ERROR; return; } # Get last binary address return unless ($self->{last_bin} = ip_iptobin($self->last_ip(), $self->version())); # Check that End IP >= Begin IP unless (ip_bincomp($self->binip(), 'le', $self->last_bin())) { $ERRNO = 202; $ERROR = "Begin address is greater than End address $begin - $end"; $self->{errno} = $ERRNO; $self->{error} = $ERROR; return; } # Find all prefixes (eg:/24) in the current range my @prefixes = $self->find_prefixes() or return; # If there is only one prefix: if (scalar(@prefixes) == 1) { # Get length of prefix return unless ((undef, $self->{prefixlen}) = ip_splitprefix($prefixes[0])); # Set prefix boolean var # This value is 1 if the IP range only contains a single /nn prefix $self->{is_prefix} = 1; } # If the range is a single prefix: if ($self->{is_prefix}) { # Set mask property $self->{binmask} = ip_get_mask($self->prefixlen(), $self->version()); # Check that the mask is valid unless ( ip_check_prefix( $self->binip(), $self->prefixlen(), $self->version() ) ) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } } return ($self); } sub print { my $self = shift; if ($self->{is_prefix}) { return ($self->short() . '/' . $self->prefixlen()); } else { return (sprintf("%s - %s", $self->ip(), $self->last_ip())); } } #------------------------------------------------------------------------------ # Subroutine error # Purpose : Return the current error message # Returns : Error string sub error { my $self = shift; return $self->{error}; } #------------------------------------------------------------------------------ # Subroutine errno # Purpose : Return the current error number # Returns : Error number sub errno { my $self = shift; return $self->{errno}; } #------------------------------------------------------------------------------ # Subroutine binip # Purpose : Return the IP as a binary string # Returns : binary string sub binip { my $self = shift; return $self->{binip}; } #------------------------------------------------------------------------------ # Subroutine prefixlen # Purpose : Get the IP prefix length # Returns : prefix length sub prefixlen { my $self = shift; return $self->{prefixlen}; } #------------------------------------------------------------------------------ # Subroutine version # Purpose : Return the IP version # Returns : IP version sub version { my $self = shift; return $self->{ipversion}; } #------------------------------------------------------------------------------ # Subroutine version # Purpose : Return the IP in quad format # Returns : IP string sub ip { my $self = shift; return $self->{ip}; } #------------------------------------------------------------------------------ # Subroutine is_prefix # Purpose : Check if range of IPs is a prefix # Returns : boolean sub is_prefix { my $self = shift; return $self->{is_prefix}; } #------------------------------------------------------------------------------ # Subroutine binmask # Purpose : Return the binary mask of an IP prefix # Returns : Binary mask (as string) sub binmask { my $self = shift; return $self->{binmask}; } #------------------------------------------------------------------------------ # Subroutine size # Purpose : Return the number of addresses contained in an IP object # Returns : Number of addresses sub size { my $self = shift; my $size = new Math::BigInt($self->last_int); $size->badd(1); $size->bsub($self->intip); } # All the following functions work the same way: the method is just a frontend # to the real function. When the real function is called, the output is cached # so that next time the same function is called,the frontend function directly # returns the result. #------------------------------------------------------------------------------ # Subroutine intip # Purpose : Return the IP in integer format # Returns : Integer sub intip { my $self = shift; return ($self->{intformat}) if defined($self->{intformat}); my $int = ip_bintoint($self->binip()); if (!$int) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{intformat} = $int; return ($int); } #------------------------------------------------------------------------------ # Subroutine hexip # Purpose : Return the IP in hex format # Returns : hex string sub hexip { my $self = shift; return $self->{'hexformat'} if(defined($self->{'hexformat'})); $self->{'hexformat'} = $self->intip->as_hex(); return $self->{'hexformat'}; } #------------------------------------------------------------------------------ # Subroutine hexmask # Purpose : Return the mask back in hex # Returns : hex string sub hexmask { my $self = shift; return $self->{hexmask} if(defined($self->{hexmask})); my $intmask = ip_bintoint($self->binmask); $self->{'hexmask'} = $intmask->as_hex(); return ($self->{'hexmask'}); } #------------------------------------------------------------------------------ # Subroutine prefix # Purpose : Return the Prefix (n.n.n.n/s) # Returns : IP Prefix sub prefix { my $self = shift; if (not $self->is_prefix()) { $self->{error} = "IP range $self->{ip} is not a Prefix."; $self->{errno} = 209; return; } return ($self->{prefix}) if defined($self->{prefix}); my $prefix = $self->ip() . '/' . $self->prefixlen(); if (!$prefix) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{prefix} = $prefix; return ($prefix); } #------------------------------------------------------------------------------ # Subroutine mask # Purpose : Return the IP mask in quad format # Returns : Mask (string) sub mask { my $self = shift; if (not $self->is_prefix()) { $self->{error} = "IP range $self->{ip} is not a Prefix."; $self->{errno} = 209; return; } return ($self->{mask}) if defined($self->{mask}); my $mask = ip_bintoip($self->binmask(), $self->version()); if (!$mask) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{mask} = $mask; return ($mask); } #------------------------------------------------------------------------------ # Subroutine short # Purpose : Get the short format of an IP address or a Prefix # Returns : short format IP or undef sub short { my $self = shift; my $r; if ($self->version == 6) { $r = ip_compress_address($self->ip(), $self->version()); } else { $r = ip_compress_v4_prefix($self->ip(), $self->prefixlen()); } if (!defined($r)) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } return ($r); } #------------------------------------------------------------------------------ # Subroutine iptype # Purpose : Return the type of an IP # Returns : Type or undef (failure) sub iptype { my ($self) = shift; return ($self->{iptype}) if defined($self->{iptype}); my $type = ip_iptype($self->binip(), $self->version()); if (!$type) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{iptype} = $type; return ($type); } #------------------------------------------------------------------------------ # Subroutine reverse_ip # Purpose : Return the Reverse IP # Returns : Reverse IP or undef(failure) sub reverse_ip { my ($self) = shift; if (not $self->is_prefix()) { $self->{error} = "IP range $self->{ip} is not a Prefix."; $self->{errno} = 209; return; } return ($self->{reverse_ip}) if defined($self->{reverse_ip}); my $rev = ip_reverse($self->ip(), $self->prefixlen(), $self->version()); if (!$rev) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{reverse_ip} = $rev; return ($rev); } #------------------------------------------------------------------------------ # Subroutine last_bin # Purpose : Get the last IP of a range in binary format # Returns : Last binary IP or undef (failure) sub last_bin { my ($self) = shift; return ($self->{last_bin}) if defined($self->{last_bin}); my $last; if ($self->is_prefix()) { $last = ip_last_address_bin($self->binip(), $self->prefixlen(), $self->version()); } else { $last = ip_iptobin($self->last_ip(), $self->version()); } if (!$last) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{last_bin} = $last; return ($last); } #------------------------------------------------------------------------------ # Subroutine last_int # Purpose : Get the last IP of a range in integer format # Returns : Last integer IP or undef (failure) sub last_int { my ($self) = shift; return ($self->{last_int}) if defined($self->{last_int}); my $last_bin = $self->last_bin() or return; my $last_int = ip_bintoint($last_bin, $self->version()) or return; $self->{last_int} = $last_int; return ($last_int); } #------------------------------------------------------------------------------ # Subroutine last_ip # Purpose : Get the last IP of a prefix in IP format # Returns : IP or undef (failure) sub last_ip { my ($self) = shift; return ($self->{last_ip}) if defined($self->{last_ip}); my $last = ip_bintoip($self->last_bin(), $self->version()); if (!$last) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{last_ip} = $last; return ($last); } #------------------------------------------------------------------------------ # Subroutine find_prefixes # Purpose : Get all prefixes in the range defined by two IPs # Params : IP # Returns : List of prefixes or undef (failure) sub find_prefixes { my ($self) = @_; my @list = ip_range_to_prefix($self->binip(), $self->last_bin(), $self->version()); if (!scalar(@list)) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } return (@list); } #------------------------------------------------------------------------------ # Subroutine bincomp # Purpose : Compare two IPs # Params : Operation, IP to compare # Returns : 1 (True), 0 (False) or undef (problem) # Comments : Operation can be lt, le, gt, ge sub bincomp { my ($self, $op, $other) = @_; my $a = ip_bincomp($self->binip(), $op, $other->binip()); unless (defined $a) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } return ($a); } #------------------------------------------------------------------------------ # Subroutine binadd # Purpose : Add two IPs # Params : IP to add # Returns : New IP object or undef (failure) sub binadd { my ($self, $other) = @_; my $ip = ip_binadd($self->binip(), $other->binip()); if (!$ip) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } my $new = new Net::IP(ip_bintoip($ip, $self->version())) or return; return ($new); } #------------------------------------------------------------------------------ # Subroutine aggregate # Purpose : Aggregate (append) two IPs # Params : IP to add # Returns : New IP object or undef (failure) sub aggregate { my ($self, $other) = @_; my $r = ip_aggregate( $self->binip(), $self->last_bin(), $other->binip(), $other->last_bin(), $self->version() ); if (!$r) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } return (new Net::IP($r)); } #------------------------------------------------------------------------------ # Subroutine overlaps # Purpose : Check if two prefixes overlap # Params : Prefix to compare # Returns : $NO_OVERLAP (no overlap) # $IP_PARTIAL_OVERLAP (overlap) # $IP_A_IN_B_OVERLAP (range1 is included in range2) # $IP_B_IN_A_OVERLAP (range2 is included in range1) # $IP_IDENTICAL (range1 == range2) # or undef (problem) sub overlaps { my ($self, $other) = @_; my $r = ip_is_overlap( $self->binip(), $self->last_bin(), $other->binip(), $other->last_bin() ); if (!defined($r)) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } return ($r); } #------------------------------------------------------------------------------ # Subroutine auth # Purpose : Return Authority information from IP::Authority # Params : IP object # Returns : Authority Source sub auth { my ($self) = shift; return ($self->{auth}) if defined($self->{auth}); my $auth = ip_auth($self->ip, $self->version); if (!$auth) { $self->{error} = $ERROR; $self->{errno} = $ERRNO; return; } $self->{auth} = $auth; return ($self->{auth}); } #------------------------------ PROCEDURAL INTERFACE -------------------------- #------------------------------------------------------------------------------ # Subroutine Error # Purpose : Return the ERROR string # Returns : string sub Error { return ($ERROR); } #------------------------------------------------------------------------------ # Subroutine Error # Purpose : Return the ERRNO value # Returns : number sub Errno { return ($ERRNO); } #------------------------------------------------------------------------------ # Subroutine ip_iplengths # Purpose : Get the length in bits of an IP from its version # Params : IP version # Returns : Number of bits sub ip_iplengths { my ($version) = @_; if ($version == 4) { return (32); } elsif ($version == 6) { return (128); } else { return; } } #------------------------------------------------------------------------------ # Subroutine ip_iptobin # Purpose : Transform an IP address into a bit string # Params : IP address, IP version # Returns : bit string on success, undef otherwise sub ip_iptobin { my ($ip, $ipversion) = @_; # v4 -> return 32-bit array if ($ipversion == 4) { return unpack('B32', pack('C4C4C4C4', split(/\./, $ip))); } # Strip ':' $ip =~ s/://g; # Check size unless (length($ip) == 32) { $ERROR = "Bad IP address $ip"; $ERRNO = 102; return; } # v6 -> return 128-bit array return unpack('B128', pack('H32', $ip)); } #------------------------------------------------------------------------------ # Subroutine ip_bintoip # Purpose : Transform a bit string into an IP address # Params : bit string, IP version # Returns : IP address on success, undef otherwise sub ip_bintoip { my ($binip, $ip_version) = @_; # Define normal size for address my $len = ip_iplengths($ip_version); if ($len < length($binip)) { $ERROR = "Invalid IP length for binary IP $binip\n"; $ERRNO = 189; return; } # Prepend 0s if address is less than normal size $binip = '0' x ($len - length($binip)) . $binip; # IPv4 if ($ip_version == 4) { return join '.', unpack('C4C4C4C4', pack('B32', $binip)); } # IPv6 return join(':', unpack('H4H4H4H4H4H4H4H4', pack('B128', $binip))); } #------------------------------------------------------------------------------ # Subroutine ip_bintoint # Purpose : Transform a bit string into an Integer # Params : bit string # Returns : BigInt sub ip_bintoint { my $binip = shift; # $n is the increment, $dec is the returned value my ($n, $dec) = (Math::BigInt->new(1), Math::BigInt->new(0)); # Reverse the bit string foreach (reverse(split '', $binip)) { # If the nth bit is 1, add 2**n to $dec $_ and $dec += $n; $n *= 2; } # Strip leading + sign $dec =~ s/^\+//; return $dec; } #------------------------------------------------------------------------------ # Subroutine ip_inttobin # Purpose : Transform a BigInt into a bit string # Comments : sets warnings (-w) off. # This is necessary because Math::BigInt is not compliant # Params : BigInt, IP version # Returns : bit string sub ip_inttobin { my $dec = Math::BigInt->new(shift); # Find IP version my $ip_version = shift; unless ($ip_version) { $ERROR = "Cannot determine IP version for $dec"; $ERRNO = 101; return; } my $binip = $dec->as_bin(); $binip =~ s/^0b//; # Define normal size for address my $len = ip_iplengths($ip_version); # Prepend 0s if result is less than normal size $binip = '0' x ($len - length($binip)) . $binip; return $binip; } #------------------------------------------------------------------------------ # Subroutine ip_get_version # Purpose : Get an IP version # Params : IP address # Returns : 4, 6, 0(don't know) sub ip_get_version { my $ip = shift; # If the address does not contain any ':', maybe it's IPv4 $ip !~ /:/ and ip_is_ipv4($ip) and return '4'; # Is it IPv6 ? ip_is_ipv6($ip) and return '6'; return; } #------------------------------------------------------------------------------ # Subroutine ip_is_ipv4 # Purpose : Check if an IP address is version 4 # Params : IP address # Returns : 1 (yes) or 0 (no) sub ip_is_ipv4 { my $ip = shift; # Check for invalid chars unless ($ip =~ m/^[\d\.]+$/) { $ERROR = "Invalid chars in IP $ip"; $ERRNO = 107; return 0; } if ($ip =~ m/^\./) { $ERROR = "Invalid IP $ip - starts with a dot"; $ERRNO = 103; return 0; } if ($ip =~ m/\.$/) { $ERROR = "Invalid IP $ip - ends with a dot"; $ERRNO = 104; return 0; } # Single Numbers are considered to be IPv4 if ($ip =~ m/^(\d+)$/ and $1 < 256) { return 1 } # Count quads my $n = ($ip =~ tr/\./\./); # IPv4 must have from 1 to 4 quads unless ($n >= 0 and $n < 4) { $ERROR = "Invalid IP address $ip"; $ERRNO = 105; return 0; } # Check for empty quads if ($ip =~ m/\.\./) { $ERROR = "Empty quad in IP address $ip"; $ERRNO = 106; return 0; } foreach (split /\./, $ip) { # Check for invalid quads unless ($_ >= 0 and $_ < 256) { $ERROR = "Invalid quad in IP address $ip - $_"; $ERRNO = 107; return 0; } } return 1; } #------------------------------------------------------------------------------ # Subroutine ip_is_ipv6 # Purpose : Check if an IP address is version 6 # Params : IP address # Returns : 1 (yes) or 0 (no) sub ip_is_ipv6 { my $ip = shift; # Count octets my $n = ($ip =~ tr/:/:/); return 0 unless ($n > 0 and $n < 8); # $k is a counter my $k; foreach (split /:/, $ip) { $k++; # Empty octet ? next if ($_ eq ''); # Normal v6 octet ? next if (/^[a-f\d]{1,4}$/i); # Last octet - is it IPv4 ? if ( ($k == $n + 1) && ip_is_ipv4($_) ) { $n++; # ipv4 is two octets next; } $ERROR = "Invalid IP address $ip"; $ERRNO = 108; return 0; } # Does the IP address start with : ? if ($ip =~ m/^:[^:]/) { $ERROR = "Invalid address $ip (starts with :)"; $ERRNO = 109; return 0; } # Does the IP address finish with : ? if ($ip =~ m/[^:]:$/) { $ERROR = "Invalid address $ip (ends with :)"; $ERRNO = 110; return 0; } # Does the IP address have more than one '::' pattern ? if ($ip =~ s/:(?=:)/:/g > 1) { $ERROR = "Invalid address $ip (More than one :: pattern)"; $ERRNO = 111; return 0; } # number of octets if ($n != 7 && $ip !~ /::/) { $ERROR = "Invalid number of octets $ip"; $ERRNO = 112; return 0; } # valid IPv6 address return 1; } #------------------------------------------------------------------------------ # Subroutine ip_expand_address # Purpose : Expand an address from compact notation # Params : IP address, IP version # Returns : expanded IP address or undef on failure sub ip_expand_address { my ($ip, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version for $ip"; $ERRNO = 101; return; } # v4 : add .0 for missing quads if ($ip_version == 4) { my @quads = split /\./, $ip; # check number of quads if (scalar(@quads) > 4) { $ERROR = "Not a valid IPv address $ip"; $ERRNO = 102; return; } my @clean_quads = (0, 0, 0, 0); foreach my $q (reverse @quads) { #check quad data if ($q !~ m/^\d{1,3}$/) { $ERROR = "Not a valid IPv4 address $ip"; $ERRNO = 102; return; } # build clean ipv4 unshift(@clean_quads, $q + 1 - 1); } return (join '.', @clean_quads[ 0 .. 3 ]); } # Keep track of :: my $num_of_double_colon = ($ip =~ s/::/:!:/g); if ($num_of_double_colon > 1) { $ERROR = "Too many :: in ip"; $ERRNO = 102; return; } # IP as an array my @ip = split /:/, $ip; # Number of octets my $num = scalar(@ip); foreach (0 .. (scalar(@ip) - 1)) { # Embedded IPv4 if ($ip[$_] =~ /\./) { # Expand Ipv4 address # Convert into binary # Convert into hex # Keep the last two octets $ip[$_] = substr( ip_bintoip( ip_iptobin( ip_expand_address($ip[$_], 4), 4), 6), -9); # Has an error occured here ? return unless (defined($ip[$_])); # $num++ because we now have one more octet: # IPv4 address becomes two octets $num++; next; } # Add missing trailing 0s $ip[$_] = ('0' x (4 - length($ip[$_]))) . $ip[$_]; } # Now deal with '::' ('000!') foreach (0 .. (scalar(@ip) - 1)) { # Find the pattern next unless ($ip[$_] eq '000!'); # @empty is the IP address 0 my @empty = map { $_ = '0' x 4 } (0 .. 7); # Replace :: with $num '0000' octets $ip[$_] = join ':', @empty[ 0 .. 8 - $num ]; last; } return (lc(join ':', @ip)); } #------------------------------------------------------------------------------ # Subroutine ip_get_mask # Purpose : Get IP mask from prefix length. # Params : Prefix length, IP version # Returns : Binary Mask sub ip_get_mask { my ($len, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version"; $ERRNO = 101; return; } my $size = ip_iplengths($ip_version); # mask is $len 1s plus the rest as 0s return (('1' x $len) . ('0' x ($size - $len))); } #------------------------------------------------------------------------------ # Subroutine ip_last_address_bin # Purpose : Return the last binary address of a range # Params : First binary IP, prefix length, IP version # Returns : Binary IP sub ip_last_address_bin { my ($binip, $len, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version"; $ERRNO = 101; return; } my $size = ip_iplengths($ip_version); # Find the part of the IP address which will not be modified $binip = substr($binip, 0, $len); # Fill with 1s the variable part return ($binip . ('1' x ($size - length($binip)))); } #------------------------------------------------------------------------------ # Subroutine ip_splitprefix # Purpose : Split a prefix into IP and prefix length # Comments : If it was passed a simple IP, it just returns it # Params : Prefix # Returns : IP, optionnaly length of prefix sub ip_splitprefix { my $prefix = shift; # Find the '/' return unless ($prefix =~ m!^([^/]+?)(/\d+)?$!); my ($ip, $len) = ($1, $2); defined($len) and $len =~ s!/!!; return ($ip, $len); } #------------------------------------------------------------------------------ # Subroutine ip_prefix_to_range # Purpose : Get a range from a prefix # Params : IP, Prefix length, IP version # Returns : First IP, last IP sub ip_prefix_to_range { my ($ip, $len, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version"; $ERRNO = 101; return; } # Expand the first IP address $ip = ip_expand_address($ip, $ip_version); # Turn into a binary # Get last address # Turn into an IP my $binip = ip_iptobin($ip, $ip_version) or return; return unless (ip_check_prefix($binip, $len, $ip_version)); my $lastip = ip_last_address_bin($binip, $len, $ip_version) or return; return unless ($lastip = ip_bintoip($lastip, $ip_version)); return ($ip, $lastip); } #------------------------------------------------------------------------------ # Subroutine ip_is_valid_mask # Purpose : Check the validity of an IP mask (11110000) # Params : Mask # Returns : 1 or undef (invalid) sub ip_is_valid_mask { my ($mask, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version for $mask"; $ERRNO = 101; return; } my $len = ip_iplengths($ip_version); if (length($mask) != $len) { $ERROR = "Invalid mask length for $mask"; $ERRNO = 150; return; } # The mask should be of the form 111110000000 unless ($mask =~ m/^1*0*$/) { $ERROR = "Invalid mask $mask"; $ERRNO = 151; return; } return 1; } #------------------------------------------------------------------------------ # Subroutine ip_bincomp # Purpose : Compare binary Ips with <, >, <=, >= # Comments : Operators are lt(<), le(<=), gt(>), and ge(>=) # Params : First binary IP, operator, Last binary Ip # Returns : 1 (yes), 0 (no), or undef (problem) sub ip_bincomp { my ($begin, $op, $end) = @_; my ($b, $e); if ($op =~ /^l[te]$/) # Operator is lt or le { ($b, $e) = ($end, $begin); } elsif ($op =~ /^g[te]$/) # Operator is gt or ge { ($b, $e) = ($begin, $end); } else { $ERROR = "Invalid Operator $op\n"; $ERRNO = 131; return; } # le or ge -> return 1 if IPs are identical return (1) if ($op =~ /e/ and ($begin eq $end)); # Check IP sizes unless (length($b) eq length($e)) { $ERROR = "IP addresses of different length\n"; $ERRNO = 130; return; } my $c; # Foreach bit for (0 .. length($b) - 1) { # substract the two bits $c = substr($b, $_, 1) - substr($e, $_, 1); # Check the result return (1) if ($c == 1); return (0) if ($c == -1); } # IPs are identical return 0; } #------------------------------------------------------------------------------ # Subroutine ip_binadd # Purpose : Add two binary IPs # Params : First binary IP, Last binary Ip # Returns : Binary sum or undef (problem) sub ip_binadd { my ($b, $e) = @_; # Check IP length unless (length($b) eq length($e)) { $ERROR = "IP addresses of different length\n"; $ERRNO = 130; return; } # Reverse the two IPs $b = scalar(reverse $b); $e = scalar(reverse $e); my ($carry, $result, $c) = (0); # Foreach bit (reversed) for (0 .. length($b) - 1) { # add the two bits plus the carry $c = substr($b, $_, 1) + substr($e, $_, 1) + $carry; $carry = 0; # sum = 0 => $c = 0, $carry = 0 # sum = 1 => $c = 1, $carry = 0 # sum = 2 => $c = 0, $carry = 1 # sum = 3 => $c = 1, $carry = 1 if ($c > 1) { $c -= 2; $carry = 1; } $result .= $c; } # Reverse result return scalar(reverse($result)); } #------------------------------------------------------------------------------ # Subroutine ip_get_prefix_length # Purpose : Get the prefix length for a given range of IPs # Params : First binary IP, Last binary IP # Returns : Length of prefix or undef (problem) sub ip_get_prefix_length { my ($bin1, $bin2) = @_; # Check length of IPs unless (length($bin1) eq length($bin2)) { $ERROR = "IP addresses of different length\n"; $ERRNO = 130; return; } # reverse IPs $bin1 = scalar(reverse $bin1); $bin2 = scalar(reverse $bin2); # foreach bit for (0 .. length($bin1) - 1) { # If bits are equal it means we have reached the longest prefix return ("$_") if (substr($bin1, $_, 1) eq substr($bin2, $_, 1)); } # Return 32 (IPv4) or 128 (IPv6) return length($bin1); } #------------------------------------------------------------------------------ # Subroutine ip_range_to_prefix # Purpose : Return all prefixes between two IPs # Params : First IP, Last IP, IP version # Returns : List of Prefixes or undef (problem) sub ip_range_to_prefix { my ($binip, $endbinip, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version"; $ERRNO = 101; return; } unless (length($binip) eq length($endbinip)) { $ERROR = "IP addresses of different length\n"; $ERRNO = 130; return; } my ($len, $nbits, $current, $add, @prefix); # 1 in binary my $one = ('0' x (ip_iplengths($ip_version) - 1)) . '1'; # While we have not reached the last IP while (ip_bincomp($binip, 'le', $endbinip) == 1) { # Find all 0s at the end if ($binip =~ m/(0+)$/) { # nbits = nb of 0 bits $nbits = length($1); } else { $nbits = 0; } do { $current = $binip; $add = '1' x $nbits; # Replace $nbits 0s with 1s $current =~ s/0{$nbits}$/$add/; $nbits--; # Decrease $nbits if $current >= $endbinip } while (ip_bincomp($current, 'le', $endbinip) != 1); # Find Prefix length $len = (ip_iplengths($ip_version)) - ip_get_prefix_length($binip, $current); # Push prefix in list push(@prefix, ip_bintoip($binip, $ip_version) . "/$len"); # Add 1 to current IP $binip = ip_binadd($current, $one); # Exit if IP is 32/128 1s last if ($current =~ m/^1+$/); } return (@prefix); } #------------------------------------------------------------------------------ # Subroutine ip_compress_v4_prefix # Purpose : Compress an IPv4 Prefix # Params : IP, Prefix length # Returns : Compressed IP - ie: 194.5 sub ip_compress_v4_prefix { my ($ip, $len) = @_; my @quads = split /\./, $ip; my $qlen = int(($len - 1) / 8); $qlen = 0 if ($qlen < 0); my $newip = join '.', @quads[ 0 .. $qlen ]; return ($newip); } #------------------------------------------------------------------------------ # Subroutine ip_compress_address # Purpose : Compress an IPv6 address # Params : IP, IP version # Returns : Compressed IP or undef (problem) sub ip_compress_address { my ($ip, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version for $ip"; $ERRNO = 101; return; } # Just return if IP is IPv4 return ($ip) if ($ip_version == 4); # already compressed addresses must be expanded first $ip = ip_expand_address( $ip, $ip_version); # Remove leading 0s: 0034 -> 34; 0000 -> 0 $ip =~ s/ (^|:) # Find beginning or ':' -> $1 0+ # 1 or several 0s (?= # Look-ahead [a-fA-F\d]+ # One or several Hexs (?::|$)) # ':' or end /$1/gx; my $reg = ''; # Find the longuest :0:0: sequence while ( $ip =~ m/ ((?:^|:) # Find beginning or ':' -> $1 0(?::0)+ # 0 followed by 1 or several ':0' (?::|$)) # ':' or end /gx ) { $reg = $1 if (length($reg) < length($1)); } # Replace sequence by '::' $ip =~ s/$reg/::/ if ($reg ne ''); return $ip; } #------------------------------------------------------------------------------ # Subroutine ip_is_overlap # Purpose : Check if two ranges overlap # Params : Four binary IPs (begin of range 1,end1,begin2,end2) # Returns : $NO_OVERLAP (no overlap) # $IP_PARTIAL_OVERLAP (overlap) # $IP_A_IN_B_OVERLAP (range1 is included in range2) # $IP_B_IN_A_OVERLAP (range2 is included in range1) # $IP_IDENTICAL (range1 == range2) # or undef (problem) sub ip_is_overlap { my ($b1, $e1, $b2, $e2) = (@_); my $swap; $swap = 0; unless ((length($b1) eq length($e1)) and (length($b2) eq length($e2)) and (length($b1) eq length($b2))) { $ERROR = "IP addresses of different length\n"; $ERRNO = 130; return; } # begin1 <= end1 ? unless (ip_bincomp($b1, 'le', $e1) == 1) { $ERROR = "Invalid range $b1 - $e1"; $ERRNO = 140; return; } # begin2 <= end2 ? unless (ip_bincomp($b2, 'le', $e2) == 1) { $ERROR = "Invalid range $b2 - $e2"; $ERRNO = 140; return; } # b1 == b2 ? if ($b1 eq $b2) { # e1 == e2 return ($IP_IDENTICAL) if ($e1 eq $e2); # e1 < e2 ? return ( ip_bincomp($e1, 'lt', $e2) ? $IP_A_IN_B_OVERLAP : $IP_B_IN_A_OVERLAP ); } # e1 == e2 ? if ($e1 eq $e2) { # b1 < b2 return ( ip_bincomp($b1, 'lt', $b2) ? $IP_B_IN_A_OVERLAP : $IP_A_IN_B_OVERLAP ); } # b1 < b2 if ((ip_bincomp($b1, 'lt', $b2) == 1)) { # e1 < b2 return ($IP_NO_OVERLAP) if (ip_bincomp($e1, 'lt', $b2) == 1); # e1 < e2 ? return ( ip_bincomp($e1, 'lt', $e2) ? $IP_PARTIAL_OVERLAP : $IP_B_IN_A_OVERLAP ); } else # b1 > b2 { # e2 < b1 return ($IP_NO_OVERLAP) if (ip_bincomp($e2, 'lt', $b1) == 1); # e2 < e1 ? return ( ip_bincomp($e2, 'lt', $e1) ? $IP_PARTIAL_OVERLAP : $IP_A_IN_B_OVERLAP ); } } #------------------------------------------------------------------------------ # Subroutine get_embedded_ipv4 # Purpose : Get an IPv4 embedded in an IPv6 address # Params : IPv6 # Returns : IPv4 or undef (not found) sub ip_get_embedded_ipv4 { my $ipv6 = shift; my @ip = split /:/, $ipv6; # Bugfix by Norbert Koch return unless (@ip); # last octet should be ipv4 return ($ip[-1]) if (ip_is_ipv4($ip[-1])); return; } #------------------------------------------------------------------------------ # Subroutine aggregate # Purpose : Aggregate 2 ranges # Params : 1st range (1st IP, Last IP), last range (1st IP, last IP), # IP version # Returns : prefix or undef (invalid) sub ip_aggregate { my ($binbip1, $bineip1, $binbip2, $bineip2, $ip_version) = @_; unless ($ip_version) { $ERROR = "Cannot determine IP version for $binbip1"; $ERRNO = 101; return; } # Bin 1 my $one = (('0' x (ip_iplengths($ip_version) - 1)) . '1'); # $eip1 + 1 = $bip2 ? unless (ip_binadd($bineip1, $one) eq $binbip2) { $ERROR = "Ranges not contiguous - $bineip1 - $binbip2"; $ERRNO = 160; return; } # Get ranges my @prefix = ip_range_to_prefix($binbip1, $bineip2, $ip_version); # There should be only one range return if scalar(@prefix) < 1; if (scalar(@prefix) > 1) { $ERROR = "$binbip1 - $bineip2 is not a single prefix"; $ERRNO = 161; return; } return ($prefix[0]); } #------------------------------------------------------------------------------ # Subroutine ip_iptype # Purpose : Return the type of an IP (Public, Private, Reserved) # Params : IP to test, IP version # Returns : type or undef (invalid) sub ip_iptype { my ($ip, $ip_version) = @_; # handle known ip versions return ip_iptypev4($ip) if $ip_version == 4; return ip_iptypev6($ip) if $ip_version == 6; # unsupported ip version $ERROR = "IP version $ip not supported"; $ERRNO = 180; return; } #------------------------------------------------------------------------------ # Subroutine ip_iptypev4 # Purpose : Return the type of an IP (Public, Private, Reserved) # Params : IP to test, IP version # Returns : type or undef (invalid) sub ip_iptypev4 { my ($ip) = @_; # check ip if ($ip !~ m/^[01]{1,32}$/) { $ERROR = "$ip is not a binary IPv4 address $ip"; $ERRNO = 180; return; } # see if IP is listed foreach (sort { length($b) <=> length($a) } keys %IPv4ranges) { return ($IPv4ranges{$_}) if ($ip =~ m/^$_/); } # not listed means IP is public return 'PUBLIC'; } #------------------------------------------------------------------------------ # Subroutine ip_iptypev6 # Purpose : Return the type of an IP (Public, Private, Reserved) # Params : IP to test, IP version # Returns : type or undef (invalid) sub ip_iptypev6 { my ($ip) = @_; # check ip if ($ip !~ m/^[01]{1,128}$/) { $ERROR = "$ip is not a binary IPv6 address"; $ERRNO = 180; return; } foreach (sort { length($b) <=> length($a) } keys %IPv6ranges) { return ($IPv6ranges{$_}) if ($ip =~ m/^$_/); } # How did we get here? All IPv6 addresses should match $ERROR = "Cannot determine type for $ip"; $ERRNO = 180; return; } #------------------------------------------------------------------------------ # Subroutine ip_check_prefix # Purpose : Check the validity of a prefix # Params : binary IP, length of prefix, IP version # Returns : 1 or undef (invalid) sub ip_check_prefix { my ($binip, $len, $ipversion) = (@_); # Check if len is longer than IP if ($len > length($binip)) { $ERROR = "Prefix length $len is longer than IP address (" . length($binip) . ")"; $ERRNO = 170; return; } my $rest = substr($binip, $len); # Check if last part of the IP (len part) has only 0s unless ($rest =~ /^0*$/) { $ERROR = "Invalid prefix $binip/$len"; $ERRNO = 171; return; } # Check if prefix length is correct unless (length($rest) + $len == ip_iplengths($ipversion)) { $ERROR = "Invalid prefix length /$len"; $ERRNO = 172; return; } return 1; } #------------------------------------------------------------------------------ # Subroutine ip_reverse # Purpose : Get a reverse name from a prefix # Comments : From Lee's iplib.pm # Params : IP, length of prefix, IP version # Returns : Reverse name or undef (error) sub ip_reverse { my ($ip, $len, $ip_version) = (@_); $ip_version ||= ip_get_version($ip); unless ($ip_version) { $ERROR = "Cannot determine IP version for $ip"; $ERRNO = 101; return; } if ($ip_version == 4) { my @quads = split /\./, $ip; my $no_quads = ($len / 8); my @reverse_quads = reverse @quads; while (@reverse_quads and $reverse_quads[0] == 0) { shift(@reverse_quads); } return join '.', @reverse_quads, 'in-addr', 'arpa.'; } elsif ($ip_version == 6) { my @rev_groups = reverse split /:/, ip_expand_address($ip, 6); my @result; foreach (@rev_groups) { my @revhex = reverse split //; push @result, @revhex; } # This takes the zone above if it's not exactly on a nibble my $first_nibble_index = $len ? 32 - (int($len / 4)) : 0; return join '.', @result[ $first_nibble_index .. $#result ], 'ip6', 'arpa.'; } } #------------------------------------------------------------------------------ # Subroutine ip_normalize # Purpose : Normalize data to a range of IP addresses # Params : IP or prefix or range # Returns : ip1, ip2 (if range) or undef (error) sub ip_normalize { my ($data) = shift; my $ipversion; my ($len, $ip, $ip2, $real_len, $first, $last, $curr_bin, $addcst, $clen); # Prefix if ($data =~ m!^(\S+?)(/\S+)$!) { ($ip, $len) = ($1, $2); return unless ($ipversion = ip_get_version($ip)); return unless ($ip = ip_expand_address($ip, $ipversion)); return unless ($curr_bin = ip_iptobin($ip, $ipversion)); my $one = '0' x (ip_iplengths($ipversion) - 1) . '1'; while ($len) { last unless ($len =~ s!^/(\d+)(\,|$)!!); $clen = $1; $addcst = length($2) > 0; return unless (ip_check_prefix($curr_bin, $clen, $ipversion)); return unless ($curr_bin = ip_last_address_bin($curr_bin, $clen, $ipversion)); if ($addcst) { return unless ($curr_bin = ip_binadd($curr_bin, $one)); } } return ($ip, ip_bintoip($curr_bin, $ipversion)); } # Range elsif ($data =~ /^(.+?)\s*\-\s*(.+)$/) { ($ip, $ip2) = ($1, $2); return unless ($ipversion = ip_get_version($ip)); return unless ($ip = ip_expand_address($ip, $ipversion)); return unless ($ip2 = ip_expand_address($ip2, $ipversion)); return ($ip, $ip2); } # IP + Number elsif ($data =~ /^(.+?)\s+\+\s+(.+)$/) { ($ip, $len) = ($1, $2); return unless ($ipversion = ip_get_version($ip)); return unless ($ip = ip_expand_address($ip, $ipversion)); my ($bin_ip); return unless ($bin_ip = ip_iptobin($ip, $ipversion)); return unless ($len = ip_inttobin($len, $ipversion)); return unless ($ip2 = ip_binadd($bin_ip, $len)); return unless ($ip2 = ip_bintoip($ip2, $ipversion)); return ($ip, $ip2); } # Single IP else { $ip = $data; return unless ($ipversion = ip_get_version($ip)); return unless ($ip = ip_expand_address($ip, $ipversion)); return $ip; } } #------------------------------------------------------------------------------ # Subroutine normal_range # Purpose : Return the normalized format of a range # Params : IP or prefix or range # Returns : "ip1 - ip2" or undef (error) sub ip_normal_range { my ($data) = shift; my ($ip1, $ip2) = ip_normalize($data); return unless ($ip1); $ip2 ||= $ip1; return ("$ip1 - $ip2"); } #------------------------------------------------------------------------------ # Subroutine ip_auth # Purpose : Get Authority information from IP::Authority Module # Comments : Requires IP::Authority # Params : IP, length of prefix # Returns : Reverse name or undef (error) sub ip_auth { my ($ip, $ip_version) = (@_); unless ($ip_version) { $ERROR = "Cannot determine IP version for $ip"; $ERRNO = 101; die; return; } if ($ip_version != 4) { $ERROR = "Cannot get auth information: Not an IPv4 address"; $ERRNO = 308; die; return; } require IP::Authority; my $reg = new IP::Authority; return ($reg->inet_atoauth($ip)); } 1; __END__ =encoding utf8 =head1 NAME Net::IP - Perl extension for manipulating IPv4/IPv6 addresses =head1 SYNOPSIS use Net::IP; my $ip = new Net::IP ('193.0.1/24') or die (Net::IP::Error()); print ("IP : ".$ip->ip()."\n"); print ("Sho : ".$ip->short()."\n"); print ("Bin : ".$ip->binip()."\n"); print ("Int : ".$ip->intip()."\n"); print ("Mask: ".$ip->mask()."\n"); print ("Last: ".$ip->last_ip()."\n"); print ("Len : ".$ip->prefixlen()."\n"); print ("Size: ".$ip->size()."\n"); print ("Type: ".$ip->iptype()."\n"); print ("Rev: ".$ip->reverse_ip()."\n"); =head1 DESCRIPTION This module provides functions to deal with B addresses. The module can be used as a class, allowing the user to instantiate IP objects, which can be single IP addresses, prefixes, or ranges of addresses. There is also a procedural way of accessing most of the functions. Most subroutines can take either B or B addresses transparently. =head1 OBJECT-ORIENTED INTERFACE =head2 Object Creation A Net::IP object can be created from a single IP address: $ip = new Net::IP ('193.0.1.46') || die ... Or from a Classless Prefix (a /24 prefix is equivalent to a C class): $ip = new Net::IP ('195.114.80/24') || die ... Or from a range of addresses: $ip = new Net::IP ('20.34.101.207 - 201.3.9.99') || die ... Or from a address plus a number: $ip = new Net::IP ('20.34.10.0 + 255') || die ... The new() function accepts IPv4 and IPv6 addresses: $ip = new Net::IP ('dead:beef::/32') || die ... Optionnaly, the function can be passed the version of the IP. Otherwise, it tries to guess what the version is (see B<_is_ipv4()> and B<_is_ipv6()>). $ip = new Net::IP ('195/8',4); # Class A =head1 OBJECT METHODS Most of these methods are front-ends for the real functions, which use a procedural interface. Most functions return undef on failure, and a true value on success. A detailed description of the procedural interface is provided below. =head2 set Set an IP address in an existing IP object. This method has the same functionality as the new() method, except that it reuses an existing object to store the new IP. C<$ip-Eset('130.23.1/24',4);> Like new(), set() takes two arguments - a string used to build an IP address, prefix, or range, and optionally, the IP version of the considered address. It returns an IP object on success, and undef on failure. =head2 error Return the current object error string. The error string is set whenever one of the methods produces an error. Also, a global, class-wide B function is avaliable. Cerror());> =head2 errno Return the current object error number. The error number is set whenever one of the methods produces an error. Also, a global B<$ERRNO> variable is set when an error is produced. Cerrno());> =head2 ip Return the IP address (or first IP of the prefix or range) in quad format, as a string. Cip());> =head2 binip Return the IP address as a binary string of 0s and 1s. Cbinip());> =head2 prefixlen Return the length in bits of the current prefix. Cprefixlen());> =head2 version Return the version of the current IP object (4 or 6). Cversion());> =head2 size Return the number of IP addresses in the current prefix or range. Use of this function requires Math::BigInt. Csize());> =head2 binmask Return the binary mask of the current prefix, if applicable. Cbinmask());> =head2 mask Return the mask in quad format of the current prefix. Cmask());> =head2 prefix Return the full prefix (ip+prefix length) in quad (standard) format. Cprefix());> =head2 print Print the IP object (IP/Prefix or First - Last) Cprint());> =head2 intip Convert the IP in integer format and return it as a Math::BigInt object. Cintip());> =head2 hexip Return the IP in hex format Chexip());> =head2 hexmask Return the mask in hex format Chexmask());> =head2 short Return the IP in short format: IPv4 addresses: 194.5/16 IPv6 addresses: ab32:f000:: Cshort());> =head2 iptype Return the IP Type - this describes the type of an IP (Public, Private, Reserved, etc.) See procedural interface ip_iptype for more details. Ciptype());> =head2 reverse_ip Return the reverse IP for a given IP address (in.addr. format). Creserve_ip());> =head2 last_ip Return the last IP of a prefix/range in quad format. Clast_ip());> =head2 last_bin Return the last IP of a prefix/range in binary format. Clast_bin());> =head2 last_int Return the last IP of a prefix/range in integer format. Clast_int());> =head2 find_prefixes This function finds all the prefixes that can be found between the two addresses of a range. The function returns a list of prefixes. C<@list = $ip-Efind_prefixes($other_ip));> =head2 bincomp Binary comparaison of two IP objects. The function takes an operation and an IP object as arguments. It returns a boolean value. The operation can be one of: lt: less than (smaller than) le: smaller or equal to gt: greater than ge: greater or equal to Cbincomp('lt',$ip2) {...}> =head2 binadd Binary addition of two IP objects. The value returned is an IP object. Cbinadd($ip2);> =head2 aggregate Aggregate 2 IPs - Append one range/prefix of IPs to another. The last address of the first range must be the one immediately preceding the first address of the second range. A new IP object is returned. Caggregate($ip2);> =head2 overlaps Check if two IP ranges/prefixes overlap each other. The value returned by the function should be one of: $IP_PARTIAL_OVERLAP (ranges overlap) $IP_NO_OVERLAP (no overlap) $IP_A_IN_B_OVERLAP (range2 contains range1) $IP_B_IN_A_OVERLAP (range1 contains range2) $IP_IDENTICAL (ranges are identical) undef (problem) Coverlaps($ip2)==$IP_A_IN_B_OVERLAP) {...};> =head2 looping The C<+> operator is overloaded in order to allow looping though a whole range of IP addresses: my $ip = new Net::IP ('195.45.6.7 - 195.45.6.19') || die; # Loop do { print $ip->ip(), "\n"; } while (++$ip); The ++ operator returns undef when the last address of the range is reached. =head2 auth Return IP authority information from the IP::Authority module C<$auth = ip->auth ();> Note: IPv4 only =head1 PROCEDURAL INTERFACE These functions do the real work in the module. Like the OO methods, most of these return undef on failure. In order to access error codes and strings, instead of using $ip-Eerror() and $ip-Eerrno(), use the global functions C and C. The functions of the procedural interface are not exported by default. In order to import these functions, you need to modify the use statement for the module: C =head2 Error Returns the error string corresponding to the last error generated in the module. This is also useful for the OO interface, as if the new() function fails, we cannot call $ip-Eerror() and so we have to use Error(). warn Error(); =head2 Errno Returns a numeric error code corresponding to the error string returned by Error. =head2 ip_iptobin Transform an IP address into a bit string. Params : IP address, IP version Returns : binary IP string on success, undef otherwise C<$binip = ip_iptobin ($ip,6);> =head2 ip_bintoip Transform a bit string into an IP address Params : binary IP, IP version Returns : IP address on success, undef otherwise C<$ip = ip_bintoip ($binip,6);> =head2 ip_bintoint Transform a bit string into a BigInt. Params : binary IP Returns : BigInt C<$bigint = new Math::BigInt (ip_bintoint($binip));> =head2 ip_inttobin Transform a BigInt into a bit string. I: sets warnings (C<-w>) off. This is necessary because Math::BigInt is not compliant. Params : BigInt, IP version Returns : binary IP C<$binip = ip_inttobin ($bigint);> =head2 ip_get_version Try to guess the IP version of an IP address. Params : IP address Returns : 4, 6, undef(unable to determine) C<$version = ip_get_version ($ip)> =head2 ip_is_ipv4 Check if an IP address is of type 4. Params : IP address Returns : 1 (yes) or 0 (no) C =head2 ip_is_ipv6 Check if an IP address is of type 6. Params : IP address Returns : 1 (yes) or 0 (no) C =head2 ip_expand_address Expand an IP address from compact notation. Params : IP address, IP version Returns : expanded IP address or undef on failure C<$ip = ip_expand_address ($ip,4);> =head2 ip_get_mask Get IP mask from prefix length. Params : Prefix length, IP version Returns : Binary Mask C<$mask = ip_get_mask ($len,6);> =head2 ip_last_address_bin Return the last binary address of a prefix. Params : First binary IP, prefix length, IP version Returns : Binary IP C<$lastbin = ip_last_address_bin ($ip,$len,6);> =head2 ip_splitprefix Split a prefix into IP and prefix length. If it was passed a simple IP, it just returns it. Params : Prefix Returns : IP, optionnaly length of prefix C<($ip,$len) = ip_splitprefix ($prefix)> =head2 ip_prefix_to_range Get a range of IPs from a prefix. Params : Prefix, IP version Returns : First IP, last IP C<($ip1,$ip2) = ip_prefix_to_range ($prefix,6);> =head2 ip_bincomp Compare binary Ips with <, >, <=, >=. Operators are lt(<), le(<=), gt(>), and ge(>=) Params : First binary IP, operator, Last binary IP Returns : 1 (yes), 0 (no), or undef (problem) C =head2 ip_binadd Add two binary IPs. Params : First binary IP, Last binary IP Returns : Binary sum or undef (problem) C<$binip = ip_binadd ($bin1,$bin2);> =head2 ip_get_prefix_length Get the prefix length for a given range of 2 IPs. Params : First binary IP, Last binary IP Returns : Length of prefix or undef (problem) C<$len = ip_get_prefix_length ($ip1,$ip2);> =head2 ip_range_to_prefix Return all prefixes between two IPs. Params : First IP (binary format), Last IP (binary format), IP version Returns : List of Prefixes or undef (problem) The prefixes returned have the form q.q.q.q/nn. C<@prefix = ip_range_to_prefix ($ip1,$ip2,6);> =head2 ip_compress_v4_prefix Compress an IPv4 Prefix. Params : IP, Prefix length Returns : Compressed Prefix C<$ip = ip_compress_v4_prefix ($ip, $len);> =head2 ip_compress_address Compress an IPv6 address. Just returns the IP if it is an IPv4. Params : IP, IP version Returns : Compressed IP or undef (problem) C<$ip = ip_compress_adress ($ip, $version);> =head2 ip_is_overlap Check if two ranges of IPs overlap. Params : Four binary IPs (begin of range 1,end1,begin2,end2), IP version $IP_PARTIAL_OVERLAP (ranges overlap) $IP_NO_OVERLAP (no overlap) $IP_A_IN_B_OVERLAP (range2 contains range1) $IP_B_IN_A_OVERLAP (range1 contains range2) $IP_IDENTICAL (ranges are identical) undef (problem) C<(ip_is_overlap($rb1,$re1,$rb2,$re2,4) eq $IP_A_IN_B_OVERLAP) and do {};> =head2 ip_get_embedded_ipv4 Get an IPv4 embedded in an IPv6 address Params : IPv6 Returns : IPv4 string or undef (not found) C<$ip4 = ip_get_embedded($ip6);> =head2 ip_check_mask Check the validity of a binary IP mask Params : Mask Returns : 1 or undef (invalid) C Checks if mask has only 1s followed by 0s. =head2 ip_aggregate Aggregate 2 ranges of binary IPs Params : 1st range (1st IP, Last IP), last range (1st IP, last IP), IP version Returns : prefix or undef (invalid) C<$prefix = ip_aggregate ($bip1,$eip1,$bip2,$eip2) || die ...> =head2 ip_iptypev4 Return the type of an IPv4 address. Params: binary IP Returns: type as of the following table or undef (invalid ip) See RFC 5735 and RFC 6598 S
S<-------------------------------------------------------------------> S<0.0.0.0/8 "This" Network RFC 1122 PRIVATE> S<10.0.0.0/8 Private-Use Networks RFC 1918 PRIVATE> S<100.64.0.0/10 CGN Shared Address Space RFC 6598 SHARED> S<127.0.0.0/8 Loopback RFC 1122 LOOPBACK> S<169.254.0.0/16 Link Local RFC 3927 LINK-LOCAL> S<172.16.0.0/12 Private-Use Networks RFC 1918 PRIVATE> S<192.0.0.0/24 IETF Protocol Assignments RFC 5736 RESERVED> S<192.0.2.0/24 TEST-NET-1 RFC 5737 TEST-NET> S<192.88.99.0/24 6to4 Relay Anycast RFC 3068 6TO4-RELAY> S<192.168.0.0/16 Private-Use Networks RFC 1918 PRIVATE> S<198.18.0.0/15 Network Interconnect> S< Device Benchmark Testing RFC 2544 RESERVED> S<198.51.100.0/24 TEST-NET-2 RFC 5737 TEST-NET> S<203.0.113.0/24 TEST-NET-3 RFC 5737 TEST-NET> S<224.0.0.0/4 Multicast RFC 3171 MULTICAST> S<240.0.0.0/4 Reserved for Future Use RFC 1112 RESERVED> S<255.255.255.255/32 Limited Broadcast RFC 919 BROADCAST> S< RFC 922> =head2 ip_iptypev6 Return the type of an IPv6 address. Params: binary ip Returns: type as of the following table or undef (invalid) See L and L S S<-------------------------------------------------------------> S<0000::/8 Reserved by IETF [RFC4291] RESERVED> S<0100::/8 Reserved by IETF [RFC4291] RESERVED> S<0200::/7 Reserved by IETF [RFC4048] RESERVED> S<0400::/6 Reserved by IETF [RFC4291] RESERVED> S<0800::/5 Reserved by IETF [RFC4291] RESERVED> S<1000::/4 Reserved by IETF [RFC4291] RESERVED> S<2000::/3 Global Unicast [RFC4291] GLOBAL-UNICAST> S<4000::/3 Reserved by IETF [RFC4291] RESERVED> S<6000::/3 Reserved by IETF [RFC4291] RESERVED> S<8000::/3 Reserved by IETF [RFC4291] RESERVED> S S S S S S S S S S S S<---------------------------------------------------------------------> S<::1/128 Loopback Address [RFC4291] UNSPECIFIED> S<::/128 Unspecified Address [RFC4291] LOOPBACK> S<::FFFF:0:0/96 IPv4-mapped Address [RFC4291] IPV4MAP> S<0100::/64 Discard-Only Prefix [RFC6666] DISCARD> S<2001:0000::/32 TEREDO [RFC4380] TEREDO> S<2001:0002::/48 BMWG [RFC5180] BMWG> S<2001:db8::/32 Documentation Prefix [RFC3849] DOCUMENTATION> S<2001:10::/28 ORCHID [RFC4843] ORCHID> S<2002::/16 6to4 [RFC3056] 6TO4> S S S =head2 ip_iptype Return the type of an IP (Public, Private, Reserved) Params : Binary IP to test, IP version (defaults to 6) Returns : type (see ip_iptypev4 and ip_iptypev6 for details) or undef (invalid) C<$type = ip_iptype ($ip);> =head2 ip_check_prefix Check the validity of a prefix Params : binary IP, length of prefix, IP version Returns : 1 or undef (invalid) Checks if the variant part of a prefix only has 0s, and the length is correct. C =head2 ip_reverse Get a reverse name from a prefix Params : IP, length of prefix, IP version Returns : Reverse name or undef (error) C<$reverse = ip_reverse ($ip);> =head2 ip_normalize Normalize data to a range/prefix of IP addresses Params : Data String (Single IP, Range, Prefix) Returns : ip1, ip2 (if range/prefix) or undef (error) C<($ip1,$ip2) = ip_normalize ($data);> =head2 ip_auth Return IP authority information from the IP::Authority module Params : IP, version Returns : Auth info (RI for RIPE, AR for ARIN, etc) C<$auth = ip_auth ($ip,4);> Note: IPv4 only =head1 BUGS The Math::BigInt library is needed for functions that use integers. These are ip_inttobin, ip_bintoint, and the size method. In a next version, Math::BigInt will become optionnal. =head1 AUTHORS Manuel Valente . Original IPv4 code by Monica Cortes Sack . Original IPv6 code by Lee Wilmot . =head1 BASED ON ipv4pack.pm, iplib.pm, iplibncc.pm. =head1 SEE ALSO perl(1), IP::Authority =cut PK!ª1‘× × perl5/Net/HTTPS.pmnuÏÃ6Ç$package Net::HTTPS; our $VERSION = '6.19'; use strict; use warnings; # Figure out which SSL implementation to use use vars qw($SSL_SOCKET_CLASS); if ($SSL_SOCKET_CLASS) { # somebody already set it } elsif ($SSL_SOCKET_CLASS = $ENV{PERL_NET_HTTPS_SSL_SOCKET_CLASS}) { unless ($SSL_SOCKET_CLASS =~ /^(IO::Socket::SSL|Net::SSL)\z/) { die "Bad socket class [$SSL_SOCKET_CLASS]"; } eval "require $SSL_SOCKET_CLASS"; die $@ if $@; } elsif ($IO::Socket::SSL::VERSION) { $SSL_SOCKET_CLASS = "IO::Socket::SSL"; # it was already loaded } elsif ($Net::SSL::VERSION) { $SSL_SOCKET_CLASS = "Net::SSL"; } else { eval { require IO::Socket::SSL; }; if ($@) { my $old_errsv = $@; eval { require Net::SSL; # from Crypt-SSLeay }; if ($@) { $old_errsv =~ s/\s\(\@INC contains:.*\)/)/g; die $old_errsv . $@; } $SSL_SOCKET_CLASS = "Net::SSL"; } else { $SSL_SOCKET_CLASS = "IO::Socket::SSL"; } } require Net::HTTP::Methods; our @ISA=($SSL_SOCKET_CLASS, 'Net::HTTP::Methods'); sub configure { my($self, $cnf) = @_; $self->http_configure($cnf); } sub http_connect { my($self, $cnf) = @_; if ($self->isa("Net::SSL")) { if ($cnf->{SSL_verify_mode}) { if (my $f = $cnf->{SSL_ca_file}) { $ENV{HTTPS_CA_FILE} = $f; } if (my $f = $cnf->{SSL_ca_path}) { $ENV{HTTPS_CA_DIR} = $f; } } if ($cnf->{SSL_verifycn_scheme}) { $@ = "Net::SSL from Crypt-SSLeay can't verify hostnames; either install IO::Socket::SSL or turn off verification by setting the PERL_LWP_SSL_VERIFY_HOSTNAME environment variable to 0"; return undef; } } $self->SUPER::configure($cnf); } sub http_default_port { 443; } if ($SSL_SOCKET_CLASS eq "Net::SSL") { # The underlying SSLeay classes fails to work if the socket is # placed in non-blocking mode. This override of the blocking # method makes sure it stays the way it was created. *blocking = sub { }; } 1; =pod =encoding UTF-8 =head1 NAME Net::HTTPS - Low-level HTTP over SSL/TLS connection (client) =head1 VERSION version 6.19 =head1 DESCRIPTION The C is a low-level HTTP over SSL/TLS client. The interface is the same as the interface for C, but the constructor takes additional parameters as accepted by L. The C object is an C too, which makes it inherit additional methods from that base class. For historical reasons this module also supports using C (from the Crypt-SSLeay distribution) as its SSL driver and base class. This base is automatically selected if available and C isn't. You might also force which implementation to use by setting $Net::HTTPS::SSL_SOCKET_CLASS before loading this module. If not set this variable is initialized from the C environment variable. =head1 ENVIRONMENT You might set the C environment variable to the name of the base SSL implementation (and Net::HTTPS base class) to use. The default is C. Currently the only other supported value is C. =head1 SEE ALSO L, L =head1 AUTHOR Gisle Aas =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2001-2017 by Gisle Aas. 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 __END__ #ABSTRACT: Low-level HTTP over SSL/TLS connection (client) PK!4;{g� � perl5/lib/core/only.pmnuÏÃ6Ç$package lib::core::only; use strict; use warnings FATAL => 'all'; use Config; sub import { @INC = @Config{qw(privlibexp archlibexp)}; return } =head1 NAME lib::core::only - Remove all non-core paths from @INC to avoid site/vendor dirs =head1 SYNOPSIS use lib::core::only; # now @INC contains only the two core directories To get only the core directories plus the ones for the local::lib in scope: $ perl -mlocal::lib -Mlib::core::only -Mlocal::lib=~/perl5 myscript.pl To attempt to do a self-contained build (but note this will not reliably propagate into subprocesses, see the CAVEATS below): $ PERL5OPT='-mlocal::lib -Mlib::core::only -Mlocal::lib=~/perl5' cpan Please note that it is necessary to use C twice for this to work. First so that C doesn't prevent C from loading (it's not currently in core) and then again after C so that the local paths are not removed. =head1 DESCRIPTION lib::core::only is simply a shortcut to say "please reduce my @INC to only the core lib and archlib (architecture-specific lib) directories of this perl". You might want to do this to ensure a local::lib contains only the code you need, or to test an L tree, or to avoid known bad vendor packages. You might want to use this to try and install a self-contained tree of perl modules. Be warned that that probably won't work (see L). This module was extracted from L's --self-contained feature, and contains the only part that ever worked. I apologise to anybody who thought anything else did. =head1 CAVEATS This does B propagate properly across perl invocations like local::lib's stuff does. It can't. It's only a module import, so it B. If you want to cascade it across invocations, you can set the PERL5OPT environment variable to '-Mlib::core::only' and it'll sort of work. But be aware that taint mode ignores this, so some modules' build and test code probably will as well. You also need to be aware that perl's command line options are not processed in order - -I options take effect before -M options, so perl -Mlib::core::only -Ilib is unlike to do what you want - it's exactly equivalent to: perl -Mlib::core::only If you want to combine a core-only @INC with additional paths, you need to add the additional paths using -M options and the L module: perl -Mlib::core::only -Mlib=lib # or if you're trying to test compiled code: perl -Mlib::core::only -Mblib For more information on the impossibility of sanely propagating this across module builds without help from the build program, see L - and for ways to achieve the old --self-contained feature's results, look at L's tree function, and at L's --local-lib-contained feature. =head1 AUTHOR Matt S. Trout =head1 LICENSE This library is free software under the same terms as perl itself. =head1 COPYRIGHT (c) 2010 the lib::core::only L as specified above. =cut 1; PK!|£ÈÒã@ã@perl5/FFI/CheckLib.pmnuÏÃ6Ç$package FFI::CheckLib; use strict; use warnings; use File::Spec; use Carp qw( croak carp ); use base qw( Exporter ); our @EXPORT = qw( find_lib assert_lib check_lib check_lib_or_exit find_lib_or_exit find_lib_or_die ); our @EXPORT_OK = qw( which where has_symbols ); # ABSTRACT: Check that a library is available for FFI our $VERSION = '0.27'; # VERSION our $system_path = []; our $os ||= $^O; my $try_ld_on_text = 0; if($os eq 'MSWin32' || $os eq 'msys') { $system_path = eval { require Env; Env->import('@PATH'); \our @PATH; }; die $@ if $@; } else { $system_path = eval { require DynaLoader; no warnings 'once'; \@DynaLoader::dl_library_path; }; die $@ if $@; } our $pattern = [ qr{^lib(.*?)\.so(?:\.([0-9]+(?:\.[0-9]+)*))?$} ]; our $version_split = qr/\./; if($os eq 'cygwin') { push @$pattern, qr{^cyg(.*?)(?:-([0-9])+)?\.dll$}; } elsif($os eq 'msys') { # doesn't seem as though msys uses psudo libfoo.so files # in the way that cygwin sometimes does. we can revisit # this if we find otherwise. $pattern = [ qr{^msys-(.*?)(?:-([0-9])+)?\.dll$} ]; } elsif($os eq 'MSWin32') { # handle cases like libgeos-3-7-0___.dll and libgtk-2.0-0.dll $pattern = [ qr{^(?:lib)?(\w+?)(?:-([0-9-\.]+))?_*\.dll$}i ]; $version_split = qr/\-/; } elsif($os eq 'darwin') { push @$pattern, qr{^lib(.*?)(?:\.([0-9]+(?:\.[0-9]+)*))?\.(?:dylib|bundle)$}; } elsif($os eq 'linux') { if(-e '/etc/redhat-release' && -x '/usr/bin/ld') { $try_ld_on_text = 1; } } sub _matches { my($filename, $path) = @_; foreach my $regex (@$pattern) { return [ $1, # 0 capture group 1 library name File::Spec->catfile($path, $filename), # 1 full path to library defined $2 ? (split $version_split, $2) : (), # 2... capture group 2 library version ] if $filename =~ $regex; } return (); } sub _cmp { my($A,$B) = @_; return $A->[0] cmp $B->[0] if $A->[0] ne $B->[0]; my $i=2; while(1) { return 0 if !defined($A->[$i]) && !defined($B->[$i]); return -1 if !defined $A->[$i]; return 1 if !defined $B->[$i]; return $B->[$i] <=> $A->[$i] if $A->[$i] != $B->[$i]; $i++; } } my $diagnostic; sub _is_binary { -B $_[0] } sub find_lib { my(%args) = @_; undef $diagnostic; croak "find_lib requires lib argument" unless defined $args{lib}; my $recursive = $args{_r} || $args{recursive} || 0; # make arguments be lists. foreach my $arg (qw( lib libpath symbol verify alien )) { next if ref $args{$arg} eq 'ARRAY'; if(defined $args{$arg}) { $args{$arg} = [ $args{$arg} ]; } else { $args{$arg} = []; } } if(defined $args{systempath} && !ref($args{systempath})) { $args{systempath} = [ $args{systempath} ]; } my @path = @{ $args{libpath} }; @path = map { _recurse($_) } @path if $recursive; push @path, grep { defined } defined $args{systempath} ? @{ $args{systempath} } : @$system_path; my $any = 1 if grep { $_ eq '*' } @{ $args{lib} }; my %missing = map { $_ => 1 } @{ $args{lib} }; my %symbols = map { $_ => 1 } @{ $args{symbol} }; my @found; delete $missing{'*'}; foreach my $alien (@{ $args{alien} }) { unless($alien =~ /^([A-Za-z_][A-Za-z_0-9]*)(::[A-Za-z_][A-Za-z_0-9]*)*$/) { croak "Doesn't appear to be a valid Alien name $alien"; } unless(eval { $alien->can('dynamic_libs') }) { my $pm = "$alien.pm"; $pm =~ s/::/\//g; require $pm; unless(eval { $alien->can('dynamic_libs') }) { croak "Alien $alien doesn't provide a dynamic_libs method"; } } push @path, [$alien->dynamic_libs]; } foreach my $path (@path) { next if ref $path ne 'ARRAY' && ! -d $path; my @maybe = # make determinist based on names and versions sort { _cmp($a,$b) } # Filter out the items that do not match the name that we are looking for # Filter out any broken symbolic links grep { ($any || $missing{$_->[0]} ) && (-e $_->[1]) } ref $path eq 'ARRAY' ? do { map { my($v, $d, $f) = File::Spec->splitpath($_); _matches($f, File::Spec->catpath($v,$d)); } @$path; } : do { my $dh; opendir $dh, $path; # get [ name, full_path ] mapping, # each entry is a 2 element list ref map { _matches($_,$path) } readdir $dh; }; if($try_ld_on_text && $args{try_linker_script}) { # This is tested in t/ci.t only @maybe = map { -B $_->[1] ? $_ : do { my($name, $so) = @$_; my $output = `/usr/bin/ld -t $so -o /dev/null -shared`; $output =~ /\((.*?lib.*\.so.*?)\)/ ? [$name, $1] : die "unable to parse ld output"; } } @maybe; } midloop: foreach my $lib (@maybe) { next unless $any || $missing{$lib->[0]}; foreach my $verify (@{ $args{verify} }) { next midloop unless $verify->(@$lib); } delete $missing{$lib->[0]}; if(%symbols) { require DynaLoader; my $dll = DynaLoader::dl_load_file($lib->[1],0); foreach my $symbol (keys %symbols) { if(DynaLoader::dl_find_symbol($dll, $symbol) ? 1 : 0) { delete $symbols{$symbol} } } DynaLoader::dl_unload_file($dll); } my $found = $lib->[1]; unless($any) { while(-l $found) { require File::Basename; my $dir = File::Basename::dirname($found); $found = File::Spec->rel2abs( readlink($found), $dir ); } } push @found, $found; } } if(%missing) { my @missing = sort keys %missing; if(@missing > 1) { $diagnostic = "libraries not found: @missing" } else { $diagnostic = "library not found: @missing" } } elsif(%symbols) { my @missing = sort keys %symbols; if(@missing > 1) { $diagnostic = "symbols not found: @missing" } else { $diagnostic = "symbol not found: @missing" } } return if %symbols; return $found[0] unless wantarray; return @found; } sub _recurse { my($dir) = @_; return unless -d $dir; my $dh; opendir $dh, $dir; my @list = grep { -d $_ } map { File::Spec->catdir($dir, $_) } grep !/^\.\.?$/, readdir $dh; closedir $dh; ($dir, map { _recurse($_) } @list); } sub assert_lib { croak $diagnostic || 'library not found' unless check_lib(@_); } sub check_lib_or_exit { unless(check_lib(@_)) { carp $diagnostic || 'library not found'; exit; } } sub find_lib_or_exit { my(@libs) = find_lib(@_); unless(@libs) { carp $diagnostic || 'library not found'; exit; } return unless @libs; wantarray ? @libs : $libs[0]; } sub find_lib_or_die { my(@libs) = find_lib(@_); unless(@libs) { croak $diagnostic || 'library not found'; } return unless @libs; wantarray ? @libs : $libs[0]; } sub check_lib { find_lib(@_) ? 1 : 0; } sub which { my($name) = @_; croak("cannot which *") if $name eq '*'; scalar find_lib( lib => $name ); } sub where { my($name) = @_; $name eq '*' ? find_lib(lib => '*') : find_lib(lib => '*', verify => sub { $_[0] eq $name }); } sub has_symbols { my($path, @symbols) = @_; require DynaLoader; my $dll = DynaLoader::dl_load_file($path, 0); my $ok = 1; foreach my $symbol (@symbols) { unless(DynaLoader::dl_find_symbol($dll, $symbol)) { $ok = 0; last; } } DynaLoader::dl_unload_file($dll); $ok; } sub system_path { $system_path; } 1; __END__ =pod =encoding UTF-8 =head1 NAME FFI::CheckLib - Check that a library is available for FFI =head1 VERSION version 0.27 =head1 SYNOPSIS use FFI::CheckLib; check_lib_or_exit( lib => 'jpeg', symbol => 'jinit_memory_mgr' ); check_lib_or_exit( lib => [ 'iconv', 'jpeg' ] ); # or prompt for path to library and then: print "where to find jpeg library: "; my $path = ; check_lib_or_exit( lib => 'jpeg', libpath => $path ); =head1 DESCRIPTION This module checks whether a particular dynamic library is available for FFI to use. It is modeled heavily on L, but will find dynamic libraries even when development packages are not installed. It also provides a L function that will return the full path to the found dynamic library, which can be feed directly into L or another FFI system. Although intended mainly for FFI modules via L and similar, this module does not actually use any FFI to do its detection and probing. This module does not have any non-core runtime dependencies. The test suite does depend on L. =head1 FUNCTIONS All of these take the same named parameters and are exported by default. =head2 find_lib my(@libs) = find_lib(%args); This will return a list of dynamic libraries, or empty list if none were found. [version 0.05] If called in scalar context it will return the first library found. Arguments are key value pairs with these keys: =over 4 =item lib Must be either a string with the name of a single library or a reference to an array of strings of library names. Depending on your platform, C will prepend C or append C<.dll> or C<.so> when searching. [version 0.11] As a special case, if C<*> is specified then any libs found will match. =item libpath A string or array of additional paths to search for libraries. =item systempath [version 0.11] A string or array of system paths to search for instead of letting L determine the system path. You can set this to C<[]> in order to not search I system paths. =item symbol A string or a list of symbol names that must be found. =item verify A code reference used to verify a library really is the one that you want. It should take two arguments, which is the name of the library and the full path to the library pathname. It should return true if it is acceptable, and false otherwise. You can use this in conjunction with L to determine if it is going to meet your needs. Example: use FFI::CheckLib; use FFI::Platypus; my($lib) = find_lib( lib => 'foo', verify => sub { my($name, $libpath) = @_; my $ffi = FFI::Platypus->new; $ffi->lib($libpath); my $f = $ffi->function('foo_version', [] => 'int'); return $f->call() >= 500; # we accept version 500 or better }, ); =item recursive [version 0.11] Recursively search for libraries in any non-system paths (those provided via C above). =item try_linker_script [version 0.24] Some vendors provide C<.so> files that are linker scripts that point to the real binary shared library. These linker scripts can be used by gcc or clang, but are not directly usable by L and friends. On select platforms, this options will use the linker command (C) to attempt to resolve the real C<.so> for non-binary files. Since there is extra overhead this is off by default. An example is libyaml on Red Hat based Linux distributions. On Debian these are handled with symlinks and no trickery is required. =item alien [version 0.25] If no libraries can be found, try the given aliens instead. The Alien classes specified must provide the L interface for dynamic libraries, which is to say they should provide a method called C that returns a list of dynamic libraries. =back =head2 assert_lib assert_lib(%args); This behaves exactly the same as L, except that instead of returning empty list of failure it throws an exception. =head2 check_lib_or_exit check_lib_or_exit(%args); This behaves exactly the same as L, except that instead of dying, it warns (with exactly the same error message) and exists. This is intended for use in C or C =head2 find_lib_or_exit [version 0.05] my(@libs) = find_lib_or_exit(%args); This behaves exactly the same as L, except that if the library is not found, it will call exit with an appropriate diagnostic. =head2 find_lib_or_die [version 0.06] my(@libs) = find_lib_or_die(%args); This behaves exactly the same as L, except that if the library is not found, it will die with an appropriate diagnostic. =head2 check_lib my $bool = check_lib(%args); This behaves exactly the same as L, except that it returns true (1) on finding the appropriate libraries or false (0) otherwise. =head2 which [version 0.17] my $path = where($name); Return the path to the first library that matches the given name. Not exported by default. =head2 where [version 0.17] my @paths = where($name); Return the paths to all the libraries that match the given name. Not exported by default. =head2 has_symbols [version 0.17] my $bool = has_symbols($path, @symbol_names); Returns true if I of the symbols can be found in the dynamic library located at the given path. Can be useful in conjunction with C with C above. Not exported by default. =head2 system_path [version 0.20] my $path = FFI::CheckLib::system_path; Returns the system path as a list reference. On some systems, this is C on others it might be C on still others it could be something completely different. So although you I add items to this list, you should probably do some careful consideration before you do so. This function is not exportable, even on request. =head1 FAQ =over 4 =item Why not just use C? Calling C on a library name and then C immediately can tell you if you have the exact name of a library available on a system. It does have a number of drawbacks as well. =over 4 =item No absolute or relative path It only tells you that the library is I on the system, not having the absolute or relative path makes it harder to generate useful diagnostics. =item POSIX only This doesn't work on non-POSIX systems like Microsoft Windows. If you are using a POSIX emulation layer on Windows that provides C, like Cygwin, there are a number of gotchas there as well. Having a layer written in Perl handles this means that developers on Unix can develop FFI that will more likely work on these platforms without special casing them. =item inconsistent implementations Even on POSIX systems you have inconsistent implementations. OpenBSD for example don't usually include symlinks for C<.so> files meaning you need to know the exact C<.so> version. =item non-system directories By default C only works for libraries in the system paths. Most platforms have a way of configuring the search for different non-system paths, but none of them are portable, and are usually discouraged anyway. L and friends need to do searches for dynamic libraries in non-system directories for C installs. =back =item My 64-bit Perl is misconfigured and has 32-bit libraries in its search path. Is that a bug in L? Nope. =item The way L is implemented it won't work on AIX, HP-UX, OpenVMS or Plan 9. I know for a fact that it doesn't work on AIX I because I used to develop on AIX in the early 2000s, and I am aware of some of the technical challenges. There are probably other systems that it won't work on. I would love to add support for these platforms. Realistically these platforms have a tiny market share, and absent patches from users or the companies that own these operating systems (patches welcome), or hardware / CPU time donations, these platforms are unsupportable anyway. =back =head1 SEE ALSO =over 4 =item L Call library functions dynamically without a compiler. =item L L plugin for this module. =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Bakkiaraj Murugesan (bakkiaraj) Dan Book (grinnz, DBOOK) Ilya Pavlov (Ilya, ILUX) Shawn Laffan (SLAFFAN) Petr Pisar (ppisar) =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014-2018 by Graham Ollis. 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 PK!«³öÅLÅLperl5/XML/SAX/Expat.pmnuƒ7�æm ### # XML::SAX::Expat - SAX2 Driver for Expat (XML::Parser) # Originally by Robin Berjon ### package XML::SAX::Expat; use strict; use base qw(XML::SAX::Base); use XML::NamespaceSupport qw(); use XML::Parser qw(); use vars qw($VERSION); $VERSION = '0.51'; #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,# #`,`, Variations on parse `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,# #```````````````````````````````````````````````````````````````````# #-------------------------------------------------------------------# # CharacterStream #-------------------------------------------------------------------# sub _parse_characterstream { my $p = shift; my $xml = shift; my $opt = shift; my $expat = $p->_create_parser($opt); my $result = $expat->parse($xml); $p->_cleanup; return $result; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # ByteStream #-------------------------------------------------------------------# sub _parse_bytestream { my $p = shift; my $xml = shift; my $opt = shift; my $expat = $p->_create_parser($opt); my $result = $expat->parse($xml); $p->_cleanup; return $result; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # String #-------------------------------------------------------------------# sub _parse_string { my $p = shift; my $xml = shift; my $opt = shift; my $expat = $p->_create_parser($opt); my $result = $expat->parse($xml); $p->_cleanup; return $result; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # SystemId #-------------------------------------------------------------------# sub _parse_systemid { my $p = shift; my $xml = shift; my $opt = shift; my $expat = $p->_create_parser($opt); my $result = $expat->parsefile($xml); $p->_cleanup; return $result; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # $p->_create_parser(\%options) #-------------------------------------------------------------------# sub _create_parser { my $self = shift; my $opt = shift; die "ParserReference: parser instance ($self) already parsing\n" if $self->{_InParse}; my $featUri = 'http://xml.org/sax/features/'; my $ppe = ($self->get_feature($featUri . 'external-general-entities') or $self->get_feature($featUri . 'external-parameter-entities') ) ? 1 : 0; my $expat = XML::Parser->new( ParseParamEnt => $ppe ); $expat->{__XSE} = $self; $expat->setHandlers( Init => \&_handle_init, Final => \&_handle_final, Start => \&_handle_start, End => \&_handle_end, Char => \&_handle_char, Comment => \&_handle_comment, Proc => \&_handle_proc, CdataStart => \&_handle_start_cdata, CdataEnd => \&_handle_end_cdata, Unparsed => \&_handle_unparsed_entity, Notation => \&_handle_notation_decl, #ExternEnt #ExternEntFin Entity => \&_handle_entity_decl, Element => \&_handle_element_decl, Attlist => \&_handle_attr_decl, Doctype => \&_handle_start_doctype, DoctypeFin => \&_handle_end_doctype, XMLDecl => \&_handle_xml_decl, ); $self->{_InParse} = 1; $self->{_NodeStack} = []; $self->{_NSStack} = []; $self->{_NSHelper} = XML::NamespaceSupport->new({xmlns => 1}); $self->{_started} = 0; return $expat; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # $p->_cleanup #-------------------------------------------------------------------# sub _cleanup { my $self = shift; $self->{_InParse} = 0; delete $self->{_NodeStack}; } #-------------------------------------------------------------------# #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,# #`,`, Expat Handlers ,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,# #```````````````````````````````````````````````````````````````````# #-------------------------------------------------------------------# # _handle_init #-------------------------------------------------------------------# sub _handle_init { #my $self = shift()->{__XSE}; #my $document = {}; #push @{$self->{_NodeStack}}, $document; #$self->SUPER::start_document($document); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_final #-------------------------------------------------------------------# sub _handle_final { my $self = shift()->{__XSE}; #my $document = pop @{$self->{_NodeStack}}; return $self->SUPER::end_document({}); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_start #-------------------------------------------------------------------# sub _handle_start { my $self = shift()->{__XSE}; my $e_name = shift; my %attr = @_; # start_document data $self->_handle_start_document({}) unless $self->{_started}; # take care of namespaces my $nsh = $self->{_NSHelper}; $nsh->push_context; my @new_ns; for my $k (grep !index($_, 'xmlns'), keys %attr) { $k =~ m/^xmlns(:(.*))?$/; my $prefix = $2 || ''; $nsh->declare_prefix($prefix, $attr{$k}); my $ns = { Prefix => $prefix, NamespaceURI => $attr{$k}, }; push @new_ns, $ns; $self->SUPER::start_prefix_mapping($ns); } push @{$self->{_NSStack}}, \@new_ns; # create the attributes my %saxattr; map { my ($ns,$prefix,$lname) = $nsh->process_attribute_name($_); $saxattr{'{' . ($ns || '') . '}' . $lname} = { Name => $_, LocalName => $lname || '', Prefix => $prefix || '', Value => $attr{$_}, NamespaceURI => $ns || '', }; } keys %attr; # now the element my ($ns,$prefix,$lname) = $nsh->process_element_name($e_name); my $element = { Name => $e_name, LocalName => $lname || '', Prefix => $prefix || '', NamespaceURI => $ns || '', Attributes => \%saxattr, }; push @{$self->{_NodeStack}}, $element; $self->SUPER::start_element($element); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_end #-------------------------------------------------------------------# sub _handle_end { my $self = shift()->{__XSE}; my %element = %{pop @{$self->{_NodeStack}}}; delete $element{Attributes}; $self->SUPER::end_element(\%element); my $prev_ns = pop @{$self->{_NSStack}}; for my $ns (@$prev_ns) { $self->SUPER::end_prefix_mapping( { %$ns } ); } $self->{_NSHelper}->pop_context; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_char #-------------------------------------------------------------------# sub _handle_char { $_[0]->{__XSE}->_handle_start_document({}) unless $_[0]->{__XSE}->{_started}; $_[0]->{__XSE}->SUPER::characters({ Data => $_[1] }); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_comment #-------------------------------------------------------------------# sub _handle_comment { $_[0]->{__XSE}->_handle_start_document({}) unless $_[0]->{__XSE}->{_started}; $_[0]->{__XSE}->SUPER::comment({ Data => $_[1] }); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_proc #-------------------------------------------------------------------# sub _handle_proc { $_[0]->{__XSE}->_handle_start_document({}) unless $_[0]->{__XSE}->{_started}; $_[0]->{__XSE}->SUPER::processing_instruction({ Target => $_[1], Data => $_[2] }); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_start_cdata #-------------------------------------------------------------------# sub _handle_start_cdata { $_[0]->{__XSE}->SUPER::start_cdata( {} ); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_end_cdata #-------------------------------------------------------------------# sub _handle_end_cdata { $_[0]->{__XSE}->SUPER::end_cdata( {} ); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_xml_decl #-------------------------------------------------------------------# sub _handle_xml_decl { my $self = shift()->{__XSE}; my $version = shift; my $encoding = shift; my $standalone = shift; if (not defined $standalone) { $standalone = ''; } elsif ($standalone) { $standalone = 'yes'; } else { $standalone = 'no'; } my $xd = { Version => $version, Encoding => $encoding, Standalone => $standalone, }; #$self->SUPER::xml_decl($xd); $self->_handle_start_document($xd); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_notation_decl #-------------------------------------------------------------------# sub _handle_notation_decl { my $self = shift()->{__XSE}; my $notation = shift; shift; my $system = shift; my $public = shift; my $not = { Name => $notation, PublicId => $public, SystemId => $system, }; $self->SUPER::notation_decl($not); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_unparsed_entity #-------------------------------------------------------------------# sub _handle_unparsed_entity { my $self = shift()->{__XSE}; my $name = shift; my $system = shift; my $public = shift; my $notation = shift; my $ue = { Name => $name, PublicId => $public, SystemId => $system, Notation => $notation, }; $self->SUPER::unparsed_entity_decl($ue); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_element_decl #-------------------------------------------------------------------# sub _handle_element_decl { $_[0]->{__XSE}->SUPER::element_decl({ Name => $_[1], Model => "$_[2]" }); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_attr_decl #-------------------------------------------------------------------# sub _handle_attr_decl { my $self = shift()->{__XSE}; my $ename = shift; my $aname = shift; my $type = shift; my $default = shift; my $fixed = shift; my ($vd, $value); if ($fixed) { $vd = '#FIXED'; $default =~ s/^(?:"|')//; #" $default =~ s/(?:"|')$//; #" $value = $default; } else { if ($default =~ m/^#/) { $vd = $default; $value = ''; } else { $vd = ''; # maybe there's a default ? $default =~ s/^(?:"|')//; #" $default =~ s/(?:"|')$//; #" $value = $default; } } my $at = { eName => $ename, aName => $aname, Type => $type, ValueDefault => $vd, Value => $value, }; $self->SUPER::attribute_decl($at); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_entity_decl #-------------------------------------------------------------------# sub _handle_entity_decl { my $self = shift()->{__XSE}; my $name = shift; my $val = shift; my $sys = shift; my $pub = shift; my $ndata = shift; my $isprm = shift; # deal with param ents if ($isprm) { $name = '%' . $name; } # int vs ext if ($val) { my $ent = { Name => $name, Value => $val, }; $self->SUPER::internal_entity_decl($ent); } else { my $ent = { Name => $name, PublicId => $pub || '', SystemId => $sys, }; $self->SUPER::external_entity_decl($ent); } } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_start_doctype #-------------------------------------------------------------------# sub _handle_start_doctype { my $self = shift()->{__XSE}; my $name = shift; my $sys = shift; my $pub = shift; $self->_handle_start_document({}) unless $self->{_started}; my $dtd = { Name => $name, SystemId => $sys, PublicId => $pub, }; $self->SUPER::start_dtd($dtd); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_end_doctype #-------------------------------------------------------------------# sub _handle_end_doctype { $_[0]->{__XSE}->SUPER::end_dtd( {} ); } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # _handle_start_document #-------------------------------------------------------------------# sub _handle_start_document { $_[0]->SUPER::start_document($_[1]); $_[0]->{_started} = 1; } #-------------------------------------------------------------------# #-------------------------------------------------------------------# # supported_features #-------------------------------------------------------------------# sub supported_features { return ( $_[0]->SUPER::supported_features, 'http://xml.org/sax/features/external-general-entities', 'http://xml.org/sax/features/external-parameter-entities', ); } #-------------------------------------------------------------------# #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,# #`,`, Private Helpers `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,# #```````````````````````````````````````````````````````````````````# #-------------------------------------------------------------------# # _create_node #-------------------------------------------------------------------# #sub _create_node { # shift; # # this may check for a factory later # return {@_}; #} #-------------------------------------------------------------------# 1; #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,# #`,`, Documentation `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,# #```````````````````````````````````````````````````````````````````# =pod =head1 NAME XML::SAX::Expat - SAX2 Driver for Expat (XML::Parser) =head1 SYNOPSIS use XML::SAX::Expat; use XML::SAX::MyFooHandler; my $h = XML::SAX::MyFooHandler->new; my $p = XML::SAX::Expat->new(Handler => $h); $p->parse_file('/path/to/foo.xml'); =head1 DESCRIPTION This is an implementation of a SAX2 driver sitting on top of Expat (XML::Parser) which Ken MacLeod posted to perl-xml and which I have updated. It is still incomplete, though most of the basic SAX2 events should be available. The SAX2 spec is currently available from L. A more friendly URL as well as a PODification of the spec are in the works. =head1 METHODS The methods defined in this class correspond to those listed in the PerlSAX2 specification, available above. =head1 FEATURES AND CAVEATS =over 2 =item supported_features Returns: * http://xml.org/sax/features/external-general-entities * http://xml.org/sax/features/external-parameter-entities * [ Features supported by ancestors ] Turning one of the first two on also turns the other on (this maps to the XML::Parser ParseParamEnts option). This may be fixed in the future, so don't rely on this behaviour. =back =head1 MISSING PARTS XML::Parser has no listed callbacks for the following events, which are therefore not presently generated (ways may be found in the future): * ignorable_whitespace * skipped_entity * start_entity / end_entity * resolve_entity Ways of signalling them are welcome. In addition to those, set_document_locator is not yet called. =head1 TODO - reuse Ken's tests and add more =head1 AUTHOR Robin Berjon; stolen from Ken Macleod, ken@bitsko.slc.ut.us, and with suggestions and feedback from perl-xml. Currently maintained by Bjoern Hoehrmann, L. =head1 COPYRIGHT AND LICENSE Copyright (c) 2001-2008 Robin Berjon. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO XML::Parser::PerlSAX =cut PK!íqËi‹‹perl5/XML/Simple.pmnuÏÃ6Ç$package XML::Simple; $XML::Simple::VERSION = '2.25'; =head1 NAME XML::Simple - An API for simple XML files =head1 SYNOPSIS PLEASE DO NOT USE THIS MODULE IN NEW CODE. If you ignore this warning and use it anyway, the C mode will save you a little pain. use XML::Simple qw(:strict); my $ref = XMLin([] [, ]); my $xml = XMLout($hashref [, ]); Or the object oriented way: require XML::Simple qw(:strict); my $xs = XML::Simple->new([]); my $ref = $xs->XMLin([] [, ]); my $xml = $xs->XMLout($hashref [, ]); (or see L<"SAX SUPPORT"> for 'the SAX way'). Note, in these examples, the square brackets are used to denote optional items not to imply items should be supplied in arrayrefs. =cut # See after __END__ for more POD documentation # Load essentials here, other modules loaded on demand later use strict; use warnings; use warnings::register; use Carp; use Scalar::Util qw(); require Exporter; ############################################################################## # Define some constants # use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $PREFERRED_PARSER); @ISA = qw(Exporter); @EXPORT = qw(XMLin XMLout); @EXPORT_OK = qw(xml_in xml_out); my %StrictMode = (); my @KnownOptIn = qw(keyattr keeproot forcecontent contentkey noattr searchpath forcearray cache suppressempty parseropts grouptags nsexpand datahandler varattr variables normalisespace normalizespace valueattr strictmode); my @KnownOptOut = qw(keyattr keeproot contentkey noattr rootname xmldecl outputfile noescape suppressempty grouptags nsexpand handler noindent attrindent nosort valueattr numericescape strictmode); my @DefKeyAttr = qw(name key id); my $DefRootName = qq(opt); my $DefContentKey = qq(content); my $DefXmlDecl = qq(); my $xmlns_ns = 'http://www.w3.org/2000/xmlns/'; my $bad_def_ns_jcn = '{' . $xmlns_ns . '}'; # LibXML::SAX workaround ############################################################################## # Globals for use by caching routines # my %MemShareCache = (); my %MemCopyCache = (); ############################################################################## # Wrapper for Exporter - handles ':strict' # sub import { # Handle the :strict tag my($calling_package) = caller(); _strict_mode_for_caller(1) if grep(/^:strict$/, @_); # Pass everything else to Exporter.pm @_ = grep(!/^:strict$/, @_); goto &Exporter::import; } ############################################################################## # Constructor for optional object interface. # sub new { my $class = shift; if(@_ % 2) { croak "Default options must be name=>value pairs (odd number supplied)"; } my %known_opt; @known_opt{@KnownOptIn, @KnownOptOut} = (); my %raw_opt = @_; $raw_opt{strictmode} = _strict_mode_for_caller() unless exists $raw_opt{strictmode}; my %def_opt; while(my($key, $val) = each %raw_opt) { my $lkey = lc($key); $lkey =~ s/_//g; croak "Unrecognised option: $key" unless(exists($known_opt{$lkey})); $def_opt{$lkey} = $val; } my $self = { def_opt => \%def_opt }; return(bless($self, $class)); } ############################################################################## # Sub: _strict_mode_for_caller() # # Gets or sets the XML::Simple :strict mode flag for the calling namespace. # Walks back through call stack to find the calling namespace and sets the # :strict mode flag for that namespace if an argument was supplied and returns # the flag value if not. # sub _strict_mode_for_caller { my $set_mode = @_; my $frame = 1; while(my($package) = caller($frame++)) { next if $package eq 'XML::Simple'; $StrictMode{$package} = 1 if $set_mode; return $StrictMode{$package}; } return(0); } ############################################################################## # Sub: _get_object() # # Helper routine called from XMLin() and XMLout() to create an object if none # was provided. Note, this routine does mess with the caller's @_ array. # sub _get_object { my $self; if($_[0] and UNIVERSAL::isa($_[0], 'XML::Simple')) { $self = shift; } else { $self = XML::Simple->new(); } return $self; } ############################################################################## # Sub/Method: XMLin() # # Exported routine for slurping XML into a hashref - see pod for info. # # May be called as object method or as a plain function. # # Expects one arg for the source XML, optionally followed by a number of # name => value option pairs. # sub XMLin { my $self = &_get_object; # note, @_ is passed implicitly my $target = shift; # Work out whether to parse a string, a file or a filehandle if(not defined $target) { return $self->parse_file(undef, @_); } elsif($target eq '-') { local($/) = undef; $target = ; return $self->parse_string(\$target, @_); } elsif(my $type = ref($target)) { if($type eq 'SCALAR') { return $self->parse_string($target, @_); } else { return $self->parse_fh($target, @_); } } elsif($target =~ m{<.*?>}s) { return $self->parse_string(\$target, @_); } else { return $self->parse_file($target, @_); } } ############################################################################## # Sub/Method: parse_file() # # Same as XMLin, but only parses from a named file. # sub parse_file { my $self = &_get_object; # note, @_ is passed implicitly my $filename = shift; $self->handle_options('in', @_); $filename = $self->default_config_file if not defined $filename; $filename = $self->find_xml_file($filename, @{$self->{opt}->{searchpath}}); # Check cache for previous parse if($self->{opt}->{cache}) { foreach my $scheme (@{$self->{opt}->{cache}}) { my $method = 'cache_read_' . $scheme; my $opt = $self->$method($filename); return($opt) if($opt); } } my $ref = $self->build_simple_tree($filename, undef); if($self->{opt}->{cache}) { my $method = 'cache_write_' . $self->{opt}->{cache}->[0]; $self->$method($ref, $filename); } return $ref; } ############################################################################## # Sub/Method: parse_fh() # # Same as XMLin, but only parses from a filehandle. # sub parse_fh { my $self = &_get_object; # note, @_ is passed implicitly my $fh = shift; croak "Can't use " . (defined $fh ? qq{string ("$fh")} : 'undef') . " as a filehandle" unless ref $fh; $self->handle_options('in', @_); return $self->build_simple_tree(undef, $fh); } ############################################################################## # Sub/Method: parse_string() # # Same as XMLin, but only parses from a string or a reference to a string. # sub parse_string { my $self = &_get_object; # note, @_ is passed implicitly my $string = shift; $self->handle_options('in', @_); return $self->build_simple_tree(undef, ref $string ? $string : \$string); } ############################################################################## # Method: default_config_file() # # Returns the name of the XML file to parse if no filename (or XML string) # was provided. # sub default_config_file { my $self = shift; require File::Basename; my($basename, $script_dir, $ext) = File::Basename::fileparse($0, '\.[^\.]+'); # Add script directory to searchpath if($script_dir) { unshift(@{$self->{opt}->{searchpath}}, $script_dir); } return $basename . '.xml'; } ############################################################################## # Method: build_simple_tree() # # Builds a 'tree' data structure as provided by XML::Parser and then # 'simplifies' it as specified by the various options in effect. # sub build_simple_tree { my $self = shift; my $tree = eval { $self->build_tree(@_); }; Carp::croak("$@XML::Simple called") if $@; return $self->{opt}->{keeproot} ? $self->collapse({}, @$tree) : $self->collapse(@{$tree->[1]}); } ############################################################################## # Method: build_tree() # # This routine will be called if there is no suitable pre-parsed tree in a # cache. It parses the XML and returns an XML::Parser 'Tree' style data # structure (summarised in the comments for the collapse() routine below). # # XML::Simple requires the services of another module that knows how to parse # XML. If XML::SAX is installed, the default SAX parser will be used, # otherwise XML::Parser will be used. # # This routine expects to be passed a filename as argument 1 or a 'string' as # argument 2. The 'string' might be a string of XML (passed by reference to # save memory) or it might be a reference to an IO::Handle. (This # non-intuitive mess results in part from the way XML::Parser works but that's # really no excuse). # sub build_tree { my $self = shift; my $filename = shift; my $string = shift; my $preferred_parser = $PREFERRED_PARSER; unless(defined($preferred_parser)) { $preferred_parser = $ENV{XML_SIMPLE_PREFERRED_PARSER} || ''; } if($preferred_parser eq 'XML::Parser') { return($self->build_tree_xml_parser($filename, $string)); } eval { require XML::SAX; }; # We didn't need it until now if($@) { # No XML::SAX - fall back to XML::Parser if($preferred_parser) { # unless a SAX parser was expressly requested croak "XMLin() could not load XML::SAX"; } return($self->build_tree_xml_parser($filename, $string)); } $XML::SAX::ParserPackage = $preferred_parser if($preferred_parser); my $sp = XML::SAX::ParserFactory->parser(Handler => $self); $self->{nocollapse} = 1; my($tree); if($filename) { $tree = $sp->parse_uri($filename); } else { if(ref($string) && ref($string) ne 'SCALAR') { $tree = $sp->parse_file($string); } else { $tree = $sp->parse_string($$string); } } return($tree); } ############################################################################## # Method: build_tree_xml_parser() # # This routine will be called if XML::SAX is not installed, or if XML::Parser # was specifically requested. It takes the same arguments as build_tree() and # returns the same data structure (XML::Parser 'Tree' style). # sub build_tree_xml_parser { my $self = shift; my $filename = shift; my $string = shift; eval { local($^W) = 0; # Suppress warning from Expat.pm re File::Spec::load() require XML::Parser; # We didn't need it until now }; if($@) { croak "XMLin() requires either XML::SAX or XML::Parser"; } if($self->{opt}->{nsexpand}) { carp "'nsexpand' option requires XML::SAX"; } my $xp = $self->new_xml_parser(); my($tree); if($filename) { # $tree = $xp->parsefile($filename); # Changed due to prob w/mod_perl open(my $xfh, '<', $filename) || croak qq($filename - $!); $tree = $xp->parse($xfh); } else { $tree = $xp->parse($$string); } return($tree); } ############################################################################## # Method: new_xml_parser() # # Simply calls the XML::Parser constructor. Override this method to customise # the behaviour of the parser. # sub new_xml_parser { my($self) = @_; my $xp = XML::Parser->new(Style => 'Tree', @{$self->{opt}->{parseropts}}); $xp->setHandlers(ExternEnt => sub {return $_[2]}); return $xp; } ############################################################################## # Method: cache_write_storable() # # Wrapper routine for invoking Storable::nstore() to cache a parsed data # structure. # sub cache_write_storable { my($self, $data, $filename) = @_; my $cachefile = $self->storable_filename($filename); require Storable; # We didn't need it until now if ('VMS' eq $^O) { Storable::nstore($data, $cachefile); } else { # If the following line fails for you, your Storable.pm is old - upgrade Storable::lock_nstore($data, $cachefile); } } ############################################################################## # Method: cache_read_storable() # # Wrapper routine for invoking Storable::retrieve() to read a cached parsed # data structure. Only returns cached data if the cache file exists and is # newer than the source XML file. # sub cache_read_storable { my($self, $filename) = @_; my $cachefile = $self->storable_filename($filename); return unless(-r $cachefile); return unless((stat($cachefile))[9] > (stat($filename))[9]); require Storable; # We didn't need it until now if ('VMS' eq $^O) { return(Storable::retrieve($cachefile)); } else { return(Storable::lock_retrieve($cachefile)); } } ############################################################################## # Method: storable_filename() # # Translates the supplied source XML filename into a filename for the storable # cached data. A '.stor' suffix is added after stripping an optional '.xml' # suffix. # sub storable_filename { my($self, $cachefile) = @_; $cachefile =~ s{(\.xml)?$}{.stor}; return $cachefile; } ############################################################################## # Method: cache_write_memshare() # # Takes the supplied data structure reference and stores it away in a global # hash structure. # sub cache_write_memshare { my($self, $data, $filename) = @_; $MemShareCache{$filename} = [time(), $data]; } ############################################################################## # Method: cache_read_memshare() # # Takes a filename and looks in a global hash for a cached parsed version. # sub cache_read_memshare { my($self, $filename) = @_; return unless($MemShareCache{$filename}); return unless($MemShareCache{$filename}->[0] > (stat($filename))[9]); return($MemShareCache{$filename}->[1]); } ############################################################################## # Method: cache_write_memcopy() # # Takes the supplied data structure and stores a copy of it in a global hash # structure. # sub cache_write_memcopy { my($self, $data, $filename) = @_; require Storable; # We didn't need it until now $MemCopyCache{$filename} = [time(), Storable::dclone($data)]; } ############################################################################## # Method: cache_read_memcopy() # # Takes a filename and looks in a global hash for a cached parsed version. # Returns a reference to a copy of that data structure. # sub cache_read_memcopy { my($self, $filename) = @_; return unless($MemCopyCache{$filename}); return unless($MemCopyCache{$filename}->[0] > (stat($filename))[9]); return(Storable::dclone($MemCopyCache{$filename}->[1])); } ############################################################################## # Sub/Method: XMLout() # # Exported routine for 'unslurping' a data structure out to XML. # # Expects a reference to a data structure and an optional list of option # name => value pairs. # sub XMLout { my $self = &_get_object; # note, @_ is passed implicitly croak "XMLout() requires at least one argument" unless(@_); my $ref = shift; $self->handle_options('out', @_); # If namespace expansion is set, XML::NamespaceSupport is required if($self->{opt}->{nsexpand}) { require XML::NamespaceSupport; $self->{nsup} = XML::NamespaceSupport->new(); $self->{ns_prefix} = 'aaa'; } # Wrap top level arrayref in a hash if(UNIVERSAL::isa($ref, 'ARRAY')) { $ref = { anon => $ref }; } # Extract rootname from top level hash if keeproot enabled if($self->{opt}->{keeproot}) { my(@keys) = keys(%$ref); if(@keys == 1) { $ref = $ref->{$keys[0]}; $self->{opt}->{rootname} = $keys[0]; } } # Ensure there are no top level attributes if we're not adding root elements elsif($self->{opt}->{rootname} eq '') { if(UNIVERSAL::isa($ref, 'HASH')) { my $refsave = $ref; $ref = {}; foreach (keys(%$refsave)) { if(ref($refsave->{$_})) { $ref->{$_} = $refsave->{$_}; } else { $ref->{$_} = [ $refsave->{$_} ]; } } } } # Encode the hashref and write to file if necessary $self->{_ancestors} = {}; my $xml = $self->value_to_xml($ref, $self->{opt}->{rootname}, ''); delete $self->{_ancestors}; if($self->{opt}->{xmldecl}) { $xml = $self->{opt}->{xmldecl} . "\n" . $xml; } if($self->{opt}->{outputfile}) { if(ref($self->{opt}->{outputfile})) { my $fh = $self->{opt}->{outputfile}; if(UNIVERSAL::isa($fh, 'GLOB') and !UNIVERSAL::can($fh, 'print')) { eval { require IO::Handle; }; croak $@ if $@; } return($fh->print($xml)); } else { open(my $out, '>', "$self->{opt}->{outputfile}") || croak "open($self->{opt}->{outputfile}): $!"; binmode($out, ':utf8') if($] >= 5.008); print $out $xml or croak "print: $!"; close $out or croak "close: $!"; } } elsif($self->{opt}->{handler}) { require XML::SAX; my $sp = XML::SAX::ParserFactory->parser( Handler => $self->{opt}->{handler} ); return($sp->parse_string($xml)); } else { return($xml); } } ############################################################################## # Method: handle_options() # # Helper routine for both XMLin() and XMLout(). Both routines handle their # first argument and assume all other args are options handled by this routine. # Saves a hash of options in $self->{opt}. # # If default options were passed to the constructor, they will be retrieved # here and merged with options supplied to the method call. # # First argument should be the string 'in' or the string 'out'. # # Remaining arguments should be name=>value pairs. Sets up default values # for options not supplied. Unrecognised options are a fatal error. # sub handle_options { my $self = shift; my $dirn = shift; # Determine valid options based on context my %known_opt; if($dirn eq 'in') { @known_opt{@KnownOptIn} = @KnownOptIn; } else { @known_opt{@KnownOptOut} = @KnownOptOut; } # Store supplied options in hashref and weed out invalid ones if(@_ % 2) { croak "Options must be name=>value pairs (odd number supplied)"; } my %raw_opt = @_; my $opt = {}; $self->{opt} = $opt; while(my($key, $val) = each %raw_opt) { my $lkey = lc($key); $lkey =~ s/_//g; croak "Unrecognised option: $key" unless($known_opt{$lkey}); $opt->{$lkey} = $val; } # Merge in options passed to constructor foreach (keys(%known_opt)) { unless(exists($opt->{$_})) { if(exists($self->{def_opt}->{$_})) { $opt->{$_} = $self->{def_opt}->{$_}; } } } # Set sensible defaults if not supplied if(exists($opt->{rootname})) { unless(defined($opt->{rootname})) { $opt->{rootname} = ''; } } else { $opt->{rootname} = $DefRootName; } if($opt->{xmldecl} and $opt->{xmldecl} eq '1') { $opt->{xmldecl} = $DefXmlDecl; } if(exists($opt->{contentkey})) { if($opt->{contentkey} =~ m{^-(.*)$}) { $opt->{contentkey} = $1; $opt->{collapseagain} = 1; } } else { $opt->{contentkey} = $DefContentKey; } unless(exists($opt->{normalisespace})) { $opt->{normalisespace} = $opt->{normalizespace}; } $opt->{normalisespace} = 0 unless(defined($opt->{normalisespace})); # Cleanups for values assumed to be arrays later if($opt->{searchpath}) { unless(ref($opt->{searchpath})) { $opt->{searchpath} = [ $opt->{searchpath} ]; } } else { $opt->{searchpath} = [ ]; } if($opt->{cache} and !ref($opt->{cache})) { $opt->{cache} = [ $opt->{cache} ]; } if($opt->{cache}) { $_ = lc($_) foreach (@{$opt->{cache}}); foreach my $scheme (@{$opt->{cache}}) { my $method = 'cache_read_' . $scheme; croak "Unsupported caching scheme: $scheme" unless($self->can($method)); } } if(exists($opt->{parseropts})) { if(warnings::enabled()) { carp "Warning: " . "'ParserOpts' is deprecated, contact the author if you need it"; } } else { $opt->{parseropts} = [ ]; } # Special cleanup for {forcearray} which could be regex, arrayref or boolean # or left to default to 0 if(exists($opt->{forcearray})) { if(ref($opt->{forcearray}) eq 'Regexp') { $opt->{forcearray} = [ $opt->{forcearray} ]; } if(ref($opt->{forcearray}) eq 'ARRAY') { my @force_list = @{$opt->{forcearray}}; if(@force_list) { $opt->{forcearray} = {}; foreach my $tag (@force_list) { if(ref($tag) eq 'Regexp') { push @{$opt->{forcearray}->{_regex}}, $tag; } else { $opt->{forcearray}->{$tag} = 1; } } } else { $opt->{forcearray} = 0; } } else { $opt->{forcearray} = ( $opt->{forcearray} ? 1 : 0 ); } } else { if($opt->{strictmode} and $dirn eq 'in') { croak "No value specified for 'ForceArray' option in call to XML$dirn()"; } $opt->{forcearray} = 0; } # Special cleanup for {keyattr} which could be arrayref or hashref or left # to default to arrayref if(exists($opt->{keyattr})) { if(ref($opt->{keyattr})) { if(ref($opt->{keyattr}) eq 'HASH') { # Make a copy so we can mess with it $opt->{keyattr} = { %{$opt->{keyattr}} }; # Convert keyattr => { elem => '+attr' } # to keyattr => { elem => [ 'attr', '+' ] } foreach my $el (keys(%{$opt->{keyattr}})) { if($opt->{keyattr}->{$el} =~ /^(\+|-)?(.*)$/) { $opt->{keyattr}->{$el} = [ $2, ($1 ? $1 : '') ]; if($opt->{strictmode} and $dirn eq 'in') { next if($opt->{forcearray} == 1); next if(ref($opt->{forcearray}) eq 'HASH' and $opt->{forcearray}->{$el}); croak "<$el> set in KeyAttr but not in ForceArray"; } } else { delete($opt->{keyattr}->{$el}); # Never reached (famous last words?) } } } else { if(@{$opt->{keyattr}} == 0) { delete($opt->{keyattr}); } } } else { $opt->{keyattr} = [ $opt->{keyattr} ]; } } else { if($opt->{strictmode}) { croak "No value specified for 'KeyAttr' option in call to XML$dirn()"; } $opt->{keyattr} = [ @DefKeyAttr ]; } # Special cleanup for {valueattr} which could be arrayref or hashref if(exists($opt->{valueattr})) { if(ref($opt->{valueattr}) eq 'ARRAY') { $opt->{valueattrlist} = {}; $opt->{valueattrlist}->{$_} = 1 foreach(@{ delete $opt->{valueattr} }); } } # make sure there's nothing weird in {grouptags} if($opt->{grouptags}) { croak "Illegal value for 'GroupTags' option - expected a hashref" unless UNIVERSAL::isa($opt->{grouptags}, 'HASH'); while(my($key, $val) = each %{$opt->{grouptags}}) { next if $key ne $val; croak "Bad value in GroupTags: '$key' => '$val'"; } } # Check the {variables} option is valid and initialise variables hash if($opt->{variables} and !UNIVERSAL::isa($opt->{variables}, 'HASH')) { croak "Illegal value for 'Variables' option - expected a hashref"; } if($opt->{variables}) { $self->{_var_values} = { %{$opt->{variables}} }; } elsif($opt->{varattr}) { $self->{_var_values} = {}; } } ############################################################################## # Method: find_xml_file() # # Helper routine for XMLin(). # Takes a filename, and a list of directories, attempts to locate the file in # the directories listed. # Returns a full pathname on success; croaks on failure. # sub find_xml_file { my $self = shift; my $file = shift; my @search_path = @_; require File::Basename; require File::Spec; my($filename, $filedir) = File::Basename::fileparse($file); if($filename ne $file) { # Ignore searchpath if dir component return($file) if(-e $file); } else { my($path); foreach $path (@search_path) { my $fullpath = File::Spec->catfile($path, $file); return($fullpath) if(-e $fullpath); } } # If user did not supply a search path, default to current directory if(!@search_path) { return($file) if(-e $file); croak "File does not exist: $file"; } croak "Could not find $file in ", join(':', @search_path); } ############################################################################## # Method: collapse() # # Helper routine for XMLin(). This routine really comprises the 'smarts' (or # value add) of this module. # # Takes the parse tree that XML::Parser produced from the supplied XML and # recurses through it 'collapsing' unnecessary levels of indirection (nested # arrays etc) to produce a data structure that is easier to work with. # # Elements in the original parser tree are represented as an element name # followed by an arrayref. The first element of the array is a hashref # containing the attributes. The rest of the array contains a list of any # nested elements as name+arrayref pairs: # # , [ { }, , [ ... ], ... ] # # The special element name '0' (zero) flags text content. # # This routine cuts down the noise by discarding any text content consisting of # only whitespace and then moves the nested elements into the attribute hash # using the name of the nested element as the hash key and the collapsed # version of the nested element as the value. Multiple nested elements with # the same name will initially be represented as an arrayref, but this may be # 'folded' into a hashref depending on the value of the keyattr option. # sub collapse { my $self = shift; # Start with the hash of attributes my $attr = shift; if($self->{opt}->{noattr}) { # Discard if 'noattr' set $attr = $self->new_hashref; } elsif($self->{opt}->{normalisespace} == 2) { while(my($key, $value) = each %$attr) { $attr->{$key} = $self->normalise_space($value) } } # Do variable substitutions if(my $var = $self->{_var_values}) { while(my($key, $val) = each(%$attr)) { $val =~ s^\$\{([\w.]+)\}^ $self->get_var($1) ^ge; $attr->{$key} = $val; } } # Roll up 'value' attributes (but only if no nested elements) if(!@_ and keys %$attr == 1) { my($k) = keys %$attr; if($self->{opt}->{valueattrlist} and $self->{opt}->{valueattrlist}->{$k}) { return $attr->{$k}; } } # Add any nested elements my($key, $val); while(@_) { $key = shift; $val = shift; $val = '' if not defined $val; if(ref($val)) { $val = $self->collapse(@$val); next if(!defined($val) and $self->{opt}->{suppressempty}); } elsif($key eq '0') { next if($val =~ m{^\s*$}s); # Skip all whitespace content $val = $self->normalise_space($val) if($self->{opt}->{normalisespace} == 2); # do variable substitutions if(my $var = $self->{_var_values}) { $val =~ s^\$\{(\w+)\}^ $self->get_var($1) ^ge; } # look for variable definitions if(my $var = $self->{opt}->{varattr}) { if(exists $attr->{$var}) { $self->set_var($attr->{$var}, $val); } } # Collapse text content in element with no attributes to a string if(!%$attr and !@_) { return($self->{opt}->{forcecontent} ? { $self->{opt}->{contentkey} => $val } : $val ); } $key = $self->{opt}->{contentkey}; } # Combine duplicate attributes into arrayref if required if(exists($attr->{$key})) { if(UNIVERSAL::isa($attr->{$key}, 'ARRAY')) { push(@{$attr->{$key}}, $val); } else { $attr->{$key} = [ $attr->{$key}, $val ]; } } elsif(defined($val) and UNIVERSAL::isa($val, 'ARRAY')) { $attr->{$key} = [ $val ]; } else { if( $key ne $self->{opt}->{contentkey} and ( ($self->{opt}->{forcearray} == 1) or ( (ref($self->{opt}->{forcearray}) eq 'HASH') and ( $self->{opt}->{forcearray}->{$key} or (grep $key =~ $_, @{$self->{opt}->{forcearray}->{_regex}}) ) ) ) ) { $attr->{$key} = [ $val ]; } else { $attr->{$key} = $val; } } } # Turn arrayrefs into hashrefs if key fields present if($self->{opt}->{keyattr}) { while(($key,$val) = each %$attr) { if(defined($val) and UNIVERSAL::isa($val, 'ARRAY')) { $attr->{$key} = $self->array_to_hash($key, $val); } } } # disintermediate grouped tags if($self->{opt}->{grouptags}) { while(my($key, $val) = each(%$attr)) { next unless(UNIVERSAL::isa($val, 'HASH') and (keys %$val == 1)); next unless(exists($self->{opt}->{grouptags}->{$key})); my($child_key, $child_val) = %$val; if($self->{opt}->{grouptags}->{$key} eq $child_key) { $attr->{$key}= $child_val; } } } # Fold hashes containing a single anonymous array up into just the array my $count = scalar keys %$attr; if($count == 1 and exists $attr->{anon} and UNIVERSAL::isa($attr->{anon}, 'ARRAY') ) { return($attr->{anon}); } # Do the right thing if hash is empty, otherwise just return it if(!%$attr and exists($self->{opt}->{suppressempty})) { if(defined($self->{opt}->{suppressempty}) and $self->{opt}->{suppressempty} eq '') { return(''); } return(undef); } # Roll up named elements with named nested 'value' attributes if($self->{opt}->{valueattr}) { while(my($key, $val) = each(%$attr)) { next unless($self->{opt}->{valueattr}->{$key}); next unless(UNIVERSAL::isa($val, 'HASH') and (keys %$val == 1)); my($k) = keys %$val; next unless($k eq $self->{opt}->{valueattr}->{$key}); $attr->{$key} = $val->{$k}; } } return($attr) } ############################################################################## # Method: set_var() # # Called when a variable definition is encountered in the XML. (A variable # definition looks like value where attrname # matches the varattr setting). # sub set_var { my($self, $name, $value) = @_; $self->{_var_values}->{$name} = $value; } ############################################################################## # Method: get_var() # # Called during variable substitution to get the value for the named variable. # sub get_var { my($self, $name) = @_; my $value = $self->{_var_values}->{$name}; return $value if(defined($value)); return '${' . $name . '}'; } ############################################################################## # Method: normalise_space() # # Strips leading and trailing whitespace and collapses sequences of whitespace # characters to a single space. # sub normalise_space { my($self, $text) = @_; $text =~ s/^\s+//s; $text =~ s/\s+$//s; $text =~ s/\s\s+/ /sg; return $text; } ############################################################################## # Method: array_to_hash() # # Helper routine for collapse(). # Attempts to 'fold' an array of hashes into an hash of hashes. Returns a # reference to the hash on success or the original array if folding is # not possible. Behaviour is controlled by 'keyattr' option. # sub array_to_hash { my $self = shift; my $name = shift; my $arrayref = shift; my $hashref = $self->new_hashref; my($i, $key, $val, $flag); # Handle keyattr => { .... } if(ref($self->{opt}->{keyattr}) eq 'HASH') { return($arrayref) unless(exists($self->{opt}->{keyattr}->{$name})); ($key, $flag) = @{$self->{opt}->{keyattr}->{$name}}; for($i = 0; $i < @$arrayref; $i++) { if(UNIVERSAL::isa($arrayref->[$i], 'HASH') and exists($arrayref->[$i]->{$key}) ) { $val = $arrayref->[$i]->{$key}; if(ref($val)) { $self->die_or_warn("<$name> element has non-scalar '$key' key attribute"); return($arrayref); } $val = $self->normalise_space($val) if($self->{opt}->{normalisespace} == 1); $self->die_or_warn("<$name> element has non-unique value in '$key' key attribute: $val") if(exists($hashref->{$val})); $hashref->{$val} = $self->new_hashref( %{$arrayref->[$i]} ); $hashref->{$val}->{"-$key"} = $hashref->{$val}->{$key} if($flag eq '-'); delete $hashref->{$val}->{$key} unless($flag eq '+'); } else { $self->die_or_warn("<$name> element has no '$key' key attribute"); return($arrayref); } } } # Or assume keyattr => [ .... ] else { my $default_keys = join(',', @DefKeyAttr) eq join(',', @{$self->{opt}->{keyattr}}); ELEMENT: for($i = 0; $i < @$arrayref; $i++) { return($arrayref) unless(UNIVERSAL::isa($arrayref->[$i], 'HASH')); foreach $key (@{$self->{opt}->{keyattr}}) { if(defined($arrayref->[$i]->{$key})) { $val = $arrayref->[$i]->{$key}; if(ref($val)) { $self->die_or_warn("<$name> element has non-scalar '$key' key attribute") if not $default_keys; return($arrayref); } $val = $self->normalise_space($val) if($self->{opt}->{normalisespace} == 1); $self->die_or_warn("<$name> element has non-unique value in '$key' key attribute: $val") if(exists($hashref->{$val})); $hashref->{$val} = $self->new_hashref( %{$arrayref->[$i]} ); delete $hashref->{$val}->{$key}; next ELEMENT; } } return($arrayref); # No keyfield matched } } # collapse any hashes which now only have a 'content' key if($self->{opt}->{collapseagain}) { $hashref = $self->collapse_content($hashref); } return($hashref); } ############################################################################## # Method: die_or_warn() # # Takes a diagnostic message and does one of three things: # 1. dies if strict mode is enabled # 2. warns if warnings are enabled but strict mode is not # 3. ignores message and returns silently if neither strict mode nor warnings # are enabled # sub die_or_warn { my $self = shift; my $msg = shift; croak $msg if($self->{opt}->{strictmode}); if(warnings::enabled()) { carp "Warning: $msg"; } } ############################################################################## # Method: new_hashref() # # This is a hook routine for overriding in a sub-class. Some people believe # that using Tie::IxHash here will solve order-loss problems. # sub new_hashref { my $self = shift; return { @_ }; } ############################################################################## # Method: collapse_content() # # Helper routine for array_to_hash # # Arguments expected are: # - an XML::Simple object # - a hashref # the hashref is a former array, turned into a hash by array_to_hash because # of the presence of key attributes # at this point collapse_content avoids over-complicated structures like # dir => { libexecdir => { content => '$exec_prefix/libexec' }, # localstatedir => { content => '$prefix' }, # } # into # dir => { libexecdir => '$exec_prefix/libexec', # localstatedir => '$prefix', # } sub collapse_content { my $self = shift; my $hashref = shift; my $contentkey = $self->{opt}->{contentkey}; # first go through the values,checking that they are fit to collapse foreach my $val (values %$hashref) { return $hashref unless ( (ref($val) eq 'HASH') and (keys %$val == 1) and (exists $val->{$contentkey}) ); } # now collapse them foreach my $key (keys %$hashref) { $hashref->{$key}= $hashref->{$key}->{$contentkey}; } return $hashref; } ############################################################################## # Method: value_to_xml() # # Helper routine for XMLout() - recurses through a data structure building up # and returning an XML representation of that structure as a string. # # Arguments expected are: # - the data structure to be encoded (usually a reference) # - the XML tag name to use for this item # - a string of spaces for use as the current indent level # sub value_to_xml { my $self = shift;; # Grab the other arguments my($ref, $name, $indent) = @_; my $named = (defined($name) and $name ne '' ? 1 : 0); my $nl = "\n"; my $is_root = $indent eq '' ? 1 : 0; # Warning, dirty hack! if($self->{opt}->{noindent}) { $indent = ''; $nl = ''; } # Convert to XML my $refaddr = Scalar::Util::refaddr($ref); if($refaddr) { croak "circular data structures not supported" if $self->{_ancestors}->{$refaddr}; $self->{_ancestors}->{$refaddr} = $ref; # keep ref alive until we delete it } else { if($named) { return(join('', $indent, '<', $name, '>', ($self->{opt}->{noescape} ? $ref : $self->escape_value($ref)), '", $nl )); } else { return("$ref$nl"); } } # Unfold hash to array if possible if(UNIVERSAL::isa($ref, 'HASH') # It is a hash and keys %$ref # and it's not empty and $self->{opt}->{keyattr} # and folding is enabled and !$is_root # and its not the root element ) { $ref = $self->hash_to_array($name, $ref); } my @result = (); my($key, $value); # Handle hashrefs if(UNIVERSAL::isa($ref, 'HASH')) { # Reintermediate grouped values if applicable if($self->{opt}->{grouptags}) { $ref = $self->copy_hash($ref); while(my($key, $val) = each %$ref) { if($self->{opt}->{grouptags}->{$key}) { $ref->{$key} = $self->new_hashref( $self->{opt}->{grouptags}->{$key} => $val ); } } } # Scan for namespace declaration attributes my $nsdecls = ''; my $default_ns_uri; if($self->{nsup}) { $ref = $self->copy_hash($ref); $self->{nsup}->push_context(); # Look for default namespace declaration first if(exists($ref->{xmlns})) { $self->{nsup}->declare_prefix('', $ref->{xmlns}); $nsdecls .= qq( xmlns="$ref->{xmlns}"); delete($ref->{xmlns}); } $default_ns_uri = $self->{nsup}->get_uri(''); # Then check all the other keys foreach my $qname (keys(%$ref)) { my($uri, $lname) = $self->{nsup}->parse_jclark_notation($qname); if($uri) { if($uri eq $xmlns_ns) { $self->{nsup}->declare_prefix($lname, $ref->{$qname}); $nsdecls .= qq( xmlns:$lname="$ref->{$qname}"); delete($ref->{$qname}); } } } # Translate any remaining Clarkian names foreach my $qname (keys(%$ref)) { my($uri, $lname) = $self->{nsup}->parse_jclark_notation($qname); if($uri) { if($default_ns_uri and $uri eq $default_ns_uri) { $ref->{$lname} = $ref->{$qname}; delete($ref->{$qname}); } else { my $prefix = $self->{nsup}->get_prefix($uri); unless($prefix) { # $self->{nsup}->declare_prefix(undef, $uri); # $prefix = $self->{nsup}->get_prefix($uri); $prefix = $self->{ns_prefix}++; $self->{nsup}->declare_prefix($prefix, $uri); $nsdecls .= qq( xmlns:$prefix="$uri"); } $ref->{"$prefix:$lname"} = $ref->{$qname}; delete($ref->{$qname}); } } } } my @nested = (); my $text_content = undef; if($named) { push @result, $indent, '<', $name, $nsdecls; } if(keys %$ref) { my $first_arg = 1; foreach my $key ($self->sorted_keys($name, $ref)) { my $value = $ref->{$key}; next if(substr($key, 0, 1) eq '-'); if(!defined($value)) { next if $self->{opt}->{suppressempty}; unless(exists($self->{opt}->{suppressempty}) and !defined($self->{opt}->{suppressempty}) ) { carp 'Use of uninitialized value' if warnings::enabled(); } if($key eq $self->{opt}->{contentkey}) { $text_content = ''; } else { $value = exists($self->{opt}->{suppressempty}) ? {} : ''; } } if(!ref($value) and $self->{opt}->{valueattr} and $self->{opt}->{valueattr}->{$key} ) { $value = $self->new_hashref( $self->{opt}->{valueattr}->{$key} => $value ); } if(ref($value) or $self->{opt}->{noattr}) { push @nested, $self->value_to_xml($value, $key, "$indent "); } else { if($key eq $self->{opt}->{contentkey}) { $value = $self->escape_value($value) unless($self->{opt}->{noescape}); $text_content = $value; } else { $value = $self->escape_attr($value) unless($self->{opt}->{noescape}); push @result, "\n$indent " . ' ' x length($name) if($self->{opt}->{attrindent} and !$first_arg); push @result, ' ', $key, '="', $value , '"'; $first_arg = 0; } } } } else { $text_content = ''; } if(@nested or defined($text_content)) { if($named) { push @result, ">"; if(defined($text_content)) { push @result, $text_content; $nested[0] =~ s/^\s+// if(@nested); } else { push @result, $nl; } if(@nested) { push @result, @nested, $indent; } push @result, '", $nl; } else { push @result, @nested; # Special case if no root elements } } else { push @result, " />", $nl; } $self->{nsup}->pop_context() if($self->{nsup}); } # Handle arrayrefs elsif(UNIVERSAL::isa($ref, 'ARRAY')) { foreach $value (@$ref) { next if !defined($value) and $self->{opt}->{suppressempty}; if(!ref($value)) { push @result, $indent, '<', $name, '>', ($self->{opt}->{noescape} ? $value : $self->escape_value($value)), '$nl"; } elsif(UNIVERSAL::isa($value, 'HASH')) { push @result, $self->value_to_xml($value, $name, $indent); } else { push @result, $indent, '<', $name, ">$nl", $self->value_to_xml($value, 'anon', "$indent "), $indent, '$nl"; } } } else { croak "Can't encode a value of type: " . ref($ref); } delete $self->{_ancestors}->{$refaddr}; return(join('', @result)); } ############################################################################## # Method: sorted_keys() # # Returns the keys of the referenced hash sorted into alphabetical order, but # with the 'key' key (as in KeyAttr) first, if there is one. # sub sorted_keys { my($self, $name, $ref) = @_; return keys %$ref if $self->{opt}->{nosort}; my %hash = %$ref; my $keyattr = $self->{opt}->{keyattr}; my @key; if(ref $keyattr eq 'HASH') { if(exists $keyattr->{$name} and exists $hash{$keyattr->{$name}->[0]}) { push @key, $keyattr->{$name}->[0]; delete $hash{$keyattr->{$name}->[0]}; } } elsif(ref $keyattr eq 'ARRAY') { foreach (@{$keyattr}) { if(exists $hash{$_}) { push @key, $_; delete $hash{$_}; last; } } } return(@key, sort keys %hash); } ############################################################################## # Method: escape_value() # # Helper routine for automatically escaping values for XMLout(). # Expects a scalar data value. Returns escaped version. # sub escape_value { my($self, $data) = @_; return '' unless(defined($data)); $data =~ s/&/&/sg; $data =~ s//>/sg; $data =~ s/"/"/sg; my $level = $self->{opt}->{numericescape} or return $data; return $self->numeric_escape($data, $level); } sub numeric_escape { my($self, $data, $level) = @_; if($self->{opt}->{numericescape} eq '2') { $data =~ s/([^\x00-\x7F])/'&#' . ord($1) . ';'/gse; } else { $data =~ s/([^\x00-\xFF])/'&#' . ord($1) . ';'/gse; } return $data; } ############################################################################## # Method: escape_attr() # # Helper routine for escaping attribute values. Defaults to escape_value(), # but may be overridden by a subclass to customise behaviour. # sub escape_attr { my $self = shift; return $self->escape_value(@_); } ############################################################################## # Method: hash_to_array() # # Helper routine for value_to_xml(). # Attempts to 'unfold' a hash of hashes into an array of hashes. Returns a # reference to the array on success or the original hash if unfolding is # not possible. # sub hash_to_array { my $self = shift; my $parent = shift; my $hashref = shift; my $arrayref = []; my($key, $value); my @keys = $self->{opt}->{nosort} ? keys %$hashref : sort keys %$hashref; foreach $key (@keys) { $value = $hashref->{$key}; return($hashref) unless(UNIVERSAL::isa($value, 'HASH')); if(ref($self->{opt}->{keyattr}) eq 'HASH') { return($hashref) unless(defined($self->{opt}->{keyattr}->{$parent})); push @$arrayref, $self->copy_hash( $value, $self->{opt}->{keyattr}->{$parent}->[0] => $key ); } else { push(@$arrayref, { $self->{opt}->{keyattr}->[0] => $key, %$value }); } } return($arrayref); } ############################################################################## # Method: copy_hash() # # Helper routine for hash_to_array(). When unfolding a hash of hashes into # an array of hashes, we need to copy the key from the outer hash into the # inner hash. This routine makes a copy of the original hash so we don't # destroy the original data structure. You might wish to override this # method if you're using tied hashes and don't want them to get untied. # sub copy_hash { my($self, $orig, @extra) = @_; return { @extra, %$orig }; } ############################################################################## # Methods required for building trees from SAX events ############################################################################## sub start_document { my $self = shift; $self->handle_options('in') unless($self->{opt}); $self->{lists} = []; $self->{curlist} = $self->{tree} = []; } sub start_element { my $self = shift; my $element = shift; my $name = $element->{Name}; if($self->{opt}->{nsexpand}) { $name = $element->{LocalName} || ''; if($element->{NamespaceURI}) { $name = '{' . $element->{NamespaceURI} . '}' . $name; } } my $attributes = {}; if($element->{Attributes}) { # Might be undef foreach my $attr (values %{$element->{Attributes}}) { if($self->{opt}->{nsexpand}) { my $name = $attr->{LocalName} || ''; if($attr->{NamespaceURI}) { $name = '{' . $attr->{NamespaceURI} . '}' . $name } $name = 'xmlns' if($name eq $bad_def_ns_jcn); $attributes->{$name} = $attr->{Value}; } else { $attributes->{$attr->{Name}} = $attr->{Value}; } } } my $newlist = [ $attributes ]; push @{ $self->{lists} }, $self->{curlist}; push @{ $self->{curlist} }, $name => $newlist; $self->{curlist} = $newlist; } sub characters { my $self = shift; my $chars = shift; my $text = $chars->{Data}; my $clist = $self->{curlist}; my $pos = $#$clist; if ($pos > 0 and $clist->[$pos - 1] eq '0') { $clist->[$pos] .= $text; } else { push @$clist, 0 => $text; } } sub end_element { my $self = shift; $self->{curlist} = pop @{ $self->{lists} }; } sub end_document { my $self = shift; delete($self->{curlist}); delete($self->{lists}); my $tree = $self->{tree}; delete($self->{tree}); # Return tree as-is to XMLin() return($tree) if($self->{nocollapse}); # Or collapse it before returning it to SAX parser class if($self->{opt}->{keeproot}) { $tree = $self->collapse({}, @$tree); } else { $tree = $self->collapse(@{$tree->[1]}); } if($self->{opt}->{datahandler}) { return($self->{opt}->{datahandler}->($self, $tree)); } return($tree); } *xml_in = \&XMLin; *xml_out = \&XMLout; 1; __END__ =head1 STATUS OF THIS MODULE The use of this module in new code is B. Other modules are available which provide more straightforward and consistent interfaces. In particular, L is highly recommended and you can refer to L for a tutorial introduction. L is another excellent alternative. The major problems with this module are the large number of options (some of which have unfortunate defaults) and the arbitrary ways in which these options interact - often producing unexpected results. Patches with bug fixes and documentation fixes are welcome, but new features are unlikely to be added. =head1 QUICK START Say you have a script called B and a file of configuration options called B containing the following:
10.0.0.101
10.0.1.101
10.0.0.102
10.0.0.103
10.0.1.103
The following lines of code in B: use XML::Simple qw(:strict); my $config = XMLin(undef, KeyAttr => { server => 'name' }, ForceArray => [ 'server', 'address' ]); will 'slurp' the configuration options into the hashref $config (because no filename or XML string was passed as the first argument to C the name and location of the XML file will be inferred from name and location of the script). You can dump out the contents of the hashref using Data::Dumper: use Data::Dumper; print Dumper($config); which will produce something like this (formatting has been adjusted for brevity): { 'logdir' => '/var/log/foo/', 'debugfile' => '/tmp/foo.debug', 'server' => { 'sahara' => { 'osversion' => '2.6', 'osname' => 'solaris', 'address' => [ '10.0.0.101', '10.0.1.101' ] }, 'gobi' => { 'osversion' => '6.5', 'osname' => 'irix', 'address' => [ '10.0.0.102' ] }, 'kalahari' => { 'osversion' => '2.0.34', 'osname' => 'linux', 'address' => [ '10.0.0.103', '10.0.1.103' ] } } } Your script could then access the name of the log directory like this: print $config->{logdir}; similarly, the second address on the server 'kalahari' could be referenced as: print $config->{server}->{kalahari}->{address}->[1]; Note: If the mapping between the output of Data::Dumper and the print statements above is not obvious to you, then please refer to the 'references' tutorial (AKA: "Mark's very short tutorial about references") at L. In this example, the C<< ForceArray >> option was used to list elements that might occur multiple times and should therefore be represented as arrayrefs (even when only one element is present). The C<< KeyAttr >> option was used to indicate that each C<< >> element has a unique identifier in the C<< name >> attribute. This allows you to index directly to a particular server record using the name as a hash key (as shown above). For simple requirements, that's really all there is to it. If you want to store your XML in a different directory or file, or pass it in as a string or even pass it in via some derivative of an IO::Handle, you'll need to check out L<"OPTIONS">. If you want to turn off or tweak the array folding feature (that neat little transformation that produced $config->{server}) you'll find options for that as well. If you want to generate XML (for example to write a modified version of $config back out as XML), check out C. If your needs are not so simple, this may not be the module for you. In that case, you might want to read L<"WHERE TO FROM HERE?">. =head1 DESCRIPTION The XML::Simple module provides a simple API layer on top of an underlying XML parsing module (either XML::Parser or one of the SAX2 parser modules). Two functions are exported: C and C. Note: you can explicitly request the lower case versions of the function names: C and C. The simplest approach is to call these two functions directly, but an optional object oriented interface (see L<"OPTIONAL OO INTERFACE"> below) allows them to be called as methods of an B object. The object interface can also be used at either end of a SAX pipeline. =head2 XMLin() Parses XML formatted data and returns a reference to a data structure which contains the same information in a more readily accessible form. (Skip down to L<"EXAMPLES"> below, for more sample code). C accepts an optional XML specifier followed by zero or more 'name => value' option pairs. The XML specifier can be one of the following: =over 4 =item A filename If the filename contains no directory components C will look for the file in each directory in the SearchPath (see L<"OPTIONS"> below) or in the current directory if the SearchPath option is not defined. eg: $ref = XMLin('/etc/params.xml'); Note, the filename '-' can be used to parse from STDIN. =item undef If there is no XML specifier, C will check the script directory and each of the SearchPath directories for a file with the same name as the script but with the extension '.xml'. Note: if you wish to specify options, you must specify the value 'undef'. eg: $ref = XMLin(undef, ForceArray => 1); =item A string of XML A string containing XML (recognised by the presence of '<' and '>' characters) will be parsed directly. eg: $ref = XMLin(''); =item An IO::Handle object An IO::Handle object will be read to EOF and its contents parsed. eg: $fh = IO::File->new('/etc/params.xml'); $ref = XMLin($fh); =back =head2 XMLout() Takes a data structure (generally a hashref) and returns an XML encoding of that structure. If the resulting XML is parsed using C, it should return a data structure equivalent to the original (see caveats below). The C function can also be used to output the XML as SAX events see the C option and L<"SAX SUPPORT"> for more details). When translating hashes to XML, hash keys which have a leading '-' will be silently skipped. This is the approved method for marking elements of a data structure which should be ignored by C. (Note: If these items were not skipped the key names would be emitted as element or attribute names with a leading '-' which would not be valid XML). =head2 Caveats Some care is required in creating data structures which will be passed to C. Hash keys from the data structure will be encoded as either XML element names or attribute names. Therefore, you should use hash key names which conform to the relatively strict XML naming rules: Names in XML must begin with a letter. The remaining characters may be letters, digits, hyphens (-), underscores (_) or full stops (.). It is also allowable to include one colon (:) in an element name but this should only be used when working with namespaces (B can only usefully work with namespaces when teamed with a SAX Parser). You can use other punctuation characters in hash values (just not in hash keys) however B does not support dumping binary data. If you break these rules, the current implementation of C will simply emit non-compliant XML which will be rejected if you try to read it back in. (A later version of B might take a more proactive approach). Note also that although you can nest hashes and arrays to arbitrary levels, circular data structures are not supported and will cause C to die. If you wish to 'round-trip' arbitrary data structures from Perl to XML and back to Perl, then you should probably disable array folding (using the KeyAttr option) both with C and with C. If you still don't get the expected results, you may prefer to use L which is designed for exactly that purpose. Refer to L<"WHERE TO FROM HERE?"> if C is too simple for your needs. =head1 OPTIONS B supports a number of options (in fact as each release of B adds more options, the module's claim to the name 'Simple' becomes increasingly tenuous). If you find yourself repeatedly having to specify the same options, you might like to investigate L<"OPTIONAL OO INTERFACE"> below. If you can't be bothered reading the documentation, refer to L<"STRICT MODE"> to automatically catch common mistakes. Because there are so many options, it's hard for new users to know which ones are important, so here are the two you really need to know about: =over 4 =item * check out C because you'll almost certainly want to turn it on =item * make sure you know what the C option does and what its default value is because it may surprise you otherwise (note in particular that 'KeyAttr' affects both C and C) =back The option name headings below have a trailing 'comment' - a hash followed by two pieces of metadata: =over 4 =item * Options are marked with 'I' if they are recognised by C and 'I' if they are recognised by C. =item * Each option is also flagged to indicate whether it is: 'important' - don't use the module until you understand this one 'handy' - you can skip this on the first time through 'advanced' - you can skip this on the second time through 'SAX only' - don't worry about this unless you're using SAX (or alternatively if you need this, you also need SAX) 'seldom used' - you'll probably never use this unless you were the person that requested the feature =back The options are listed alphabetically: Note: option names are no longer case sensitive so you can use the mixed case versions shown here; all lower case as required by versions 2.03 and earlier; or you can add underscores between the words (eg: key_attr). =head2 AttrIndent => 1 I<# out - handy> When you are using C, enable this option to have attributes printed one-per-line with sensible indentation rather than all on one line. =head2 Cache => [ cache schemes ] I<# in - advanced> Because loading the B module and parsing an XML file can consume a significant number of CPU cycles, it is often desirable to cache the output of C for later reuse. When parsing from a named file, B supports a number of caching schemes. The 'Cache' option may be used to specify one or more schemes (using an anonymous array). Each scheme will be tried in turn in the hope of finding a cached pre-parsed representation of the XML file. If no cached copy is found, the file will be parsed and the first cache scheme in the list will be used to save a copy of the results. The following cache schemes have been implemented: =over 4 =item storable Utilises B to read/write a cache file with the same name as the XML file but with the extension .stor =item memshare When a file is first parsed, a copy of the resulting data structure is retained in memory in the B module's namespace. Subsequent calls to parse the same file will return a reference to this structure. This cached version will persist only for the life of the Perl interpreter (which in the case of mod_perl for example, may be some significant time). Because each caller receives a reference to the same data structure, a change made by one caller will be visible to all. For this reason, the reference returned should be treated as read-only. =item memcopy This scheme works identically to 'memshare' (above) except that each caller receives a reference to a new data structure which is a copy of the cached version. Copying the data structure will add a little processing overhead, therefore this scheme should only be used where the caller intends to modify the data structure (or wishes to protect itself from others who might). This scheme uses B to perform the copy. =back Warning! The memory-based caching schemes compare the timestamp on the file to the time when it was last parsed. If the file is stored on an NFS filesystem (or other network share) and the clock on the file server is not exactly synchronised with the clock where your script is run, updates to the source XML file may appear to be ignored. =head2 ContentKey => 'keyname' I<# in+out - seldom used> When text content is parsed to a hash value, this option lets you specify a name for the hash key to override the default 'content'. So for example: XMLin('Text', ContentKey => 'text') will parse to: { 'one' => 1, 'text' => 'Text' } instead of: { 'one' => 1, 'content' => 'Text' } C will also honour the value of this option when converting a hashref to XML. You can also prefix your selected key name with a '-' character to have C try a little harder to eliminate unnecessary 'content' keys after array folding. For example: XMLin( 'FirstSecond', KeyAttr => {item => 'name'}, ForceArray => [ 'item' ], ContentKey => '-content' ) will parse to: { 'item' => { 'one' => 'First' 'two' => 'Second' } } rather than this (without the '-'): { 'item' => { 'one' => { 'content' => 'First' } 'two' => { 'content' => 'Second' } } } =head2 DataHandler => code_ref I<# in - SAX only> When you use an B object as a SAX handler, it will return a 'simple tree' data structure in the same format as C would return. If this option is set (to a subroutine reference), then when the tree is built the subroutine will be called and passed two arguments: a reference to the B object and a reference to the data tree. The return value from the subroutine will be returned to the SAX driver. (See L<"SAX SUPPORT"> for more details). =head2 ForceArray => 1 I<# in - important> This option should be set to '1' to force nested elements to be represented as arrays even when there is only one. Eg, with ForceArray enabled, this XML: value would parse to this: { 'name' => [ 'value' ] } instead of this (the default): { 'name' => 'value' } This option is especially useful if the data structure is likely to be written back out as XML and the default behaviour of rolling single nested elements up into attributes is not desirable. If you are using the array folding feature, you should almost certainly enable this option. If you do not, single nested elements will not be parsed to arrays and therefore will not be candidates for folding to a hash. (Given that the default value of 'KeyAttr' enables array folding, the default value of this option should probably also have been enabled too - sorry). =head2 ForceArray => [ names ] I<# in - important> This alternative (and preferred) form of the 'ForceArray' option allows you to specify a list of element names which should always be forced into an array representation, rather than the 'all or nothing' approach above. It is also possible (since version 2.05) to include compiled regular expressions in the list - any element names which match the pattern will be forced to arrays. If the list contains only a single regex, then it is not necessary to enclose it in an arrayref. Eg: ForceArray => qr/_list$/ =head2 ForceContent => 1 I<# in - seldom used> When C parses elements which have text content as well as attributes, the text content must be represented as a hash value rather than a simple scalar. This option allows you to force text content to always parse to a hash value even when there are no attributes. So for example: XMLin('text1text2', ForceContent => 1) will parse to: { 'x' => { 'content' => 'text1' }, 'y' => { 'a' => 2, 'content' => 'text2' } } instead of: { 'x' => 'text1', 'y' => { 'a' => 2, 'content' => 'text2' } } =head2 GroupTags => { grouping tag => grouped tag } I<# in+out - handy> You can use this option to eliminate extra levels of indirection in your Perl data structure. For example this XML: /usr/bin /usr/local/bin /usr/X11/bin Would normally be read into a structure like this: { searchpath => { dir => [ '/usr/bin', '/usr/local/bin', '/usr/X11/bin' ] } } But when read in with the appropriate value for 'GroupTags': my $opt = XMLin($xml, GroupTags => { searchpath => 'dir' }); It will return this simpler structure: { searchpath => [ '/usr/bin', '/usr/local/bin', '/usr/X11/bin' ] } The grouping element (C<< >> in the example) must not contain any attributes or elements other than the grouped element. You can specify multiple 'grouping element' to 'grouped element' mappings in the same hashref. If this option is combined with C, the array folding will occur first and then the grouped element names will be eliminated. C will also use the grouptag mappings to re-introduce the tags around the grouped elements. Beware though that this will occur in all places that the 'grouping tag' name occurs - you probably don't want to use the same name for elements as well as attributes. =head2 Handler => object_ref I<# out - SAX only> Use the 'Handler' option to have C generate SAX events rather than returning a string of XML. For more details see L<"SAX SUPPORT"> below. Note: the current implementation of this option generates a string of XML and uses a SAX parser to translate it into SAX events. The normal encoding rules apply here - your data must be UTF8 encoded unless you specify an alternative encoding via the 'XMLDecl' option; and by the time the data reaches the handler object, it will be in UTF8 form regardless of the encoding you supply. A future implementation of this option may generate the events directly. =head2 KeepRoot => 1 I<# in+out - handy> In its attempt to return a data structure free of superfluous detail and unnecessary levels of indirection, C normally discards the root element name. Setting the 'KeepRoot' option to '1' will cause the root element name to be retained. So after executing this code: $config = XMLin('', KeepRoot => 1) You'll be able to reference the tempdir as C<$config-E{config}-E{tempdir}> instead of the default C<$config-E{tempdir}>. Similarly, setting the 'KeepRoot' option to '1' will tell C that the data structure already contains a root element name and it is not necessary to add another. =head2 KeyAttr => [ list ] I<# in+out - important> This option controls the 'array folding' feature which translates nested elements from an array to a hash. It also controls the 'unfolding' of hashes to arrays. For example, this XML: would, by default, parse to this: { 'user' => [ { 'login' => 'grep', 'fullname' => 'Gary R Epstein' }, { 'login' => 'stty', 'fullname' => 'Simon T Tyson' } ] } If the option 'KeyAttr => "login"' were used to specify that the 'login' attribute is a key, the same XML would parse to: { 'user' => { 'stty' => { 'fullname' => 'Simon T Tyson' }, 'grep' => { 'fullname' => 'Gary R Epstein' } } } The key attribute names should be supplied in an arrayref if there is more than one. C will attempt to match attribute names in the order supplied. C will use the first attribute name supplied when 'unfolding' a hash into an array. Note 1: The default value for 'KeyAttr' is ['name', 'key', 'id']. If you do not want folding on input or unfolding on output you must set this option to an empty list to disable the feature. Note 2: If you wish to use this option, you should also enable the C option. Without 'ForceArray', a single nested element will be rolled up into a scalar rather than an array and therefore will not be folded (since only arrays get folded). =head2 KeyAttr => { list } I<# in+out - important> This alternative (and preferred) method of specifying the key attributes allows more fine grained control over which elements are folded and on which attributes. For example the option 'KeyAttr => { package => 'id' } will cause any package elements to be folded on the 'id' attribute. No other elements which have an 'id' attribute will be folded at all. Note: C will generate a warning (or a fatal error in L<"STRICT MODE">) if this syntax is used and an element which does not have the specified key attribute is encountered (eg: a 'package' element without an 'id' attribute, to use the example above). Warnings can be suppressed with the lexical C pragma or C. Two further variations are made possible by prefixing a '+' or a '-' character to the attribute name: The option 'KeyAttr => { user => "+login" }' will cause this XML: to parse to this data structure: { 'user' => { 'stty' => { 'fullname' => 'Simon T Tyson', 'login' => 'stty' }, 'grep' => { 'fullname' => 'Gary R Epstein', 'login' => 'grep' } } } The '+' indicates that the value of the key attribute should be copied rather than moved to the folded hash key. A '-' prefix would produce this result: { 'user' => { 'stty' => { 'fullname' => 'Simon T Tyson', '-login' => 'stty' }, 'grep' => { 'fullname' => 'Gary R Epstein', '-login' => 'grep' } } } As described earlier, C will ignore hash keys starting with a '-'. =head2 NoAttr => 1 I<# in+out - handy> When used with C, the generated XML will contain no attributes. All hash key/values will be represented as nested elements instead. When used with C, any attributes in the XML will be ignored. =head2 NoEscape => 1 I<# out - seldom used> By default, C will translate the characters 'E', 'E', '&' and '"' to '<', '>', '&' and '"' respectively. Use this option to suppress escaping (presumably because you've already escaped the data in some more sophisticated manner). =head2 NoIndent => 1 I<# out - seldom used> Set this option to 1 to disable C's default 'pretty printing' mode. With this option enabled, the XML output will all be on one line (unless there are newlines in the data) - this may be easier for downstream processing. =head2 NoSort => 1 I<# out - seldom used> Newer versions of XML::Simple sort elements and attributes alphabetically (*), by default. Enable this option to suppress the sorting - possibly for backwards compatibility. * Actually, sorting is alphabetical but 'key' attribute or element names (as in 'KeyAttr') sort first. Also, when a hash of hashes is 'unfolded', the elements are sorted alphabetically by the value of the key field. =head2 NormaliseSpace => 0 | 1 | 2 I<# in - handy> This option controls how whitespace in text content is handled. Recognised values for the option are: =over 4 =item * 0 = (default) whitespace is passed through unaltered (except of course for the normalisation of whitespace in attribute values which is mandated by the XML recommendation) =item * 1 = whitespace is normalised in any value used as a hash key (normalising means removing leading and trailing whitespace and collapsing sequences of whitespace characters to a single space) =item * 2 = whitespace is normalised in all text content =back Note: you can spell this option with a 'z' if that is more natural for you. =head2 NSExpand => 1 I<# in+out handy - SAX only> This option controls namespace expansion - the translation of element and attribute names of the form 'prefix:name' to '{uri}name'. For example the element name 'xsl:template' might be expanded to: '{http://www.w3.org/1999/XSL/Transform}template'. By default, C will return element names and attribute names exactly as they appear in the XML. Setting this option to 1 will cause all element and attribute names to be expanded to include their namespace prefix. I. This option also controls whether C performs the reverse translation from '{uri}name' back to 'prefix:name'. The default is no translation. If your data contains expanded names, you should set this option to 1 otherwise C will emit XML which is not well formed. I to translate URIs back to prefixes>. =head2 NumericEscape => 0 | 1 | 2 I<# out - handy> Use this option to have 'high' (non-ASCII) characters in your Perl data structure converted to numeric entities (eg: €) in the XML output. Three levels are possible: 0 - default: no numeric escaping (OK if you're writing out UTF8) 1 - only characters above 0xFF are escaped (ie: characters in the 0x80-FF range are not escaped), possibly useful with ISO8859-1 output 2 - all characters above 0x7F are escaped (good for plain ASCII output) =head2 OutputFile => I<# out - handy> The default behaviour of C is to return the XML as a string. If you wish to write the XML to a file, simply supply the filename using the 'OutputFile' option. This option also accepts an IO handle object - especially useful in Perl 5.8.0 and later for output using an encoding other than UTF-8, eg: open my $fh, '>:encoding(iso-8859-1)', $path or die "open($path): $!"; XMLout($ref, OutputFile => $fh); Note, XML::Simple does not require that the object you pass in to the OutputFile option inherits from L - it simply assumes the object supports a C method. =head2 ParserOpts => [ XML::Parser Options ] I<# in - don't use this> I. This option allows you to pass parameters to the constructor of the underlying XML::Parser object (which of course assumes you're not using SAX). =head2 RootName => 'string' I<# out - handy> By default, when C generates XML, the root element will be named 'opt'. This option allows you to specify an alternative name. Specifying either undef or the empty string for the RootName option will produce XML with no root elements. In most cases the resulting XML fragment will not be 'well formed' and therefore could not be read back in by C. Nevertheless, the option has been found to be useful in certain circumstances. =head2 SearchPath => [ list ] I<# in - handy> If you pass C a filename, but the filename include no directory component, you can use this option to specify which directories should be searched to locate the file. You might use this option to search first in the user's home directory, then in a global directory such as /etc. If a filename is provided to C but SearchPath is not defined, the file is assumed to be in the current directory. If the first parameter to C is undefined, the default SearchPath will contain only the directory in which the script itself is located. Otherwise the default SearchPath will be empty. =head2 StrictMode => 1 | 0 I<# in+out seldom used> This option allows you to turn L on or off for a particular call, regardless of whether it was enabled at the time XML::Simple was loaded. =head2 SuppressEmpty => 1 | '' | undef I<# in+out - handy> This option controls what C should do with empty elements (no attributes and no content). The default behaviour is to represent them as empty hashes. Setting this option to a true value (eg: 1) will cause empty elements to be skipped altogether. Setting the option to 'undef' or the empty string will cause empty elements to be represented as the undefined value or the empty string respectively. The latter two alternatives are a little easier to test for in your code than a hash with no keys. The option also controls what C does with undefined values. Setting the option to undef causes undefined values to be output as empty elements (rather than empty attributes), it also suppresses the generation of warnings about undefined values. Setting the option to a true value (eg: 1) causes undefined values to be skipped altogether on output. =head2 ValueAttr => [ names ] I<# in - handy> Use this option to deal elements which always have a single attribute and no content. Eg: Setting C<< ValueAttr => [ 'value' ] >> will cause the above XML to parse to: { colour => 'red', size => 'XXL' } instead of this (the default): { colour => { value => 'red' }, size => { value => 'XXL' } } Note: This form of the ValueAttr option is not compatible with C - since the attribute name is discarded at parse time, the original XML cannot be reconstructed. =head2 ValueAttr => { element => attribute, ... } I<# in+out - handy> This (preferred) form of the ValueAttr option requires you to specify both the element and the attribute names. This is not only safer, it also allows the original XML to be reconstructed by C. Note: You probably don't want to use this option and the NoAttr option at the same time. =head2 Variables => { name => value } I<# in - handy> This option allows variables in the XML to be expanded when the file is read. (there is no facility for putting the variable names back if you regenerate XML using C). A 'variable' is any text of the form C<${name}> which occurs in an attribute value or in the text content of an element. If 'name' matches a key in the supplied hashref, C<${name}> will be replaced with the corresponding value from the hashref. If no matching key is found, the variable will not be replaced. Names must match the regex: C<[\w.]+> (ie: only 'word' characters and dots are allowed). =head2 VarAttr => 'attr_name' I<# in - handy> In addition to the variables defined using C, this option allows variables to be defined in the XML. A variable definition consists of an element with an attribute called 'attr_name' (the value of the C option). The value of the attribute will be used as the variable name and the text content of the element will be used as the value. A variable defined in this way will override a variable defined using the C option. For example: XMLin( ' /usr/local/apache ${prefix} ${exec_prefix}/bin ', VarAttr => 'name', ContentKey => '-content' ); produces the following data structure: { dir => { prefix => '/usr/local/apache', exec_prefix => '/usr/local/apache', bindir => '/usr/local/apache/bin', } } =head2 XMLDecl => 1 or XMLDecl => 'string' I<# out - handy> If you want the output from C to start with the optional XML declaration, simply set the option to '1'. The default XML declaration is: If you want some other string (for example to declare an encoding value), set the value of this option to the complete string you require. =head1 OPTIONAL OO INTERFACE The procedural interface is both simple and convenient however there are a couple of reasons why you might prefer to use the object oriented (OO) interface: =over 4 =item * to define a set of default values which should be used on all subsequent calls to C or C =item * to override methods in B to provide customised behaviour =back The default values for the options described above are unlikely to suit everyone. The OO interface allows you to effectively override B's defaults with your preferred values. It works like this: First create an XML::Simple parser object with your preferred defaults: my $xs = XML::Simple->new(ForceArray => 1, KeepRoot => 1); then call C or C as a method of that object: my $ref = $xs->XMLin($xml); my $xml = $xs->XMLout($ref); You can also specify options when you make the method calls and these values will be merged with the values specified when the object was created. Values specified in a method call take precedence. Note: when called as methods, the C and C routines may be called as C or C. The method names are aliased so the only difference is the aesthetics. =head2 Parsing Methods You can explicitly call one of the following methods rather than rely on the C method automatically determining whether the target to be parsed is a string, a file or a filehandle: =over 4 =item parse_string(text) Works exactly like the C method but assumes the first argument is a string of XML (or a reference to a scalar containing a string of XML). =item parse_file(filename) Works exactly like the C method but assumes the first argument is the name of a file containing XML. =item parse_fh(file_handle) Works exactly like the C method but assumes the first argument is a filehandle which can be read to get XML. =back =head2 Hook Methods You can make your own class which inherits from XML::Simple and overrides certain behaviours. The following methods may provide useful 'hooks' upon which to hang your modified behaviour. You may find other undocumented methods by examining the source, but those may be subject to change in future releases. =over 4 =item new_xml_parser() This method will be called when a new XML::Parser object must be constructed (either because XML::SAX is not installed or XML::Parser is preferred). =item handle_options(direction, name => value ...) This method will be called when one of the parsing methods or the C method is called. The initial argument will be a string (either 'in' or 'out') and the remaining arguments will be name value pairs. =item default_config_file() Calculates and returns the name of the file which should be parsed if no filename is passed to C (default: C<$0.xml>). =item build_simple_tree(filename, string) Called from C or any of the parsing methods. Takes either a file name as the first argument or C followed by a 'string' as the second argument. Returns a simple tree data structure. You could override this method to apply your own transformations before the data structure is returned to the caller. =item new_hashref() When the 'simple tree' data structure is being built, this method will be called to create any required anonymous hashrefs. =item sorted_keys(name, hashref) Called when C is translating a hashref to XML. This routine returns a list of hash keys in the order that the corresponding attributes/elements should appear in the output. =item escape_value(string) Called from C, takes a string and returns a copy of the string with XML character escaping rules applied. =item escape_attr(string) Called from C, to handle attribute values. By default, just calls C, but you can override this method if you want attributes escaped differently than text content. =item numeric_escape(string) Called from C, to handle non-ASCII characters (depending on the value of the NumericEscape option). =item copy_hash(hashref, extra_key => value, ...) Called from C, when 'unfolding' a hash of hashes into an array of hashes. You might wish to override this method if you're using tied hashes and don't want them to get untied. =back =head2 Cache Methods XML::Simple implements three caching schemes ('storable', 'memshare' and 'memcopy'). You can implement a custom caching scheme by implementing two methods - one for reading from the cache and one for writing to it. For example, you might implement a new 'dbm' scheme that stores cached data structures using the L module. First, you would add a C method which accepted a filename for use as a lookup key and returned a data structure on success, or undef on failure. Then, you would implement a C method which accepted a data structure and a filename. You would use this caching scheme by specifying the option: Cache => [ 'dbm' ] =head1 STRICT MODE If you import the B routines like this: use XML::Simple qw(:strict); the following common mistakes will be detected and treated as fatal errors =over 4 =item * Failing to explicitly set the C option - if you can't be bothered reading about this option, turn it off with: KeyAttr => [ ] =item * Failing to explicitly set the C option - if you can't be bothered reading about this option, set it to the safest mode with: ForceArray => 1 =item * Setting ForceArray to an array, but failing to list all the elements from the KeyAttr hash. =item * Data error - KeyAttr is set to say { part => 'partnum' } but the XML contains one or more EpartE elements without a 'partnum' attribute (or nested element). Note: if strict mode is not set but C is in force, this condition triggers a warning. =item * Data error - as above, but non-unique values are present in the key attribute (eg: more than one EpartE element with the same partnum). This will also trigger a warning if strict mode is not enabled. =item * Data error - as above, but value of key attribute (eg: partnum) is not a scalar string (due to nested elements etc). This will also trigger a warning if strict mode is not enabled. =back =head1 SAX SUPPORT From version 1.08_01, B includes support for SAX (the Simple API for XML) - specifically SAX2. In a typical SAX application, an XML parser (or SAX 'driver') module generates SAX events (start of element, character data, end of element, etc) as it parses an XML document and a 'handler' module processes the events to extract the required data. This simple model allows for some interesting and powerful possibilities: =over 4 =item * Applications written to the SAX API can extract data from huge XML documents without the memory overheads of a DOM or tree API. =item * The SAX API allows for plug and play interchange of parser modules without having to change your code to fit a new module's API. A number of SAX parsers are available with capabilities ranging from extreme portability to blazing performance. =item * A SAX 'filter' module can implement both a handler interface for receiving data and a generator interface for passing modified data on to a downstream handler. Filters can be chained together in 'pipelines'. =item * One filter module might split a data stream to direct data to two or more downstream handlers. =item * Generating SAX events is not the exclusive preserve of XML parsing modules. For example, a module might extract data from a relational database using DBI and pass it on to a SAX pipeline for filtering and formatting. =back B can operate at either end of a SAX pipeline. For example, you can take a data structure in the form of a hashref and pass it into a SAX pipeline using the 'Handler' option on C: use XML::Simple; use Some::SAX::Filter; use XML::SAX::Writer; my $ref = { .... # your data here }; my $writer = XML::SAX::Writer->new(); my $filter = Some::SAX::Filter->new(Handler => $writer); my $simple = XML::Simple->new(Handler => $filter); $simple->XMLout($ref); You can also put B at the opposite end of the pipeline to take advantage of the simple 'tree' data structure once the relevant data has been isolated through filtering: use XML::SAX; use Some::SAX::Filter; use XML::Simple; my $simple = XML::Simple->new(ForceArray => 1, KeyAttr => ['partnum']); my $filter = Some::SAX::Filter->new(Handler => $simple); my $parser = XML::SAX::ParserFactory->parser(Handler => $filter); my $ref = $parser->parse_uri('some_huge_file.xml'); print $ref->{part}->{'555-1234'}; You can build a filter by using an XML::Simple object as a handler and setting its DataHandler option to point to a routine which takes the resulting tree, modifies it and sends it off as SAX events to a downstream handler: my $writer = XML::SAX::Writer->new(); my $filter = XML::Simple->new( DataHandler => sub { my $simple = shift; my $data = shift; # Modify $data here $simple->XMLout($data, Handler => $writer); } ); my $parser = XML::SAX::ParserFactory->parser(Handler => $filter); $parser->parse_uri($filename); I but it could also have been specified in the constructor>. =head1 ENVIRONMENT If you don't care which parser module B uses then skip this section entirely (it looks more complicated than it really is). B will default to using a B parser if one is available or B if SAX is not available. You can dictate which parser module is used by setting either the environment variable 'XML_SIMPLE_PREFERRED_PARSER' or the package variable $XML::Simple::PREFERRED_PARSER to contain the module name. The following rules are used: =over 4 =item * The package variable takes precedence over the environment variable if both are defined. To force B to ignore the environment settings and use its default rules, you can set the package variable to an empty string. =item * If the 'preferred parser' is set to the string 'XML::Parser', then L will be used (or C will die if L is not installed). =item * If the 'preferred parser' is set to some other value, then it is assumed to be the name of a SAX parser module and is passed to L. If L is not installed, or the requested parser module is not installed, then C will die. =item * If the 'preferred parser' is not defined at all (the normal default state), an attempt will be made to load L. If L is installed, then a parser module will be selected according to L's normal rules (which typically means the last SAX parser installed). =item * if the 'preferred parser' is not defined and B is not installed, then B will be used. C will die if L is not installed. =back Note: The B distribution includes an XML parser written entirely in Perl. It is very portable but it is not very fast. You should consider installing L or L if they are available for your platform. =head1 ERROR HANDLING The XML standard is very clear on the issue of non-compliant documents. An error in parsing any single element (for example a missing end tag) must cause the whole document to be rejected. B will die with an appropriate message if it encounters a parsing error. If dying is not appropriate for your application, you should arrange to call C in an eval block and look for errors in $@. eg: my $config = eval { XMLin() }; PopUpMessage($@) if($@); Note, there is a common misconception that use of B will significantly slow down a script. While that may be true when the code being eval'd is in a string, it is not true of code like the sample above. =head1 EXAMPLES When C reads the following very simple piece of XML: it returns the following data structure: { 'username' => 'testuser', 'password' => 'frodo' } The identical result could have been produced with this alternative XML: Or this (although see 'ForceArray' option for variations): testuser frodo Repeated nested elements are represented as anonymous arrays: joe@smith.com jsmith@yahoo.com bob@smith.com { 'person' => [ { 'email' => [ 'joe@smith.com', 'jsmith@yahoo.com' ], 'firstname' => 'Joe', 'lastname' => 'Smith' }, { 'email' => 'bob@smith.com', 'firstname' => 'Bob', 'lastname' => 'Smith' } ] } Nested elements with a recognised key attribute are transformed (folded) from an array into a hash keyed on the value of that attribute (see the C option): { 'person' => { 'jbloggs' => { 'firstname' => 'Joe', 'lastname' => 'Bloggs' }, 'tsmith' => { 'firstname' => 'Tom', 'lastname' => 'Smith' }, 'jsmith' => { 'firstname' => 'Joe', 'lastname' => 'Smith' } } } The tag can be used to form anonymous arrays: Col 1Col 2Col 3 R1C1R1C2R1C3 R2C1R2C2R2C3 R3C1R3C2R3C3 { 'head' => [ [ 'Col 1', 'Col 2', 'Col 3' ] ], 'data' => [ [ 'R1C1', 'R1C2', 'R1C3' ], [ 'R2C1', 'R2C2', 'R2C3' ], [ 'R3C1', 'R3C2', 'R3C3' ] ] } Anonymous arrays can be nested to arbitrary levels and as a special case, if the surrounding tags for an XML document contain only an anonymous array the arrayref will be returned directly rather than the usual hashref: Col 1Col 2 R1C1R1C2 R2C1R2C2 [ [ 'Col 1', 'Col 2' ], [ 'R1C1', 'R1C2' ], [ 'R2C1', 'R2C2' ] ] Elements which only contain text content will simply be represented as a scalar. Where an element has both attributes and text content, the element will be represented as a hashref with the text content in the 'content' key (see the C option): first second { 'one' => 'first', 'two' => { 'attr' => 'value', 'content' => 'second' } } Mixed content (elements which contain both text content and nested elements) will be not be represented in a useful way - element order and significant whitespace will be lost. If you need to work with mixed content, then XML::Simple is not the right tool for your job - check out the next section. =head1 WHERE TO FROM HERE? B is able to present a simple API because it makes some assumptions on your behalf. These include: =over 4 =item * You're not interested in text content consisting only of whitespace =item * You don't mind that when things get slurped into a hash the order is lost =item * You don't want fine-grained control of the formatting of generated XML =item * You would never use a hash key that was not a legal XML element name =item * You don't need help converting between different encodings =back In a serious XML project, you'll probably outgrow these assumptions fairly quickly. This section of the document used to offer some advice on choosing a more powerful option. That advice has now grown into the 'Perl-XML FAQ' document which you can find at: L The advice in the FAQ boils down to a quick explanation of tree versus event based parsers and then recommends: For event based parsing, use SAX (do not set out to write any new code for XML::Parser's handler API - it is obsolete). For tree-based parsing, you could choose between the 'Perlish' approach of L and more standards based DOM implementations - preferably one with XPath support such as L. =head1 SEE ALSO B requires either L or L. To generate documents with namespaces, L is required. The optional caching functions require L. Answers to Frequently Asked Questions about XML::Simple are bundled with this distribution as: L =head1 COPYRIGHT Copyright 1999-2004 Grant McLean Egrantm@cpan.orgE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!Ê›ãë°Q°Qperl5/XML/Simple/FAQ.podnuÏÃ6Ç$ =head1 NAME XML::Simple::FAQ - Frequently Asked Questions about XML::Simple =head1 Basics =head2 What should I use XML::Simple for? Nothing! It's as simple as that. Choose a better module. See L for a gentle introduction to L with lots of examples. =head2 What was XML::Simple designed to be used for? XML::Simple is a Perl module that was originally developed as a tool for reading and writing configuration data in XML format. You could use it for other purposes that involve storing and retrieving structured data in XML but it's likely to be a frustrating experience. =head2 Why store configuration data in XML anyway? It seemed like a good idea at the time. Now, I use and recommend L which uses a format similar to that used by the Apache web server. This is easier to read than XML while still allowing advanced concepts such as nested sections. At the time XML::Simple was written, the advantages of using XML format for configuration data were thought to include: =over 4 =item * Using existing XML parsing tools requires less development time, is easier and more robust than developing your own config file parsing code =item * XML can represent relationships between pieces of data, such as nesting of sections to arbitrary levels (not easily done with .INI files for example) =item * XML is basically just text, so you can easily edit a config file (easier than editing a Win32 registry) =item * XML provides standard solutions for handling character sets and encoding beyond basic ASCII (important for internationalization) =item * If it becomes necessary to change your configuration file format, there are many tools available for performing transformations on XML files =item * XML is an open standard (the world does not need more proprietary binary file formats) =item * Taking the extra step of developing a DTD allows the format of configuration files to be validated before your program reads them (not directly supported by XML::Simple) =item * Combining a DTD with a good XML editor can give you a GUI config editor for minimal coding effort =back =head2 What isn't XML::Simple good for? The main limitation of XML::Simple is that it does not work with 'mixed content' (see the next question). If you consider your XML files contain marked up text rather than structured data, you should probably use another module. If your source XML documents change regularly, it's likely that you will experience intermittent failures. In particular, failure to properly use the ForceArray and KeyAttr options will produce code that works when you get a list of elements with the same name, but fails when there's only one item in the list. These types of problems can be avoided by not using XML::Simple in the first place. If you are working with very large XML files, XML::Simple's approach of representing the whole file in memory as a 'tree' data structure may not be suitable. =head2 What is mixed content? Consider this example XML: This is mixed content. This is said to be mixed content, because the EparaE element contains both character data (text content) and nested elements. Here's some more XML: Joe Bloggs 25-April-1969 This second example is not generally considered to be mixed content. The Efirst_nameE, Elast_nameE and EdobE elements contain only character data and the EpersonE element contains only nested elements. (Note: Strictly speaking, the whitespace between the nested elements is character data, but it is ignored by XML::Simple). =head2 Why doesn't XML::Simple handle mixed content? Because if it did, it would no longer be simple :-) Seriously though, there are plenty of excellent modules that allow you to work with mixed content in a variety of ways. Handling mixed content correctly is not easy and by ignoring these issues, XML::Simple is able to present an API without a steep learning curve. =head2 Which Perl modules do handle mixed content? Every one of them except XML::Simple :-) If you're looking for a recommendation, I'd suggest you look at the Perl-XML FAQ at: http://perl-xml.sourceforge.net/faq/ =head1 Installation =head2 How do I install XML::Simple? If you're running ActiveState Perl, or L you've probably already got XML::Simple and therefore do not need to install it at all. But you probably also have L, which is a much better module, so just use that. If you do need to install XML::Simple, you'll need to install an XML parser module first. Install either XML::Parser (which you may have already) or XML::SAX. If you install both, XML::SAX will be used by default. Once you have a parser installed ... On Unix systems, try: perl -MCPAN -e 'install XML::Simple' If that doesn't work, download the latest distribution from ftp://ftp.cpan.org/pub/CPAN/authors/id/G/GR/GRANTM , unpack it and run these commands: perl Makefile.PL make make test make install On Win32, if you have a recent build of ActiveState Perl (618 or better) try this command: ppm install XML::Simple If that doesn't work, you really only need the Simple.pm file, so extract it from the .tar.gz file (eg: using WinZIP) and save it in the \site\lib\XML directory under your Perl installation (typically C:\Perl). =head2 I'm trying to install XML::Simple and 'make test' fails Is the directory where you've unpacked XML::Simple mounted from a file server using NFS, SMB or some other network file sharing? If so, that may cause errors in the following test scripts: 3_Storable.t 4_MemShare.t 5_MemCopy.t The test suite is designed to exercise the boundary conditions of all XML::Simple's functionality and these three scripts exercise the caching functions. If XML::Simple is asked to parse a file for which it has a cached copy of a previous parse, then it compares the timestamp on the XML file with the timestamp on the cached copy. If the cached copy is *newer* then it will be used. If the cached copy is older or the same age then the file is re-parsed. The test scripts will get confused by networked filesystems if the workstation and server system clocks are not synchronised (to the second). If you get an error in one of these three test scripts but you don't plan to use the caching options (they're not enabled by default), then go right ahead and run 'make install'. If you do plan to use caching, then try unpacking the distribution on local disk and doing the build/test there. It's probably not a good idea to use the caching options with networked filesystems in production. If the file server's clock is ahead of the local clock, XML::Simple will re-parse files when it could have used the cached copy. However if the local clock is ahead of the file server clock and a file is changed immediately after it is cached, the old cached copy will be used. Is one of the three test scripts (above) failing but you're not running on a network filesystem? Are you running Win32? If so, you may be seeing a bug in Win32 where writes to a file do not affect its modification timestamp. If none of these scenarios match your situation, please confirm you're running the latest version of XML::Simple and then email the output of 'make test' to me at grantm@cpan.org =head2 Why is XML::Simple so slow? If you find that XML::Simple is very slow reading XML, the most likely reason is that you have XML::SAX installed but no additional SAX parser module. The XML::SAX distribution includes an XML parser written entirely in Perl. This is very portable but not very fast. For better performance install either XML::SAX::Expat or XML::LibXML. =head1 Usage =head2 How do I use XML::Simple? If you don't know how to use XML::Simple then the best approach is to L instead. Stop reading this document and use that one instead. If you are determined to use XML::Simple, it come with copious documentation, so L. =head2 There are so many options, which ones do I really need to know about? Although you can get by without using any options, you shouldn't even consider using XML::Simple in production until you know what these two options do: =over 4 =item * forcearray =item * keyattr =back The reason you really need to read about them is because the default values for these options will trip you up if you don't. Although everyone agrees that these defaults are not ideal, there is not wide agreement on what they should be changed to. The answer therefore is to read about them (see below) and select values which are right for you. =head2 What is the forcearray option all about? Consider this XML in a file called ./person.xml: Joe Bloggs bungy jumping sky diving knitting You could read it in with this line: my $person = XMLin('./person.xml'); Which would give you a data structure like this: $person = { 'first_name' => 'Joe', 'last_name' => 'Bloggs', 'hobbie' => [ 'bungy jumping', 'sky diving', 'knitting' ] }; The Efirst_nameE and Elast_nameE elements are represented as simple scalar values which you could refer to like this: print "$person->{first_name} $person->{last_name}\n"; The EhobbieE elements are represented as an array - since there is more than one. You could refer to the first one like this: print $person->{hobbie}->[0], "\n"; Or the whole lot like this: print join(', ', @{$person->{hobbie}} ), "\n"; The catch is, that these last two lines of code will only work for people who have more than one hobbie. If there is only one EhobbieE element, it will be represented as a simple scalar (just like Efirst_nameE and Elast_nameE). Which might lead you to write code like this: if(ref($person->{hobbie})) { print join(', ', @{$person->{hobbie}} ), "\n"; } else { print $person->{hobbie}, "\n"; } Don't do that. One alternative approach is to set the forcearray option to a true value: my $person = XMLin('./person.xml', forcearray => 1); Which will give you a data structure like this: $person = { 'first_name' => [ 'Joe' ], 'last_name' => [ 'Bloggs' ], 'hobbie' => [ 'bungy jumping', 'sky diving', 'knitting' ] }; Then you can use this line to refer to all the list of hobbies even if there was only one: print join(', ', @{$person->{hobbie}} ), "\n"; The downside of this approach is that the Efirst_nameE and Elast_nameE elements will also always be represented as arrays even though there will never be more than one: print "$person->{first_name}->[0] $person->{last_name}->[0]\n"; This might be OK if you change the XML to use attributes for things that will always be singular and nested elements for things that may be plural: motorcycle maintenance On the other hand, if you prefer not to use attributes, then you could specify that any EhobbieE elements should always be represented as arrays and all other nested elements should be simple scalar values unless there is more than one: my $person = XMLin('./person.xml', forcearray => [ 'hobbie' ]); The forcearray option accepts a list of element names which should always be forced to an array representation: forcearray => [ qw(hobbie qualification childs_name) ] See the XML::Simple manual page for more information. =head2 What is the keyattr option all about? Consider this sample XML: You could slurp it in with this code: my $catalog = XMLin('./catalog.xml'); Which would return a data structure like this: $catalog = { 'part' => [ { 'partnum' => '1842334', 'desc' => 'High pressure flange', 'price' => '24.50' }, { 'partnum' => '9344675', 'desc' => 'Threaded gasket', 'price' => '9.25' }, { 'partnum' => '5634896', 'desc' => 'Low voltage washer', 'price' => '12.00' } ] }; Then you could access the description of the first part in the catalog with this code: print $catalog->{part}->[0]->{desc}, "\n"; However, if you wanted to access the description of the part with the part number of "9344675" then you'd have to code a loop like this: foreach my $part (@{$catalog->{part}}) { if($part->{partnum} eq '9344675') { print $part->{desc}, "\n"; last; } } The knowledge that each EpartE element has a unique partnum attribute allows you to eliminate this search. You can pass this knowledge on to XML::Simple like this: my $catalog = XMLin($xml, keyattr => ['partnum']); Which will return a data structure like this: $catalog = { 'part' => { '5634896' => { 'desc' => 'Low voltage washer', 'price' => '12.00' }, '1842334' => { 'desc' => 'High pressure flange', 'price' => '24.50' }, '9344675' => { 'desc' => 'Threaded gasket', 'price' => '9.25' } } }; XML::Simple has been able to transform $catalog->{part} from an arrayref to a hashref (keyed on partnum). This transformation is called 'array folding'. Through the use of array folding, you can now index directly to the description of the part you want: print $catalog->{part}->{9344675}->{desc}, "\n"; The 'keyattr' option also enables array folding when the unique key is in a nested element rather than an attribute. eg: 1842334 High pressure flange 24.50 9344675 Threaded gasket 9.25 5634896 Low voltage washer 12.00 See the XML::Simple manual page for more information. =head2 So what's the catch with 'keyattr'? One thing to watch out for is that you might get array folding even if you don't supply the keyattr option. The default value for this option is: [ 'name', 'key', 'id'] Which means if your XML elements have a 'name', 'key' or 'id' attribute (or nested element) then they may get folded on those values. This means that you can take advantage of array folding simply through careful choice of attribute names. On the hand, if you really don't want array folding at all, you'll need to set 'key attr to an empty list: my $ref = XMLin($xml, keyattr => []); A second 'gotcha' is that array folding only works on arrays. That might seem obvious, but if there's only one record in your XML and you didn't set the 'forcearray' option then it won't be represented as an array and consequently won't get folded into a hash. The moral is that if you're using array folding, you should always turn on the forcearray option. You probably want to be as specific as you can be too. For instance, the safest way to parse the EcatalogE example above would be: my $catalog = XMLin($xml, keyattr => { part => 'partnum'}, forcearray => ['part']); By using the hashref for keyattr, you can specify that only EpartE elements should be folded on the 'partnum' attribute (and that the EpartE elements should not be folded on any other attribute). By supplying a list of element names for forcearray, you're ensuring that folding will work even if there's only one EpartE. You're also ensuring that if the 'partnum' unique key is supplied in a nested element then that element won't get forced to an array too. =head2 How do I know what my data structure should look like? The rules are fairly straightforward: =over 4 =item * each element gets represented as a hash =item * unless it contains only text, in which case it'll be a simple scalar value =item * or unless there's more than one element with the same name, in which case they'll be represented as an array =item * unless you've got array folding enabled, in which case they'll be folded into a hash =item * empty elements (no text contents B no attributes) will either be represented as an empty hash, an empty string or undef - depending on the value of the 'suppressempty' option. =back If you're in any doubt, use Data::Dumper, eg: use XML::Simple; use Data::Dumper; my $ref = XMLin($xml); print Dumper($ref); =head2 I'm getting 'Use of uninitialized value' warnings You're probably trying to index into a non-existant hash key - try Data::Dumper. =head2 I'm getting a 'Not an ARRAY reference' error Something that you expect to be an array is not. The two most likely causes are that you forgot to use 'forcearray' or that the array got folded into a hash - try Data::Dumper. =head2 I'm getting a 'No such array field' error Something that you expect to be a hash is actually an array. Perhaps array folding failed because one element was missing the key attribute - try Data::Dumper. =head2 I'm getting an 'Out of memory' error Something in the data structure is not as you expect and Perl may be trying unsuccessfully to autovivify things - try Data::Dumper. If you're already using Data::Dumper, try calling Dumper() immediately after XMLin() - ie: before you attempt to access anything in the data structure. =head2 My element order is getting jumbled up If you read an XML file with XMLin() and then write it back out with XMLout(), the order of the elements will likely be different. (However, if you read the file back in with XMLin() you'll get the same Perl data structure). The reordering happens because XML::Simple uses hashrefs to store your data and Perl hashes do not really have any order. It is possible that a future version of XML::Simple will use Tie::IxHash to store the data in hashrefs which do retain the order. However this will not fix all cases of element order being lost. If your application really is sensitive to element order, don't use XML::Simple (and don't put order-sensitive values in attributes). =head2 XML::Simple turns nested elements into attributes If you read an XML file with XMLin() and then write it back out with XMLout(), some data which was originally stored in nested elements may end up in attributes. (However, if you read the file back in with XMLin() you'll get the same Perl data structure). There are a number of ways you might handle this: =over 4 =item * use the 'forcearray' option with XMLin() =item * use the 'noattr' option with XMLout() =item * live with it =item * don't use XML::Simple =back =head2 Why does XMLout() insert EnameE elements (or attributes)? Try setting keyattr => []. When you call XMLin() to read XML, the 'keyattr' option controls whether arrays get 'folded' into hashes. Similarly, when you call XMLout(), the 'keyattr' option controls whether hashes get 'unfolded' into arrays. As described above, 'keyattr' is enabled by default. =head2 Why are empty elements represented as empty hashes? An element is always represented as a hash unless it contains only text, in which case it is represented as a scalar string. If you would prefer empty elements to be represented as empty strings or the undefined value, set the 'suppressempty' option to '' or undef respectively. =head2 Why is ParserOpts deprecated? The C option is a remnant of the time when XML::Simple only worked with the XML::Parser API. Its value is completely ignored if you're using a SAX parser, so writing code which relied on it would bar you from taking advantage of SAX. Even if you are using XML::Parser, it is seldom necessary to pass options to the parser object. A number of people have written to say they use this option to set XML::Parser's C option. Don't do that, it's wrong, Wrong, WRONG! Fix the XML document so that it's well-formed and you won't have a problem. Having said all of that, as long as XML::Simple continues to support the XML::Parser API, this option will not be removed. There are currently no plans to remove support for the XML::Parser API. =cut PK!b²É±±perl5/Data/Uniqid.pmnuÏÃ6Ç$package Data::Uniqid; use 5.006; use strict; use warnings; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Exporter); our %EXPORT_TAGS = ( 'all' => [ qw( suniqid uniqid luniqid ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.12'; use Math::BigInt; use Sys::Hostname; use Time::HiRes qw( gettimeofday usleep ); sub base62() { ################################################### Base62 ##### my($s)=@_; my(@c)=('0'..'9','a'..'z','A'..'Z'); my(@p,$u,$v,$i,$n); my($m)=20; $p[0]=1; for $i (1..$m) { $p[$i]=Math::BigInt->new($p[$i-1]); $p[$i]=$p[$i]->bmul(62); } $v=Math::BigInt->new($s); for ($i=$m;$i>=0;$i--) { $v=Math::BigInt->new($v); ($n,$v)=$v->bdiv($p[$i]); $u.=$c[$n]; } $u=~s/^0+//; return($u); } sub suniqid { ########################################### get unique id ##### my($s,$us)=gettimeofday();usleep(1); my($v)=sprintf("%06d%05d%06d",$us,substr($s,-5),$$); return(&base62($v)); } sub uniqid { ########################################### get unique id ##### my($s,$us)=gettimeofday();usleep(1); my($v)=sprintf("%06d%010d%06d",$us,$s,$$); return(&base62($v)); } sub luniqid { ############################################ get unique id ##### my($s,$us)=gettimeofday();usleep(1); my($ia,$ib,$ic,$id)=unpack("C4", (gethostbyname(hostname()))[4]); my($v)=sprintf("%06d%10d%06d%03d%03d%03d%03d",$us,$s,$$,$ia,$ib,$ic,$id); return(&base62($v)); } 1; __END__ =head1 NAME Data::Uniqid - Perl extension for simple genrating of unique id's =head1 SYNOPSIS use Data::Uniqid qw ( suniqid uniqid luniqid ); $id = suniqid; $id = uniqid; $id = luniqid; =head1 DESCRIPTION Data::Uniqid provides three simple routines for generating unique ids. These ids are coded with a Base62 systen to make them short and handy (e.g. to use it as part of a URL). suinqid genrates a very short id valid only for the localhost and with a liftime of 1 day uniqid generates a short id valid on the local host luniqid generates a long id valid everywhere and ever =head1 AUTHOR Mike Wesemann, <mwx@gmx.de> =head1 SEE ALSO L. =cut PK!rŽTKÇÇ perl5/ok.pmnuÏÃ6Ç$package ok; our $VERSION = '1.302183'; use strict; use Test::More (); sub import { shift; if (@_) { goto &Test::More::pass if $_[0] eq 'ok'; goto &Test::More::use_ok; } # No argument list - croak as if we are prototyped like use_ok() my (undef, $file, $line) = caller(); ($file =~ /^\(eval/) or die "Not enough arguments for 'use ok' at $file line $line\n"; } __END__ =encoding UTF-8 =head1 NAME ok - Alternative to Test::More::use_ok =head1 SYNOPSIS use ok 'Some::Module'; =head1 DESCRIPTION With this module, simply change all C in test scripts to C, and they will be executed at C time. Please see L for the full description. =head1 CC0 1.0 Universal To the extent possible under law, å”�é³³ has waived all copyright and related or neighboring rights to L. This work is published from Taiwan. L =cut PK!-èû**perl5/Canary/Stability.pmnuÏÃ6Ç$=head1 NAME Canary::Stability - canary to check perl compatibility for schmorp's modules =head1 SYNOPSIS # in Makefile.PL use Canary::Stability DISTNAME => 2001, MINIMUM_PERL_VERSION; =head1 DESCRIPTION This module is used by Schmorp's modules during configuration stage to test the installed perl for compatibility with his modules. It's not, at this stage, meant as a tool for other module authors, although in principle nothing prevents them from subscribing to the same ideas. See the F in L or L for usage examples. =cut package Canary::Stability; BEGIN { $VERSION = 2013; } sub sgr { # we just assume ANSI almost everywhere # red 31, yellow 33, green 32 local $| = 1; $ENV{PERL_CANARY_STABILITY_COLOUR} ne 0 and ((-t STDOUT and length $ENV{TERM}) or $ENV{PERL_CANARY_STABILITY_COLOUR}) and print "\e[$_[0]m"; } sub import { my (undef, $distname, $minvers, $minperl) = @_; $ENV{PERL_CANARY_STABILITY_DISABLE} and return; $minperl ||= 5.008002; print < $VERSION) { sgr 33; print < Do not prompt the user on alert messages. =item C Disable use of colour. =item C Force use of colour. =item C Disable this modules functionality completely. =item C When this variable is set to a true value and the perl minimum version requirement is not met, the module will exit, which should skip testing under automated testing environments. This is done to avoid false failure or success reports when the chances of success are already quite low and the failures are not supported by the author. =back =head1 AUTHOR Marc Lehmann http://software.schmorp.de/pkg/Canary-Stability.html =cut 1 PK!FR°©©perl5/JSON/PP/Boolean.pmnuÏÃ6Ç$=head1 NAME JSON::PP::Boolean - dummy module providing JSON::PP::Boolean =head1 SYNOPSIS # do not "use" yourself =head1 DESCRIPTION This module exists only to provide overload resolution for Storable and similar modules. See L for more info about this class. =cut use JSON::PP (); use strict; 1; =head1 AUTHOR This idea is from L written by Marc Lehmann =cut PK!Ý„õM@M@perl5/JSON/PP.pmnuÏÃ6Ç$package JSON::PP; # JSON-2.0 use 5.005; use strict; use base qw(Exporter); use overload (); use Carp (); use B (); #use Devel::Peek; $JSON::PP::VERSION = '2.27203'; @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json); # instead of hash-access, i tried index-access for speed. # but this method is not faster than what i expected. so it will be changed. use constant P_ASCII => 0; use constant P_LATIN1 => 1; use constant P_UTF8 => 2; use constant P_INDENT => 3; use constant P_CANONICAL => 4; use constant P_SPACE_BEFORE => 5; use constant P_SPACE_AFTER => 6; use constant P_ALLOW_NONREF => 7; use constant P_SHRINK => 8; use constant P_ALLOW_BLESSED => 9; use constant P_CONVERT_BLESSED => 10; use constant P_RELAXED => 11; use constant P_LOOSE => 12; use constant P_ALLOW_BIGNUM => 13; use constant P_ALLOW_BAREKEY => 14; use constant P_ALLOW_SINGLEQUOTE => 15; use constant P_ESCAPE_SLASH => 16; use constant P_AS_NONBLESSED => 17; use constant P_ALLOW_UNKNOWN => 18; use constant OLD_PERL => $] < 5.008 ? 1 : 0; BEGIN { my @xs_compati_bit_properties = qw( latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink allow_blessed convert_blessed relaxed allow_unknown ); my @pp_bit_properties = qw( allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed ); # Perl version check, Unicode handling is enable? # Helper module sets @JSON::PP::_properties. if ($] < 5.008 ) { my $helper = $] >= 5.006 ? 'JSON::PP::Compat5006' : 'JSON::PP::Compat5005'; eval qq| require $helper |; if ($@) { Carp::croak $@; } } for my $name (@xs_compati_bit_properties, @pp_bit_properties) { my $flag_name = 'P_' . uc($name); eval qq/ sub $name { my \$enable = defined \$_[1] ? \$_[1] : 1; if (\$enable) { \$_[0]->{PROPS}->[$flag_name] = 1; } else { \$_[0]->{PROPS}->[$flag_name] = 0; } \$_[0]; } sub get_$name { \$_[0]->{PROPS}->[$flag_name] ? 1 : ''; } /; } } # Functions my %encode_allow_method = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash allow_blessed convert_blessed indent indent_length allow_bignum as_nonblessed /; my %decode_allow_method = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum allow_barekey max_size relaxed/; my $JSON; # cache sub encode_json ($) { # encode ($JSON ||= __PACKAGE__->new->utf8)->encode(@_); } sub decode_json { # decode ($JSON ||= __PACKAGE__->new->utf8)->decode(@_); } # Obsoleted sub to_json($) { Carp::croak ("JSON::PP::to_json has been renamed to encode_json."); } sub from_json($) { Carp::croak ("JSON::PP::from_json has been renamed to decode_json."); } # Methods sub new { my $class = shift; my $self = { max_depth => 512, max_size => 0, indent => 0, FLAGS => 0, fallback => sub { encode_error('Invalid value. JSON can only reference.') }, indent_length => 3, }; bless $self, $class; } sub encode { return $_[0]->PP_encode_json($_[1]); } sub decode { return $_[0]->PP_decode_json($_[1], 0x00000000); } sub decode_prefix { return $_[0]->PP_decode_json($_[1], 0x00000001); } # accessor # pretty printing sub pretty { my ($self, $v) = @_; my $enable = defined $v ? $v : 1; if ($enable) { # indent_length(3) for JSON::XS compatibility $self->indent(1)->indent_length(3)->space_before(1)->space_after(1); } else { $self->indent(0)->space_before(0)->space_after(0); } $self; } # etc sub max_depth { my $max = defined $_[1] ? $_[1] : 0x80000000; $_[0]->{max_depth} = $max; $_[0]; } sub get_max_depth { $_[0]->{max_depth}; } sub max_size { my $max = defined $_[1] ? $_[1] : 0; $_[0]->{max_size} = $max; $_[0]; } sub get_max_size { $_[0]->{max_size}; } sub filter_json_object { $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0; $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0; $_[0]; } sub filter_json_single_key_object { if (@_ > 1) { $_[0]->{cb_sk_object}->{$_[1]} = $_[2]; } $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0; $_[0]; } sub indent_length { if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) { Carp::carp "The acceptable range of indent_length() is 0 to 15."; } else { $_[0]->{indent_length} = $_[1]; } $_[0]; } sub get_indent_length { $_[0]->{indent_length}; } sub sort_by { $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1; $_[0]; } sub allow_bigint { Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted."); } ############################### ### ### Perl => JSON ### { # Convert my $max_depth; my $indent; my $ascii; my $latin1; my $utf8; my $space_before; my $space_after; my $canonical; my $allow_blessed; my $convert_blessed; my $indent_length; my $escape_slash; my $bignum; my $as_nonblessed; my $depth; my $indent_count; my $keysort; sub PP_encode_json { my $self = shift; my $obj = shift; $indent_count = 0; $depth = 0; my $idx = $self->{PROPS}; ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed, $convert_blessed, $escape_slash, $bignum, $as_nonblessed) = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED, P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED]; ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/}; $keysort = $canonical ? sub { $a cmp $b } : undef; if ($self->{sort_by}) { $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by} : $self->{sort_by} =~ /\D+/ ? $self->{sort_by} : sub { $a cmp $b }; } encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)") if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]); my $str = $self->object_to_json($obj); $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible unless ($ascii or $latin1 or $utf8) { utf8::upgrade($str); } if ($idx->[ P_SHRINK ]) { utf8::downgrade($str, 1); } return $str; } sub object_to_json { my ($self, $obj) = @_; my $type = ref($obj); if($type eq 'HASH'){ return $self->hash_to_json($obj); } elsif($type eq 'ARRAY'){ return $self->array_to_json($obj); } elsif ($type) { # blessed object? if (blessed($obj)) { return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') ); if ( $convert_blessed and $obj->can('TO_JSON') ) { my $result = $obj->TO_JSON(); if ( defined $result and ref( $result ) ) { if ( refaddr( $obj ) eq refaddr( $result ) ) { encode_error( sprintf( "%s::TO_JSON method returned same object as was passed instead of a new one", ref $obj ) ); } } return $self->object_to_json( $result ); } return "$obj" if ( $bignum and _is_bignum($obj) ); return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed. encode_error( sprintf("encountered object '%s', but neither allow_blessed " . "nor convert_blessed settings are enabled", $obj) ) unless ($allow_blessed); return 'null'; } else { return $self->value_to_json($obj); } } else{ return $self->value_to_json($obj); } } sub hash_to_json { my ($self, $obj) = @_; my @res; encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)") if (++$depth > $max_depth); my ($pre, $post) = $indent ? $self->_up_indent() : ('', ''); my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : ''); for my $k ( _sort( $obj ) ) { if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized push @res, string_to_json( $self, $k ) . $del . ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) ); } --$depth; $self->_down_indent() if ($indent); return '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . '}'; } sub array_to_json { my ($self, $obj) = @_; my @res; encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)") if (++$depth > $max_depth); my ($pre, $post) = $indent ? $self->_up_indent() : ('', ''); for my $v (@$obj){ push @res, $self->object_to_json($v) || $self->value_to_json($v); } --$depth; $self->_down_indent() if ($indent); return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']'; } sub value_to_json { my ($self, $value) = @_; return 'null' if(!defined $value); my $b_obj = B::svref_2object(\$value); # for round trip problem my $flags = $b_obj->FLAGS; return $value # as is if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV? my $type = ref($value); if(!$type){ return string_to_json($self, $value); } elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ){ return $$value == 1 ? 'true' : 'false'; } elsif ($type) { if ((overload::StrVal($value) =~ /=(\w+)/)[0]) { return $self->value_to_json("$value"); } if ($type eq 'SCALAR' and defined $$value) { return $$value eq '1' ? 'true' : $$value eq '0' ? 'false' : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null' : encode_error("cannot encode reference to scalar"); } if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) { return 'null'; } else { if ( $type eq 'SCALAR' or $type eq 'REF' ) { encode_error("cannot encode reference to scalar"); } else { encode_error("encountered $value, but JSON can only represent references to arrays or hashes"); } } } else { return $self->{fallback}->($value) if ($self->{fallback} and ref($self->{fallback}) eq 'CODE'); return 'null'; } } my %esc = ( "\n" => '\n', "\r" => '\r', "\t" => '\t', "\f" => '\f', "\b" => '\b', "\"" => '\"', "\\" => '\\\\', "\'" => '\\\'', ); sub string_to_json { my ($self, $arg) = @_; $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g; $arg =~ s/\//\\\//g if ($escape_slash); $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg; if ($ascii) { $arg = JSON_PP_encode_ascii($arg); } if ($latin1) { $arg = JSON_PP_encode_latin1($arg); } if ($utf8) { utf8::encode($arg); } return '"' . $arg . '"'; } sub blessed_to_json { my $reftype = reftype($_[1]) || ''; if ($reftype eq 'HASH') { return $_[0]->hash_to_json($_[1]); } elsif ($reftype eq 'ARRAY') { return $_[0]->array_to_json($_[1]); } else { return 'null'; } } sub encode_error { my $error = shift; Carp::croak "$error"; } sub _sort { defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]}; } sub _up_indent { my $self = shift; my $space = ' ' x $indent_length; my ($pre,$post) = ('',''); $post = "\n" . $space x $indent_count; $indent_count++; $pre = "\n" . $space x $indent_count; return ($pre,$post); } sub _down_indent { $indent_count--; } sub PP_encode_box { { depth => $depth, indent_count => $indent_count, }; } } # Convert sub _encode_ascii { join('', map { $_ <= 127 ? chr($_) : $_ <= 65535 ? sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_)); } unpack('U*', $_[0]) ); } sub _encode_latin1 { join('', map { $_ <= 255 ? chr($_) : $_ <= 65535 ? sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_)); } unpack('U*', $_[0]) ); } sub _encode_surrogates { # from perlunicode my $uni = $_[0] - 0x10000; return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00); } sub _is_bignum { $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat'); } # # JSON => Perl # my $max_intsize; BEGIN { my $checkint = 1111; for my $d (5..64) { $checkint .= 1; my $int = eval qq| $checkint |; if ($int =~ /[eE]/) { $max_intsize = $d - 1; last; } } } { # PARSE my %escapes = ( # by Jeremy Muhlich b => "\x8", t => "\x9", n => "\xA", f => "\xC", r => "\xD", '\\' => '\\', '"' => '"', '/' => '/', ); my $text; # json data my $at; # offset my $ch; # 1chracter my $len; # text length (changed according to UTF8 or NON UTF8) # INTERNAL my $depth; # nest counter my $encoding; # json text encoding my $is_valid_utf8; # temp variable my $utf8_len; # utf8 byte length # FLAGS my $utf8; # must be utf8 my $max_depth; # max nest nubmer of objects and arrays my $max_size; my $relaxed; my $cb_object; my $cb_sk_object; my $F_HOOK; my $allow_bigint; # using Math::BigInt my $singlequote; # loosely quoting my $loose; # my $allow_barekey; # bareKey # $opt flag # 0x00000001 .... decode_prefix # 0x10000000 .... incr_parse sub PP_decode_json { my ($self, $opt); # $opt is an effective flag during this decode_json. ($self, $text, $opt) = @_; ($at, $ch, $depth) = (0, '', 0); if ( !defined $text or ref $text ) { decode_error("malformed JSON string, neither array, object, number, string or atom"); } my $idx = $self->{PROPS}; ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote) = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE]; if ( $utf8 ) { utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry"); } else { utf8::upgrade( $text ); } $len = length $text; ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK) = @{$self}{qw/max_depth max_size cb_object cb_sk_object F_HOOK/}; if ($max_size > 1) { use bytes; my $bytes = length $text; decode_error( sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s" , $bytes, $max_size), 1 ) if ($bytes > $max_size); } # Currently no effect # should use regexp my @octets = unpack('C4', $text); $encoding = ( $octets[0] and $octets[1]) ? 'UTF-8' : (!$octets[0] and $octets[1]) ? 'UTF-16BE' : (!$octets[0] and !$octets[1]) ? 'UTF-32BE' : ( $octets[2] ) ? 'UTF-16LE' : (!$octets[2] ) ? 'UTF-32LE' : 'unknown'; white(); # remove head white space my $valid_start = defined $ch; # Is there a first character for JSON structure? my $result = value(); return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start; if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) { decode_error( 'JSON text must be an object or array (but found number, string, true, false or null,' . ' use allow_nonref to allow this)', 1); } Carp::croak('something wrong.') if $len < $at; # we won't arrive here. my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length white(); # remove tail white space if ( $ch ) { return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix decode_error("garbage after JSON object"); } ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result; } sub next_chr { return $ch = undef if($at >= $len); $ch = substr($text, $at++, 1); } sub value { white(); return if(!defined $ch); return object() if($ch eq '{'); return array() if($ch eq '['); return string() if($ch eq '"' or ($singlequote and $ch eq "'")); return number() if($ch =~ /[0-9]/ or $ch eq '-'); return word(); } sub string { my ($i, $s, $t, $u); my $utf16; my $is_utf8; ($is_valid_utf8, $utf8_len) = ('', 0); $s = ''; # basically UTF8 flag on if($ch eq '"' or ($singlequote and $ch eq "'")){ my $boundChar = $ch; OUTER: while( defined(next_chr()) ){ if($ch eq $boundChar){ next_chr(); if ($utf16) { decode_error("missing low surrogate character in surrogate pair"); } utf8::decode($s) if($is_utf8); return $s; } elsif($ch eq '\\'){ next_chr(); if(exists $escapes{$ch}){ $s .= $escapes{$ch}; } elsif($ch eq 'u'){ # UNICODE handling my $u = ''; for(1..4){ $ch = next_chr(); last OUTER if($ch !~ /[0-9a-fA-F]/); $u .= $ch; } # U+D800 - U+DBFF if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate? $utf16 = $u; } # U+DC00 - U+DFFF elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate? unless (defined $utf16) { decode_error("missing high surrogate character in surrogate pair"); } $is_utf8 = 1; $s .= JSON_PP_decode_surrogates($utf16, $u) || next; $utf16 = undef; } else { if (defined $utf16) { decode_error("surrogate pair expected"); } if ( ( my $hex = hex( $u ) ) > 127 ) { $is_utf8 = 1; $s .= JSON_PP_decode_unicode($u) || next; } else { $s .= chr $hex; } } } else{ unless ($loose) { $at -= 2; decode_error('illegal backslash escape sequence in string'); } $s .= $ch; } } else{ if ( ord $ch > 127 ) { if ( $utf8 ) { unless( $ch = is_valid_utf8($ch) ) { $at -= 1; decode_error("malformed UTF-8 character in JSON string"); } else { $at += $utf8_len - 1; } } else { utf8::encode( $ch ); } $is_utf8 = 1; } if (!$loose) { if ($ch =~ /[\x00-\x1f\x22\x5c]/) { # '/' ok $at--; decode_error('invalid character encountered while parsing JSON string'); } } $s .= $ch; } } } decode_error("unexpected end of string while parsing JSON string"); } sub white { while( defined $ch ){ if($ch le ' '){ next_chr(); } elsif($ch eq '/'){ next_chr(); if(defined $ch and $ch eq '/'){ 1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r"); } elsif(defined $ch and $ch eq '*'){ next_chr(); while(1){ if(defined $ch){ if($ch eq '*'){ if(defined(next_chr()) and $ch eq '/'){ next_chr(); last; } } else{ next_chr(); } } else{ decode_error("Unterminated comment"); } } next; } else{ $at--; decode_error("malformed JSON string, neither array, object, number, string or atom"); } } else{ if ($relaxed and $ch eq '#') { # correctly? pos($text) = $at; $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g; $at = pos($text); next_chr; next; } last; } } } sub array { my $a = $_[0] || []; # you can use this code to use another array ref object. decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)') if (++$depth > $max_depth); next_chr(); white(); if(defined $ch and $ch eq ']'){ --$depth; next_chr(); return $a; } else { while(defined($ch)){ push @$a, value(); white(); if (!defined $ch) { last; } if($ch eq ']'){ --$depth; next_chr(); return $a; } if($ch ne ','){ last; } next_chr(); white(); if ($relaxed and $ch eq ']') { --$depth; next_chr(); return $a; } } } decode_error(", or ] expected while parsing array"); } sub object { my $o = $_[0] || {}; # you can use this code to use another hash ref object. my $k; decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)') if (++$depth > $max_depth); next_chr(); white(); if(defined $ch and $ch eq '}'){ --$depth; next_chr(); if ($F_HOOK) { return _json_object_hook($o); } return $o; } else { while (defined $ch) { $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string(); white(); if(!defined $ch or $ch ne ':'){ $at--; decode_error("':' expected"); } next_chr(); $o->{$k} = value(); white(); last if (!defined $ch); if($ch eq '}'){ --$depth; next_chr(); if ($F_HOOK) { return _json_object_hook($o); } return $o; } if($ch ne ','){ last; } next_chr(); white(); if ($relaxed and $ch eq '}') { --$depth; next_chr(); if ($F_HOOK) { return _json_object_hook($o); } return $o; } } } $at--; decode_error(", or } expected while parsing object/hash"); } sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition my $key; while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){ $key .= $ch; next_chr(); } return $key; } sub word { my $word = substr($text,$at-1,4); if($word eq 'true'){ $at += 3; next_chr; return $JSON::PP::true; } elsif($word eq 'null'){ $at += 3; next_chr; return undef; } elsif($word eq 'fals'){ $at += 3; if(substr($text,$at,1) eq 'e'){ $at++; next_chr; return $JSON::PP::false; } } $at--; # for decode_error report decode_error("'null' expected") if ($word =~ /^n/); decode_error("'true' expected") if ($word =~ /^t/); decode_error("'false' expected") if ($word =~ /^f/); decode_error("malformed JSON string, neither array, object, number, string or atom"); } sub number { my $n = ''; my $v; # According to RFC4627, hex or oct digts are invalid. if($ch eq '0'){ my $peek = substr($text,$at,1); my $hex = $peek =~ /[xX]/; # 0 or 1 if($hex){ decode_error("malformed number (leading zero must not be followed by another digit)"); ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/); } else{ # oct ($n) = ( substr($text, $at) =~ /^([0-7]+)/); if (defined $n and length $n > 1) { decode_error("malformed number (leading zero must not be followed by another digit)"); } } if(defined $n and length($n)){ if (!$hex and length($n) == 1) { decode_error("malformed number (leading zero must not be followed by another digit)"); } $at += length($n) + $hex; next_chr; return $hex ? hex($n) : oct($n); } } if($ch eq '-'){ $n = '-'; next_chr; if (!defined $ch or $ch !~ /\d/) { decode_error("malformed number (no digits after initial minus)"); } } while(defined $ch and $ch =~ /\d/){ $n .= $ch; next_chr; } if(defined $ch and $ch eq '.'){ $n .= '.'; next_chr; if (!defined $ch or $ch !~ /\d/) { decode_error("malformed number (no digits after decimal point)"); } else { $n .= $ch; } while(defined(next_chr) and $ch =~ /\d/){ $n .= $ch; } } if(defined $ch and ($ch eq 'e' or $ch eq 'E')){ $n .= $ch; next_chr; if(defined($ch) and ($ch eq '+' or $ch eq '-')){ $n .= $ch; next_chr; if (!defined $ch or $ch =~ /\D/) { decode_error("malformed number (no digits after exp sign)"); } $n .= $ch; } elsif(defined($ch) and $ch =~ /\d/){ $n .= $ch; } else { decode_error("malformed number (no digits after exp sign)"); } while(defined(next_chr) and $ch =~ /\d/){ $n .= $ch; } } $v .= $n; if ($v !~ /[.eE]/ and length $v > $max_intsize) { if ($allow_bigint) { # from Adam Sussman require Math::BigInt; return Math::BigInt->new($v); } else { return "$v"; } } elsif ($allow_bigint) { require Math::BigFloat; return Math::BigFloat->new($v); } return 0+$v; } sub is_valid_utf8 { $utf8_len = $_[0] =~ /[\x00-\x7F]/ ? 1 : $_[0] =~ /[\xC2-\xDF]/ ? 2 : $_[0] =~ /[\xE0-\xEF]/ ? 3 : $_[0] =~ /[\xF0-\xF4]/ ? 4 : 0 ; return unless $utf8_len; my $is_valid_utf8 = substr($text, $at - 1, $utf8_len); return ( $is_valid_utf8 =~ /^(?: [\x00-\x7F] |[\xC2-\xDF][\x80-\xBF] |[\xE0][\xA0-\xBF][\x80-\xBF] |[\xE1-\xEC][\x80-\xBF][\x80-\xBF] |[\xED][\x80-\x9F][\x80-\xBF] |[\xEE-\xEF][\x80-\xBF][\x80-\xBF] |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF] |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF] |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF] )$/x ) ? $is_valid_utf8 : ''; } sub decode_error { my $error = shift; my $no_rep = shift; my $str = defined $text ? substr($text, $at) : ''; my $mess = ''; my $type = $] >= 5.008 ? 'U*' : $] < 5.006 ? 'C*' : utf8::is_utf8( $str ) ? 'U*' # 5.6 : 'C*' ; for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ? $mess .= $c == 0x07 ? '\a' : $c == 0x09 ? '\t' : $c == 0x0a ? '\n' : $c == 0x0d ? '\r' : $c == 0x0c ? '\f' : $c < 0x20 ? sprintf('\x{%x}', $c) : $c == 0x5c ? '\\\\' : $c < 0x80 ? chr($c) : sprintf('\x{%x}', $c) ; if ( length $mess >= 20 ) { $mess .= '...'; last; } } unless ( length $mess ) { $mess = '(end of string)'; } Carp::croak ( $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")" ); } sub _json_object_hook { my $o = $_[0]; my @ks = keys %{$o}; if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) { my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} ); if (@val == 1) { return $val[0]; } } my @val = $cb_object->($o) if ($cb_object); if (@val == 0 or @val > 1) { return $o; } else { return $val[0]; } } sub PP_decode_box { { text => $text, at => $at, ch => $ch, len => $len, depth => $depth, encoding => $encoding, is_valid_utf8 => $is_valid_utf8, }; } } # PARSE sub _decode_surrogates { # from perlunicode my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00); my $un = pack('U*', $uni); utf8::encode( $un ); return $un; } sub _decode_unicode { my $un = pack('U', hex shift); utf8::encode( $un ); return $un; } # # Setup for various Perl versions (the code from JSON::PP58) # BEGIN { unless ( defined &utf8::is_utf8 ) { require Encode; *utf8::is_utf8 = *Encode::is_utf8; } if ( $] >= 5.008 ) { *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii; *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1; *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates; *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode; } if ($] >= 5.008 and $] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken. package JSON::PP; require subs; subs->import('join'); eval q| sub join { return '' if (@_ < 2); my $j = shift; my $str = shift; for (@_) { $str .= $j . $_; } return $str; } |; } sub JSON::PP::incr_parse { local $Carp::CarpLevel = 1; ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ ); } sub JSON::PP::incr_skip { ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip; } sub JSON::PP::incr_reset { ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset; } eval q{ sub JSON::PP::incr_text : lvalue { $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new; if ( $_[0]->{_incr_parser}->{incr_parsing} ) { Carp::croak("incr_text can not be called when the incremental parser already started parsing"); } $_[0]->{_incr_parser}->{incr_text}; } } if ( $] >= 5.006 ); } # Setup for various Perl versions (the code from JSON::PP58) ############################### # Utilities # BEGIN { eval 'require Scalar::Util'; unless($@){ *JSON::PP::blessed = \&Scalar::Util::blessed; *JSON::PP::reftype = \&Scalar::Util::reftype; *JSON::PP::refaddr = \&Scalar::Util::refaddr; } else{ # This code is from Sclar::Util. # warn $@; eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }'; *JSON::PP::blessed = sub { local($@, $SIG{__DIE__}, $SIG{__WARN__}); ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef; }; my %tmap = qw( B::NULL SCALAR B::HV HASH B::AV ARRAY B::CV CODE B::IO IO B::GV GLOB B::REGEXP REGEXP ); *JSON::PP::reftype = sub { my $r = shift; return undef unless length(ref($r)); my $t = ref(B::svref_2object($r)); return exists $tmap{$t} ? $tmap{$t} : length(ref($$r)) ? 'REF' : 'SCALAR'; }; *JSON::PP::refaddr = sub { return undef unless length(ref($_[0])); my $addr; if(defined(my $pkg = blessed($_[0]))) { $addr .= bless $_[0], 'Scalar::Util::Fake'; bless $_[0], $pkg; } else { $addr .= $_[0] } $addr =~ /0x(\w+)/; local $^W; #no warnings 'portable'; hex($1); } } } # shamely copied and modified from JSON::XS code. $JSON::PP::true = do { bless \(my $dummy = 1), "JSON::PP::Boolean" }; $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" }; sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); } sub true { $JSON::PP::true } sub false { $JSON::PP::false } sub null { undef; } ############################### package JSON::PP::Boolean; use overload ( "0+" => sub { ${$_[0]} }, "++" => sub { $_[0] = ${$_[0]} + 1 }, "--" => sub { $_[0] = ${$_[0]} - 1 }, fallback => 1, ); ############################### package JSON::PP::IncrParser; use strict; use constant INCR_M_WS => 0; # initial whitespace skipping use constant INCR_M_STR => 1; # inside string use constant INCR_M_BS => 2; # inside backslash use constant INCR_M_JSON => 3; # outside anything, count nesting use constant INCR_M_C0 => 4; use constant INCR_M_C1 => 5; $JSON::PP::IncrParser::VERSION = '1.01'; my $unpack_format = $] < 5.006 ? 'C*' : 'U*'; sub new { my ( $class ) = @_; bless { incr_nest => 0, incr_text => undef, incr_parsing => 0, incr_p => 0, }, $class; } sub incr_parse { my ( $self, $coder, $text ) = @_; $self->{incr_text} = '' unless ( defined $self->{incr_text} ); if ( defined $text ) { if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) { utf8::upgrade( $self->{incr_text} ) ; utf8::decode( $self->{incr_text} ) ; } $self->{incr_text} .= $text; } my $max_size = $coder->get_max_size; if ( defined wantarray ) { $self->{incr_mode} = INCR_M_WS unless defined $self->{incr_mode}; if ( wantarray ) { my @ret; $self->{incr_parsing} = 1; do { push @ret, $self->_incr_parse( $coder, $self->{incr_text} ); unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) { $self->{incr_mode} = INCR_M_WS if $self->{incr_mode} != INCR_M_STR; } } until ( length $self->{incr_text} >= $self->{incr_p} ); $self->{incr_parsing} = 0; return @ret; } else { # in scalar context $self->{incr_parsing} = 1; my $obj = $self->_incr_parse( $coder, $self->{incr_text} ); $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans return $obj ? $obj : undef; # $obj is an empty string, parsing was completed. } } } sub _incr_parse { my ( $self, $coder, $text, $skip ) = @_; my $p = $self->{incr_p}; my $restore = $p; my @obj; my $len = length $text; if ( $self->{incr_mode} == INCR_M_WS ) { while ( $len > $p ) { my $s = substr( $text, $p, 1 ); $p++ and next if ( 0x20 >= unpack($unpack_format, $s) ); $self->{incr_mode} = INCR_M_JSON; last; } } while ( $len > $p ) { my $s = substr( $text, $p++, 1 ); if ( $s eq '"' ) { if (substr( $text, $p - 2, 1 ) eq '\\' ) { next; } if ( $self->{incr_mode} != INCR_M_STR ) { $self->{incr_mode} = INCR_M_STR; } else { $self->{incr_mode} = INCR_M_JSON; unless ( $self->{incr_nest} ) { last; } } } if ( $self->{incr_mode} == INCR_M_JSON ) { if ( $s eq '[' or $s eq '{' ) { if ( ++$self->{incr_nest} > $coder->get_max_depth ) { Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)'); } } elsif ( $s eq ']' or $s eq '}' ) { last if ( --$self->{incr_nest} <= 0 ); } elsif ( $s eq '#' ) { while ( $len > $p ) { last if substr( $text, $p++, 1 ) eq "\n"; } } } } $self->{incr_p} = $p; return if ( $self->{incr_mode} == INCR_M_STR and not $self->{incr_nest} ); return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 ); return '' unless ( length substr( $self->{incr_text}, 0, $p ) ); local $Carp::CarpLevel = 2; $self->{incr_p} = $restore; $self->{incr_c} = $p; my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 ); $self->{incr_text} = substr( $self->{incr_text}, $p ); $self->{incr_p} = 0; return $obj || ''; } sub incr_text { if ( $_[0]->{incr_parsing} ) { Carp::croak("incr_text can not be called when the incremental parser already started parsing"); } $_[0]->{incr_text}; } sub incr_skip { my $self = shift; $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} ); $self->{incr_p} = 0; } sub incr_reset { my $self = shift; $self->{incr_text} = undef; $self->{incr_p} = 0; $self->{incr_mode} = 0; $self->{incr_nest} = 0; $self->{incr_parsing} = 0; } ############################### 1; __END__ =pod =head1 NAME JSON::PP - JSON::XS compatible pure-Perl module. =head1 SYNOPSIS use JSON::PP; # exported functions, they croak on error # and expect/generate UTF-8 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; # OO-interface $coder = JSON::PP->new->ascii->pretty->allow_nonref; $json_text = $json->encode( $perl_scalar ); $perl_scalar = $json->decode( $json_text ); $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing # Note that JSON version 2.0 and above will automatically use # JSON::XS or JSON::PP, so you should be able to just: use JSON; =head1 VERSION 2.27202 L 2.27 (~2.30) compatible. =head1 NOTE JSON::PP had been inculded in JSON distribution (CPAN module). It was a perl core module in Perl 5.14. =head1 DESCRIPTION This module is L compatible pure Perl module. (Perl 5.8 or later is recommended) JSON::XS is the fastest and most proper JSON module on CPAN. It is written by Marc Lehmann in C, so must be compiled and installed in the used environment. JSON::PP is a pure-Perl module and has compatibility to JSON::XS. =head2 FEATURES =over =item * correct unicode handling This module knows how to handle Unicode (depending on Perl version). See to L and L. =item * round-trip integrity When you serialise a perl data structure using only data types supported by JSON and Perl, the deserialised data structure is identical on the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" just because it looks like a number). There I minor exceptions to this, read the MAPPING section below to learn about those. =item * strict checking of JSON correctness There is no guessing, no generating of illegal JSON texts by default, and only JSON is accepted as input by default (the latter is a security feature). But when some options are set, loose chcking features are available. =back =head1 FUNCTIONAL INTERFACE Some documents are copied and modified from L. =head2 encode_json $json_text = encode_json $perl_scalar Converts the given Perl data structure to a UTF-8 encoded, binary string. This function call is functionally identical to: $json_text = JSON::PP->new->utf8->encode($perl_scalar) =head2 decode_json $perl_scalar = decode_json $json_text The opposite of C: expects an UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. This function call is functionally identical to: $perl_scalar = JSON::PP->new->utf8->decode($json_text) =head2 JSON::PP::is_bool $is_boolean = JSON::PP::is_bool($scalar) Returns true if the passed scalar represents either JSON::PP::true or JSON::PP::false, two constants that act like C<1> and C<0> respectively and are also used to represent JSON C and C in Perl strings. =head2 JSON::PP::true Returns JSON true value which is blessed object. It C JSON::PP::Boolean object. =head2 JSON::PP::false Returns JSON false value which is blessed object. It C JSON::PP::Boolean object. =head2 JSON::PP::null Returns C. See L, below, for more information on how JSON values are mapped to Perl. =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER This section supposes that your perl vresion is 5.8 or later. If you know a JSON text from an outer world - a network, a file content, and so on, is encoded in UTF-8, you should use C or C module object with C enable. And the decoded result will contain UNICODE characters. # from network my $json = JSON::PP->new->utf8; my $json_text = CGI->new->param( 'json_data' ); my $perl_scalar = $json->decode( $json_text ); # from file content local $/; open( my $fh, '<', 'json.data' ); $json_text = <$fh>; $perl_scalar = decode_json( $json_text ); If an outer data is not encoded in UTF-8, firstly you should C it. use Encode; local $/; open( my $fh, '<', 'json.data' ); my $encoding = 'cp932'; my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE # or you can write the below code. # # open( my $fh, "<:encoding($encoding)", 'json.data' ); # $unicode_json_text = <$fh>; In this case, C<$unicode_json_text> is of course UNICODE string. So you B use C nor C module object with C enable. Instead of them, you use C module object with C disable. $perl_scalar = $json->utf8(0)->decode( $unicode_json_text ); Or C and C: $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) ); # this way is not efficient. And now, you want to convert your C<$perl_scalar> into JSON data and send it to an outer world - a network or a file content, and so on. Your data usually contains UNICODE strings and you want the converted data to be encoded in UTF-8, you should use C or C module object with C enable. print encode_json( $perl_scalar ); # to a network? file? or display? # or print $json->utf8->encode( $perl_scalar ); If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings for some reason, then its characters are regarded as B for perl (because it does not concern with your $encoding). You B use C nor C module object with C enable. Instead of them, you use C module object with C disable. Note that the resulted text is a UNICODE string but no problem to print it. # $perl_scalar contains $encoding encoded string values $unicode_json_text = $json->utf8(0)->encode( $perl_scalar ); # $unicode_json_text consists of characters less than 0x100 print $unicode_json_text; Or C all string values and C: $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } ); # ... do it to each string values, then encode_json $json_text = encode_json( $perl_scalar ); This method is a proper way but probably not efficient. See to L, L. =head1 METHODS Basically, check to L or L. =head2 new $json = JSON::PP->new Rturns a new JSON::PP object that can be used to de/encode JSON strings. All boolean flags described below are by default I. The mutators for flags all return the JSON object again and thus calls can be chained: my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]}) => {"a": [1, 2]} =head2 ascii $json = $json->ascii([$enable]) $enabled = $json->get_ascii If $enable is true (or missing), then the encode method will not generate characters outside the code range 0..127. Any Unicode characters outside that range will be escaped using either a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. (See to L). In Perl 5.005, there is no character having high value (more than 255). See to L. If $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format. JSON::PP->new->ascii(1)->encode([chr 0x10401]) => ["\ud801\udc01"] =head2 latin1 $json = $json->latin1([$enable]) $enabled = $json->get_latin1 If $enable is true (or missing), then the encode method will encode the resulting JSON text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255. If $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags. JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) See to L. =head2 utf8 $json = $json->utf8([$enable]) $enabled = $json->get_utf8 If $enable is true (or missing), then the encode method will encode the JSON result into UTF-8, as required by many protocols, while the decode method expects to be handled an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range 0..255, they are thus useful for bytewise/binary I/O. (In Perl 5.005, any character outside the range 0..255 does not exist. See to L.) In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627. If $enable is false, then the encode method will return the JSON string as a (non-encoded) Unicode string, while decode expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module. Example, output UTF-16BE-encoded JSON: use Encode; $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object); Example, decode UTF-32LE-encoded JSON: use Encode; $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext); =head2 pretty $json = $json->pretty([$enable]) This enables (or disables) all of the C, C and C flags in one call to generate the most readable (or most compact) form possible. Equivalent to: $json->indent->space_before->space_after =head2 indent $json = $json->indent([$enable]) $enabled = $json->get_indent The default indent space length is three. You can use C to change the length. =head2 space_before $json = $json->space_before([$enable]) $enabled = $json->get_space_before If C<$enable> is true (or missing), then the C method will add an extra optional space before the C<:> separating keys from values in JSON objects. If C<$enable> is false, then the C method will not add any extra space at those places. This setting has no effect when decoding JSON texts. Example, space_before enabled, space_after and indent disabled: {"key" :"value"} =head2 space_after $json = $json->space_after([$enable]) $enabled = $json->get_space_after If C<$enable> is true (or missing), then the C method will add an extra optional space after the C<:> separating keys from values in JSON objects and extra whitespace after the C<,> separating key-value pairs and array members. If C<$enable> is false, then the C method will not add any extra space at those places. This setting has no effect when decoding JSON texts. Example, space_before and indent disabled, space_after enabled: {"key": "value"} =head2 relaxed $json = $json->relaxed([$enable]) $enabled = $json->get_relaxed If C<$enable> is true (or missing), then C will accept some extensions to normal JSON syntax (see below). C will not be affected in anyway. I. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.) If C<$enable> is false (the default), then C will only accept valid JSON texts. Currently accepted extensions are: =over 4 =item * list items can have an end-comma JSON I array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them: [ 1, 2, <- this comma not normally allowed ] { "k1": "v1", "k2": "v2", <- this comma not normally allowed } =item * shell-style '#'-comments Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed. [ 1, # this comment not allowed in JSON # neither this one... ] =back =head2 canonical $json = $json->canonical([$enable]) $enabled = $json->get_canonical If C<$enable> is true (or missing), then the C method will output JSON objects by sorting their keys. This is adding a comparatively high overhead. If C<$enable> is false, then the C method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script). This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl. This setting has no effect when decoding JSON texts. If you want your own sorting routine, you can give a code referece or a subroutine name to C. See to C. =head2 allow_nonref $json = $json->allow_nonref([$enable]) $enabled = $json->get_allow_nonref If C<$enable> is true (or missing), then the C method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, C will accept those JSON values instead of croaking. If C<$enable> is false, then the C method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, C will croak if given something that is not a JSON object or array. JSON::PP->new->allow_nonref->encode ("Hello, World!") => "Hello, World!" =head2 allow_unknown $json = $json->allow_unknown ([$enable]) $enabled = $json->get_allow_unknown If $enable is true (or missing), then "encode" will *not* throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON "null" value. Note that blessed objects are not included here and are handled separately by c. If $enable is false (the default), then "encode" will throw an exception when it encounters anything it cannot encode as JSON. This option does not affect "decode" in any way, and it is recommended to leave it off unless you know your communications partner. =head2 allow_blessed $json = $json->allow_blessed([$enable]) $enabled = $json->get_allow_blessed If C<$enable> is true (or missing), then the C method will not barf when it encounters a blessed reference. Instead, the value of the B option will decide whether C (C disabled or no C method found) or a representation of the object (C enabled and C method found) is being encoded. Has no effect on C. If C<$enable> is false (the default), then C will throw an exception when it encounters a blessed object. =head2 convert_blessed $json = $json->convert_blessed([$enable]) $enabled = $json->get_convert_blessed If C<$enable> is true (or missing), then C, upon encountering a blessed object, will check for the availability of the C method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object. If no C method is found, the value of C will decide what to do. The C method may safely call die if it wants. If C returns other blessed objects, those will be handled in the same way. C must take care of not causing an endless recursion cycle (== crash) in this case. The name of C was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with the C function or method. This setting does not yet influence C in any way. If C<$enable> is false, then the C setting will decide what to do when a blessed object is found. =head2 filter_json_object $json = $json->filter_json_object([$coderef]) When C<$coderef> is specified, it will be called from C each time it decodes a JSON object. The only argument passed to the coderef is a reference to the newly-created hash. If the code references returns a single scalar (which need not be a reference), this value (i.e. a copy of that scalar to avoid aliasing) is inserted into the deserialised data structure. If it returns an empty list (NOTE: I C, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably. When C<$coderef> is omitted or undefined, any existing callback will be removed and C will not change the deserialised hash in any way. Example, convert all JSON objects into the integer 5: my $js = JSON::PP->new->filter_json_object (sub { 5 }); # returns [5] $js->decode ('[{}]'); # the given subroutine takes a hash reference. # throw an exception because allow_nonref is not enabled # so a lone 5 is not allowed. $js->decode ('{"a":1, "b":2}'); =head2 filter_json_single_key_object $json = $json->filter_json_single_key_object($key [=> $coderef]) Works remotely similar to C, but is only called for JSON objects having a single key named C<$key>. This C<$coderef> is called before the one specified via C, if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even C but the empty list), the callback from C will be called next, as if no single-key callback were specified. If C<$coderef> is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key. As this callback gets called less often then the C one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialise Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash. Typical names for the single object key are C<__class_whatever__>, or C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even things like C<__class_md5sum(classname)__>, to reduce the risk of clashing with real hashes. Example, decode JSON objects of the form C<< { "__widget__" => } >> into the corresponding C<< $WIDGET{} >> object: # return whatever is in $WIDGET{5}: JSON::PP ->new ->filter_json_single_key_object (__widget__ => sub { $WIDGET{ $_[0] } }) ->decode ('{"__widget__": 5') # this can be used with a TO_JSON method in some "widget" class # for serialisation to json: sub WidgetBase::TO_JSON { my ($self) = @_; unless ($self->{id}) { $self->{id} = ..get..some..id..; $WIDGET{$self->{id}} = $self; } { __widget__ => $self->{id} } } =head2 shrink $json = $json->shrink([$enable]) $enabled = $json->get_shrink In JSON::XS, this flag resizes strings generated by either C or C to their minimum size possible. It will also try to downgrade any strings to octet-form if possible. In JSON::PP, it is noop about resizing strings but tries C to the returned string by C. See to L. See to L =head2 max_depth $json = $json->max_depth([$maximum_nesting_depth]) $max_depth = $json->get_max_depth Sets the maximum nesting level (default C<512>) accepted while encoding or decoding. If a higher nesting level is detected in JSON text or a Perl data structure, then the encoder and decoder will stop and croak at that point. Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of C<{> or C<[> characters without their matching closing parenthesis crossed to reach a given character in a string. If no argument is given, the highest possible setting will be used, which is rarely useful. See L for more info on why this is useful. When a large value (100 or more) was set and it de/encodes a deep nested object/text, it may raise a warning 'Deep recursion on subroutin' at the perl runtime phase. =head2 max_size $json = $json->max_size([$maximum_string_size]) $max_size = $json->get_max_size Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is C<0>, meaning no limit. When C is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on C (yet). If no argument is given, the limit check will be deactivated (same as when C<0> is specified). See L for more info on why this is useful. =head2 encode $json_text = $json->encode($perl_scalar) Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its JSON representation. Simple scalars will be converted into JSON string or number sequences, while references to arrays become JSON arrays and references to hashes become JSON objects. Undefined Perl values (e.g. C) become JSON C values. References to the integers C<0> and C<1> are converted into C and C. =head2 decode $perl_scalar = $json->decode($json_text) The opposite of C: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error. JSON numbers and strings become simple Perl scalars. JSON arrays become Perl arrayrefs and JSON objects become Perl hashrefs. C becomes C<1> (C), C becomes C<0> (C) and C becomes C. =head2 decode_prefix ($perl_scalar, $characters) = $json->decode_prefix($json_text) This works like the C method, but instead of raising an exception when there is trailing garbage after the first JSON object, it will silently stop parsing there and return the number of characters consumed so far. JSON->new->decode_prefix ("[1] the tail") => ([], 3) =head1 INCREMENTAL PARSING Most of this section are copied and modified from L. In some cases, there is the need for incremental parsing of JSON texts. This module does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to using C to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls). This module will only attempt to parse the JSON text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won't stop as early as the full parser, for example, it doesn't detect parenthese mismatches. The only thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. This means you need to set resource limits (e.g. C) to ensure the parser will stop parsing in the presence if syntax errors. The following methods implement this incremental parser. =head2 incr_parse $json->incr_parse( [$string] ) # void context $obj_or_undef = $json->incr_parse( [$string] ) # scalar context @obj_or_empty = $json->incr_parse( [$string] ) # list context This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional). If C<$string> is given, then this string is appended to the already existing JSON fragment stored in the C<$json> object. After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want. If the method is called in scalar context, then it will try to extract exactly I JSON object. If that is successful, it will return this object, otherwise it will return C. If there is a parse error, this method will croak just as C would do (one can then use C to skip the errornous part). This is the most common way of using the method. And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators between the JSON objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed JSON texts will be lost. Example: Parse some JSON arrays/objects in a given string and return them. my @objs = JSON->new->incr_parse ("[5][7][1,2]"); =head2 incr_text $lvalue_string = $json->incr_text This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This I works when a preceding call to C in I successfully returned an object. Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it I fail under real world conditions). As a special exception, you can also call this method before having parsed anything. This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas). $json->incr_text =~ s/\s*,\s*//; In Perl 5.005, C attribute is not available. You must write codes like the below: $string = $json->incr_text; $string =~ s/\s*,\s*//; $json->incr_text( $string ); =head2 incr_skip $json->incr_skip This will reset the state of the incremental parser and will remove the parsed text from the input buffer. This is useful after C died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state. =head2 incr_reset $json->incr_reset This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything. This is useful if you want ot repeatedly parse JSON objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode. See to L for examples. =head1 JSON::PP OWN METHODS =head2 allow_singlequote $json = $json->allow_singlequote([$enable]) If C<$enable> is true (or missing), then C will accept JSON strings quoted by single quotations that are invalid JSON format. $json->allow_singlequote->decode({"foo":'bar'}); $json->allow_singlequote->decode({'foo':"bar"}); $json->allow_singlequote->decode({'foo':'bar'}); As same as the C option, this option may be used to parse application-specific files written by humans. =head2 allow_barekey $json = $json->allow_barekey([$enable]) If C<$enable> is true (or missing), then C will accept bare keys of JSON object that are invalid JSON format. As same as the C option, this option may be used to parse application-specific files written by humans. $json->allow_barekey->decode('{foo:"bar"}'); =head2 allow_bignum $json = $json->allow_bignum([$enable]) If C<$enable> is true (or missing), then C will convert the big integer Perl cannot handle as integer into a L object and convert a floating number (any) into a L. On the contary, C converts C objects and C objects into JSON numbers with C enable. $json->allow_nonref->allow_blessed->allow_bignum; $bigfloat = $json->decode('2.000000000000000000000000001'); print $json->encode($bigfloat); # => 2.000000000000000000000000001 See to L aboout the normal conversion of JSON number. =head2 loose $json = $json->loose([$enable]) The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings and the module doesn't allow to C to these (except for \x2f). If C<$enable> is true (or missing), then C will accept these unescaped strings. $json->loose->decode(qq|["abc def"]|); See L. =head2 escape_slash $json = $json->escape_slash([$enable]) According to JSON Grammar, I (U+002F) is escaped. But default JSON::PP (as same as JSON::XS) encodes strings without escaping slash. If C<$enable> is true (or missing), then C will escape slashes. =head2 indent_length $json = $json->indent_length($length) JSON::XS indent space length is 3 and cannot be changed. JSON::PP set the indent space length with the given $length. The default is 3. The acceptable range is 0 to 15. =head2 sort_by $json = $json->sort_by($function_name) $json = $json->sort_by($subroutine_ref) If $function_name or $subroutine_ref are set, its sort routine are used in encoding JSON objects. $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj); # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); $js = $pc->sort_by('own_sort')->encode($obj); # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b } As the sorting routine runs in the JSON::PP scope, the given subroutine name and the special variables C<$a>, C<$b> will begin 'JSON::PP::'. If $integer is set, then the effect is same as C on. =head1 INTERNAL For developers. =over =item PP_encode_box Returns { depth => $depth, indent_count => $indent_count, } =item PP_decode_box Returns { text => $text, at => $at, ch => $ch, len => $len, depth => $depth, encoding => $encoding, is_valid_utf8 => $is_valid_utf8, }; =back =head1 MAPPING This section is copied from JSON::XS and modified to C. JSON::XS and JSON::PP mapping mechanisms are almost equivalent. See to L. =head2 JSON -> PERL =over 4 =item object A JSON object becomes a reference to a hash in Perl. No ordering of object keys is preserved (JSON does not preserver object key ordering itself). =item array A JSON array becomes a reference to an array in Perl. =item string A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary. =item number A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers. If the number consists of digits only, C will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded toa JSON string). Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number). Note that precision is not accuracy - binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, C only guarantees precision up to but not including the leats significant bit. When C is enable, the big integers and the numeric can be optionally converted into L and L objects. =item true, false These JSON atoms become C and C, respectively. They are overloaded to act almost exactly like the numbers C<1> and C<0>. You can check wether a scalar is a JSON boolean by using the C function. print JSON::PP::true . "\n"; => true print JSON::PP::true + 1; => 1 ok(JSON::true eq '1'); ok(JSON::true == 1); C will install these missing overloading features to the backend modules. =item null A JSON null atom becomes C in Perl. C returns C. =back =head2 PERL -> JSON The mapping from Perl to JSON is slightly more difficult, as Perl is a truly typeless language, so we can only guess which JSON type is meant by a Perl value. =over 4 =item hash references Perl hash references become JSON objects. As there is no inherent ordering in hash keys (or JSON objects), they will usually be encoded in a pseudo-random order that can change between runs of the same program but stays generally the same within a single run of a program. C optionally sort the hash keys (determined by the I flag), so the same datastructure will serialise to the same JSON text (given same settings and version of JSON::XS), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some JSON text against another for equality. =item array references Perl array references become JSON arrays. =item other references Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers C<0> and C<1>, which get turned into C and C atoms in JSON. You can also use C and C to improve readability. to_json [\0,JSON::PP::true] # yields [false,true] =item JSON::PP::true, JSON::PP::false, JSON::PP::null These special values become JSON true and JSON false values, respectively. You can also use C<\1> and C<\0> directly if you want. JSON::PP::null returns C. =item blessed objects Blessed objects are not directly representable in JSON. See the C and C methods on various options on how to deal with this: basically, you can choose between throwing an exception, encoding the reference as if it weren't blessed, or provide your own serialiser method. See to L. =item simple scalars Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as JSON C values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value: # dump as number encode_json [2] # yields [2] encode_json [-3.0e17] # yields [-3e+17] my $value = 5; encode_json [$value] # yields [5] # used as string, so dump as string print $value; encode_json [$value] # yields ["5"] # undef becomes null encode_json [undef] # yields [null] You can force the type to be a string by stringifying it: my $x = 3.1; # some variable containing a number "$x"; # stringified $x .= ""; # another, more awkward way to stringify print $x; # perl does it for you, too, quite often You can force the type to be a number by numifying it: my $x = "3"; # some variable containing a string $x += 0; # numify it, ensuring it will be dumped as a number $x *= 1; # same thing, the choise is yours. You can not currently force the type in other, less obscure, ways. Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN's - these cannot be represented in JSON, and it is an error to pass those in. =item Big Number When C is enable, C converts C objects and C objects into JSON numbers. =back =head1 UNICODE HANDLING ON PERLS If you do not know about Unicode on Perl well, please check L. =head2 Perl 5.8 and later Perl can handle Unicode and the JSON::PP de/encode methods also work properly. $json->allow_nonref->encode(chr hex 3042); $json->allow_nonref->encode(chr hex 12345); Reuturns C<"\u3042"> and C<"\ud808\udf45"> respectively. $json->allow_nonref->decode('"\u3042"'); $json->allow_nonref->decode('"\ud808\udf45"'); Returns UTF-8 encoded strings with UTF8 flag, regarded as C and C. Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in C was broken, so JSON::PP wraps the C with a subroutine. Thus JSON::PP works slow in the versions. =head2 Perl 5.6 Perl can handle Unicode and the JSON::PP de/encode methods also work. =head2 Perl 5.005 Perl 5.005 is a byte sementics world -- all strings are sequences of bytes. That means the unicode handling is not available. In encoding, $json->allow_nonref->encode(chr hex 3042); # hex 3042 is 12354. $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565. Returns C and C, as C takes a value more than 255, it treats as C<$value % 256>, so the above codes are equivalent to : $json->allow_nonref->encode(chr 66); $json->allow_nonref->encode(chr 69); In decoding, $json->decode('"\u00e3\u0081\u0082"'); The returned is a byte sequence C<0xE3 0x81 0x82> for UTF-8 encoded japanese character (C). And if it is represented in Unicode code point, C. Next, $json->decode('"\u3042"'); We ordinary expect the returned value is a Unicode character C. But here is 5.005 world. This is C<0xE3 0x81 0x82>. $json->decode('"\ud808\udf45"'); This is not a character C but bytes - C<0xf0 0x92 0x8d 0x85>. =head1 TODO =over =item speed =item memory saving =back =head1 SEE ALSO Most of the document are copied and modified from JSON::XS doc. L RFC4627 (L) =head1 AUTHOR Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE =head1 COPYRIGHT AND LICENSE Copyright 2007-2013 by Makamaka Hannyaharamitu This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!´û¡�ùùperl5/Test2.pmnuÏÃ6Ç$package Test2; use strict; use warnings; our $VERSION = '1.302183'; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2 - Framework for writing test tools that all work together. =head1 DESCRIPTION Test2 is a new testing framework produced by forking L, completely refactoring it, adding many new features and capabilities. =head2 WHAT IS NEW? =over 4 =item Easier to test new testing tools. From the beginning Test2 was built with introspection capabilities. With Test::Builder it was difficult at best to capture test tool output for verification. Test2 Makes it easy with C. =item Better diagnostics capabilities. Test2 uses an L object to track filename, line number, and tool details. This object greatly simplifies tracking for where errors should be reported. =item Event driven. Test2 based tools produce events which get passed through a processing system before being output by a formatter. This event system allows for rich plugin and extension support. =item More complete API. Test::Builder only provided a handful of methods for generating lines of TAP. Test2 took inventory of everything people were doing with Test::Builder that required hacking it up. Test2 made public API functions for nearly all the desired functionality people didn't previously have. =item Support for output other than TAP. Test::Builder assumed everything would end up as TAP. Test2 makes no such assumption. Test2 provides ways for you to specify alternative and custom formatters. =item Subtest implementation is more sane. The Test::Builder implementation of subtests was certifiably insane. Test2 uses a stacked event hub system that greatly improves how subtests are implemented. =item Support for threading/forking. Test2 support for forking and threading can be turned on using L. Once turned on threading and forking operate sanely and work as one would expect. =back =head1 GETTING STARTED If you are interested in writing tests using new tools then you should look at L. L is a separate cpan distribution that contains many tools implemented on Test2. If you are interested in writing new tools you should take a look at L first. =head1 NAMESPACE LAYOUT This describes the namespace layout for the Test2 ecosystem. Not all the namespaces listed here are part of the Test2 distribution, some are implemented in L. =head2 Test2::Tools:: This namespace is for sets of tools. Modules in this namespace should export tools like C and C. Most things written for Test2 should go here. Modules in this namespace B export subs from other tools. See the L namespace if you want to do that. =head2 Test2::Plugin:: This namespace is for plugins. Plugins are modules that change or enhance the behavior of Test2. An example of a plugin is a module that sets the encoding to utf8 globally. Another example is a module that causes a bail-out event after the first test failure. =head2 Test2::Bundle:: This namespace is for bundles of tools and plugins. Loading one of these may load multiple tools and plugins. Modules in this namespace should not implement tools directly. In general modules in this namespace should load tools and plugins, then re-export things into the consumers namespace. =head2 Test2::Require:: This namespace is for modules that cause a test to be skipped when conditions do not allow it to run. Examples would be modules that skip the test on older perls, or when non-essential modules have not been installed. =head2 Test2::Formatter:: Formatters live under this namespace. L is the only formatter currently. It is acceptable for third party distributions to create new formatters under this namespace. =head2 Test2::Event:: Events live under this namespace. It is considered acceptable for third party distributions to add new event types in this namespace. =head2 Test2::Hub:: Hub subclasses (and some hub utility objects) live under this namespace. It is perfectly reasonable for third party distributions to add new hub subclasses in this namespace. =head2 Test2::IPC:: The IPC subsystem lives in this namespace. There are not many good reasons to add anything to this namespace, with exception of IPC drivers. =head3 Test2::IPC::Driver:: IPC drivers live in this namespace. It is fine to create new IPC drivers and to put them in this namespace. =head2 Test2::Util:: This namespace is for general utilities used by testing tools. Please be considerate when adding new modules to this namespace. =head2 Test2::API:: This is for Test2 API and related packages. =head2 Test2:: The Test2:: namespace is intended for extensions and frameworks. Tools, Plugins, etc should not go directly into this namespace. However extensions that are used to build tools and plugins may go here. In short: If the module exports anything that should be run directly by a test script it should probably NOT go directly into C. =head1 SEE ALSO L - Primary API functions. L - Detailed documentation of the context object. L - The IPC system used for threading/fork support. L - Formatters such as TAP live here. L - Events live in this namespace. L - All events eventually funnel through a hub. Custom hubs are how C and C are implemented. =head1 CONTACTING US Many Test2 developers and users lurk on L and L. We also have a slack team that can be joined by anyone with an C<@cpan.org> email address L If you do not have an C<@cpan.org> email you can ask for a slack invite by emailing Chad Granum Eexodist@cpan.orgE. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ԋ͘¹G¹Gperl5/Getopt/Long.pmnuÏÃ6Ç$#! perl # Getopt::Long.pm -- Universal options parsing # Author : Johan Vromans # Created On : Tue Sep 11 15:00:12 1990 # Last Modified By: Johan Vromans # Last Modified On: Tue Aug 18 14:48:05 2020 # Update Count : 1739 # Status : Released ################ Module Preamble ################ use 5.004; use strict; use warnings; package Getopt::Long; use vars qw($VERSION); $VERSION = 2.52; # For testing versions only. use vars qw($VERSION_STRING); $VERSION_STRING = "2.52"; use Exporter; use vars qw(@ISA @EXPORT @EXPORT_OK); @ISA = qw(Exporter); # Exported subroutines. sub GetOptions(@); # always sub GetOptionsFromArray(@); # on demand sub GetOptionsFromString(@); # on demand sub Configure(@); # on demand sub HelpMessage(@); # on demand sub VersionMessage(@); # in demand BEGIN { # Init immediately so their contents can be used in the 'use vars' below. @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER); @EXPORT_OK = qw(&HelpMessage &VersionMessage &Configure &GetOptionsFromArray &GetOptionsFromString); } # User visible variables. use vars @EXPORT, @EXPORT_OK; use vars qw($error $debug $major_version $minor_version); # Deprecated visible variables. use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order $passthrough); # Official invisible variables. use vars qw($genprefix $caller $gnu_compat $auto_help $auto_version $longprefix); # Really invisible variables. my $bundling_values; # Public subroutines. sub config(@); # deprecated name # Private subroutines. sub ConfigDefaults(); sub ParseOptionSpec($$); sub OptCtl($); sub FindOption($$$$$); sub ValidValue ($$$$$); ################ Local Variables ################ # $requested_version holds the version that was mentioned in the 'use' # or 'require', if any. It can be used to enable or disable specific # features. my $requested_version = 0; ################ Resident subroutines ################ sub ConfigDefaults() { # Handle POSIX compliancy. if ( defined $ENV{"POSIXLY_CORRECT"} ) { $genprefix = "(--|-)"; $autoabbrev = 0; # no automatic abbrev of options $bundling = 0; # no bundling of single letter switches $getopt_compat = 0; # disallow '+' to start options $order = $REQUIRE_ORDER; } else { $genprefix = "(--|-|\\+)"; $autoabbrev = 1; # automatic abbrev of options $bundling = 0; # bundling off by default $getopt_compat = 1; # allow '+' to start options $order = $PERMUTE; } # Other configurable settings. $debug = 0; # for debugging $error = 0; # error tally $ignorecase = 1; # ignore case when matching options $passthrough = 0; # leave unrecognized options alone $gnu_compat = 0; # require --opt=val if value is optional $longprefix = "(--)"; # what does a long prefix look like $bundling_values = 0; # no bundling of values } # Override import. sub import { my $pkg = shift; # package my @syms = (); # symbols to import my @config = (); # configuration my $dest = \@syms; # symbols first for ( @_ ) { if ( $_ eq ':config' ) { $dest = \@config; # config next next; } push(@$dest, $_); # push } # Hide one level and call super. local $Exporter::ExportLevel = 1; push(@syms, qw(&GetOptions)) if @syms; # always export GetOptions $requested_version = 0; $pkg->SUPER::import(@syms); # And configure. Configure(@config) if @config; } ################ Initialization ################ # Values for $order. See GNU getopt.c for details. ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2); # Version major/minor numbers. ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/; ConfigDefaults(); ################ OO Interface ################ package Getopt::Long::Parser; # Store a copy of the default configuration. Since ConfigDefaults has # just been called, what we get from Configure is the default. my $default_config = do { Getopt::Long::Configure () }; sub new { my $that = shift; my $class = ref($that) || $that; my %atts = @_; # Register the callers package. my $self = { caller_pkg => (caller)[0] }; bless ($self, $class); # Process config attributes. if ( defined $atts{config} ) { my $save = Getopt::Long::Configure ($default_config, @{$atts{config}}); $self->{settings} = Getopt::Long::Configure ($save); delete ($atts{config}); } # Else use default config. else { $self->{settings} = $default_config; } if ( %atts ) { # Oops die(__PACKAGE__.": unhandled attributes: ". join(" ", sort(keys(%atts)))."\n"); } $self; } sub configure { my ($self) = shift; # Restore settings, merge new settings in. my $save = Getopt::Long::Configure ($self->{settings}, @_); # Restore orig config and save the new config. $self->{settings} = Getopt::Long::Configure ($save); } sub getoptions { my ($self) = shift; return $self->getoptionsfromarray(\@ARGV, @_); } sub getoptionsfromarray { my ($self) = shift; # Restore config settings. my $save = Getopt::Long::Configure ($self->{settings}); # Call main routine. my $ret = 0; $Getopt::Long::caller = $self->{caller_pkg}; eval { # Locally set exception handler to default, otherwise it will # be called implicitly here, and again explicitly when we try # to deliver the messages. local ($SIG{__DIE__}) = 'DEFAULT'; $ret = Getopt::Long::GetOptionsFromArray (@_); }; # Restore saved settings. Getopt::Long::Configure ($save); # Handle errors and return value. die ($@) if $@; return $ret; } package Getopt::Long; ################ Back to Normal ################ # Indices in option control info. # Note that ParseOptions uses the fields directly. Search for 'hard-wired'. use constant CTL_TYPE => 0; #use constant CTL_TYPE_FLAG => ''; #use constant CTL_TYPE_NEG => '!'; #use constant CTL_TYPE_INCR => '+'; #use constant CTL_TYPE_INT => 'i'; #use constant CTL_TYPE_INTINC => 'I'; #use constant CTL_TYPE_XINT => 'o'; #use constant CTL_TYPE_FLOAT => 'f'; #use constant CTL_TYPE_STRING => 's'; use constant CTL_CNAME => 1; use constant CTL_DEFAULT => 2; use constant CTL_DEST => 3; use constant CTL_DEST_SCALAR => 0; use constant CTL_DEST_ARRAY => 1; use constant CTL_DEST_HASH => 2; use constant CTL_DEST_CODE => 3; use constant CTL_AMIN => 4; use constant CTL_AMAX => 5; # FFU. #use constant CTL_RANGE => ; #use constant CTL_REPEAT => ; # Rather liberal patterns to match numbers. use constant PAT_INT => "[-+]?_*[0-9][0-9_]*"; use constant PAT_XINT => "(?:". "[-+]?_*[1-9][0-9_]*". "|". "0x_*[0-9a-f][0-9a-f_]*". "|". "0b_*[01][01_]*". "|". "0[0-7_]*". ")"; use constant PAT_FLOAT => "[-+]?". # optional sign "(?=[0-9.])". # must start with digit or dec.point "[0-9_]*". # digits before the dec.point "(\.[0-9_]+)?". # optional fraction "([eE][-+]?[0-9_]+)?"; # optional exponent sub GetOptions(@) { # Shift in default array. unshift(@_, \@ARGV); # Try to keep caller() and Carp consistent. goto &GetOptionsFromArray; } sub GetOptionsFromString(@) { my ($string) = shift; require Text::ParseWords; my $args = [ Text::ParseWords::shellwords($string) ]; $caller ||= (caller)[0]; # current context my $ret = GetOptionsFromArray($args, @_); return ( $ret, $args ) if wantarray; if ( @$args ) { $ret = 0; warn("GetOptionsFromString: Excess data \"@$args\" in string \"$string\"\n"); } $ret; } sub GetOptionsFromArray(@) { my ($argv, @optionlist) = @_; # local copy of the option descriptions my $argend = '--'; # option list terminator my %opctl = (); # table of option specs my $pkg = $caller || (caller)[0]; # current context # Needed if linkage is omitted. my @ret = (); # accum for non-options my %linkage; # linkage my $userlinkage; # user supplied HASH my $opt; # current option my $prefix = $genprefix; # current prefix $error = ''; if ( $debug ) { # Avoid some warnings if debugging. local ($^W) = 0; print STDERR ("Getopt::Long $Getopt::Long::VERSION_STRING ", "called from package \"$pkg\".", "\n ", "argv: ", defined($argv) ? UNIVERSAL::isa( $argv, 'ARRAY' ) ? "(@$argv)" : $argv : "", "\n ", "autoabbrev=$autoabbrev,". "bundling=$bundling,", "bundling_values=$bundling_values,", "getopt_compat=$getopt_compat,", "gnu_compat=$gnu_compat,", "order=$order,", "\n ", "ignorecase=$ignorecase,", "requested_version=$requested_version,", "passthrough=$passthrough,", "genprefix=\"$genprefix\",", "longprefix=\"$longprefix\".", "\n"); } # Check for ref HASH as first argument. # First argument may be an object. It's OK to use this as long # as it is really a hash underneath. $userlinkage = undef; if ( @optionlist && ref($optionlist[0]) and UNIVERSAL::isa($optionlist[0],'HASH') ) { $userlinkage = shift (@optionlist); print STDERR ("=> user linkage: $userlinkage\n") if $debug; } # See if the first element of the optionlist contains option # starter characters. # Be careful not to interpret '<>' as option starters. if ( @optionlist && $optionlist[0] =~ /^\W+$/ && !($optionlist[0] eq '<>' && @optionlist > 0 && ref($optionlist[1])) ) { $prefix = shift (@optionlist); # Turn into regexp. Needs to be parenthesized! $prefix =~ s/(\W)/\\$1/g; $prefix = "([" . $prefix . "])"; print STDERR ("=> prefix=\"$prefix\"\n") if $debug; } # Verify correctness of optionlist. %opctl = (); while ( @optionlist ) { my $opt = shift (@optionlist); unless ( defined($opt) ) { $error .= "Undefined argument in option spec\n"; next; } # Strip leading prefix so people can specify "--foo=i" if they like. $opt = $+ if $opt =~ /^$prefix+(.*)$/s; if ( $opt eq '<>' ) { if ( (defined $userlinkage) && !(@optionlist > 0 && ref($optionlist[0])) && (exists $userlinkage->{$opt}) && ref($userlinkage->{$opt}) ) { unshift (@optionlist, $userlinkage->{$opt}); } unless ( @optionlist > 0 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) { $error .= "Option spec <> requires a reference to a subroutine\n"; # Kill the linkage (to avoid another error). shift (@optionlist) if @optionlist && ref($optionlist[0]); next; } $linkage{'<>'} = shift (@optionlist); next; } # Parse option spec. my ($name, $orig) = ParseOptionSpec ($opt, \%opctl); unless ( defined $name ) { # Failed. $orig contains the error message. Sorry for the abuse. $error .= $orig; # Kill the linkage (to avoid another error). shift (@optionlist) if @optionlist && ref($optionlist[0]); next; } # If no linkage is supplied in the @optionlist, copy it from # the userlinkage if available. if ( defined $userlinkage ) { unless ( @optionlist > 0 && ref($optionlist[0]) ) { if ( exists $userlinkage->{$orig} && ref($userlinkage->{$orig}) ) { print STDERR ("=> found userlinkage for \"$orig\": ", "$userlinkage->{$orig}\n") if $debug; unshift (@optionlist, $userlinkage->{$orig}); } else { # Do nothing. Being undefined will be handled later. next; } } } # Copy the linkage. If omitted, link to global variable. if ( @optionlist > 0 && ref($optionlist[0]) ) { print STDERR ("=> link \"$orig\" to $optionlist[0]\n") if $debug; my $rl = ref($linkage{$orig} = shift (@optionlist)); if ( $rl eq "ARRAY" ) { $opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY; } elsif ( $rl eq "HASH" ) { $opctl{$name}[CTL_DEST] = CTL_DEST_HASH; } elsif ( $rl eq "SCALAR" || $rl eq "REF" ) { # if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) { # my $t = $linkage{$orig}; # $$t = $linkage{$orig} = []; # } # elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) { # } # else { # Ok. # } } elsif ( $rl eq "CODE" ) { # Ok. } else { $error .= "Invalid option linkage for \"$opt\"\n"; } } else { # Link to global $opt_XXX variable. # Make sure a valid perl identifier results. my $ov = $orig; $ov =~ s/\W/_/g; if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) { print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n") if $debug; eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;"); } elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) { print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n") if $debug; eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;"); } else { print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n") if $debug; eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;"); } } if ( $opctl{$name}[CTL_TYPE] eq 'I' && ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY || $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) ) { $error .= "Invalid option linkage for \"$opt\"\n"; } } $error .= "GetOptionsFromArray: 1st parameter is not an array reference\n" unless $argv && UNIVERSAL::isa( $argv, 'ARRAY' ); # Bail out if errors found. die ($error) if $error; $error = 0; # Supply --version and --help support, if needed and allowed. if ( defined($auto_version) ? $auto_version : ($requested_version >= 2.3203) ) { if ( !defined($opctl{version}) ) { $opctl{version} = ['','version',0,CTL_DEST_CODE,undef]; $linkage{version} = \&VersionMessage; } $auto_version = 1; } if ( defined($auto_help) ? $auto_help : ($requested_version >= 2.3203) ) { if ( !defined($opctl{help}) && !defined($opctl{'?'}) ) { $opctl{help} = $opctl{'?'} = ['','help',0,CTL_DEST_CODE,undef]; $linkage{help} = \&HelpMessage; } $auto_help = 1; } # Show the options tables if debugging. if ( $debug ) { my ($arrow, $k, $v); $arrow = "=> "; while ( ($k,$v) = each(%opctl) ) { print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n"); $arrow = " "; } } # Process argument list my $goon = 1; while ( $goon && @$argv > 0 ) { # Get next argument. $opt = shift (@$argv); print STDERR ("=> arg \"", $opt, "\"\n") if $debug; # Double dash is option list terminator. if ( defined($opt) && $opt eq $argend ) { push (@ret, $argend) if $passthrough; last; } # Look it up. my $tryopt = $opt; my $found; # success status my $key; # key (if hash type) my $arg; # option argument my $ctl; # the opctl entry ($found, $opt, $ctl, $arg, $key) = FindOption ($argv, $prefix, $argend, $opt, \%opctl); if ( $found ) { # FindOption undefines $opt in case of errors. next unless defined $opt; my $argcnt = 0; while ( defined $arg ) { # Get the canonical name. my $given = $opt; print STDERR ("=> cname for \"$opt\" is ") if $debug; $opt = $ctl->[CTL_CNAME]; print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug; if ( defined $linkage{$opt} ) { print STDERR ("=> ref(\$L{$opt}) -> ", ref($linkage{$opt}), "\n") if $debug; if ( ref($linkage{$opt}) eq 'SCALAR' || ref($linkage{$opt}) eq 'REF' ) { if ( $ctl->[CTL_TYPE] eq '+' ) { print STDERR ("=> \$\$L{$opt} += \"$arg\"\n") if $debug; if ( defined ${$linkage{$opt}} ) { ${$linkage{$opt}} += $arg; } else { ${$linkage{$opt}} = $arg; } } elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) { print STDERR ("=> ref(\$L{$opt}) auto-vivified", " to ARRAY\n") if $debug; my $t = $linkage{$opt}; $$t = $linkage{$opt} = []; print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n") if $debug; push (@{$linkage{$opt}}, $arg); } elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) { print STDERR ("=> ref(\$L{$opt}) auto-vivified", " to HASH\n") if $debug; my $t = $linkage{$opt}; $$t = $linkage{$opt} = {}; print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n") if $debug; $linkage{$opt}->{$key} = $arg; } else { print STDERR ("=> \$\$L{$opt} = \"$arg\"\n") if $debug; ${$linkage{$opt}} = $arg; } } elsif ( ref($linkage{$opt}) eq 'ARRAY' ) { print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n") if $debug; push (@{$linkage{$opt}}, $arg); } elsif ( ref($linkage{$opt}) eq 'HASH' ) { print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n") if $debug; $linkage{$opt}->{$key} = $arg; } elsif ( ref($linkage{$opt}) eq 'CODE' ) { print STDERR ("=> &L{$opt}(\"$opt\"", $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "", ", \"$arg\")\n") if $debug; my $eval_error = do { local $@; local $SIG{__DIE__} = 'DEFAULT'; eval { &{$linkage{$opt}} (Getopt::Long::CallBack->new (name => $opt, given => $given, ctl => $ctl, opctl => \%opctl, linkage => \%linkage, prefix => $prefix, ), $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (), $arg); }; $@; }; print STDERR ("=> die($eval_error)\n") if $debug && $eval_error ne ''; if ( $eval_error =~ /^!/ ) { if ( $eval_error =~ /^!FINISH\b/ ) { $goon = 0; } } elsif ( $eval_error ne '' ) { warn ($eval_error); $error++; } } else { print STDERR ("Invalid REF type \"", ref($linkage{$opt}), "\" in linkage\n"); die("Getopt::Long -- internal error!\n"); } } # No entry in linkage means entry in userlinkage. elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) { if ( defined $userlinkage->{$opt} ) { print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n") if $debug; push (@{$userlinkage->{$opt}}, $arg); } else { print STDERR ("=>\$L{$opt} = [\"$arg\"]\n") if $debug; $userlinkage->{$opt} = [$arg]; } } elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) { if ( defined $userlinkage->{$opt} ) { print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n") if $debug; $userlinkage->{$opt}->{$key} = $arg; } else { print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n") if $debug; $userlinkage->{$opt} = {$key => $arg}; } } else { if ( $ctl->[CTL_TYPE] eq '+' ) { print STDERR ("=> \$L{$opt} += \"$arg\"\n") if $debug; if ( defined $userlinkage->{$opt} ) { $userlinkage->{$opt} += $arg; } else { $userlinkage->{$opt} = $arg; } } else { print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug; $userlinkage->{$opt} = $arg; } } $argcnt++; last if $argcnt >= $ctl->[CTL_AMAX] && $ctl->[CTL_AMAX] != -1; undef($arg); # Need more args? if ( $argcnt < $ctl->[CTL_AMIN] ) { if ( @$argv ) { if ( ValidValue($ctl, $argv->[0], 1, $argend, $prefix) ) { $arg = shift(@$argv); if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) { $arg =~ tr/_//d; $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/ ? oct($arg) : 0+$arg } ($key,$arg) = $arg =~ /^([^=]+)=(.*)/ if $ctl->[CTL_DEST] == CTL_DEST_HASH; next; } warn("Value \"$$argv[0]\" invalid for option $opt\n"); $error++; } else { warn("Insufficient arguments for option $opt\n"); $error++; } } # Any more args? if ( @$argv && ValidValue($ctl, $argv->[0], 0, $argend, $prefix) ) { $arg = shift(@$argv); if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) { $arg =~ tr/_//d; $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/ ? oct($arg) : 0+$arg } ($key,$arg) = $arg =~ /^([^=]+)=(.*)/ if $ctl->[CTL_DEST] == CTL_DEST_HASH; next; } } } # Not an option. Save it if we $PERMUTE and don't have a <>. elsif ( $order == $PERMUTE ) { # Try non-options call-back. my $cb; if ( defined ($cb = $linkage{'<>'}) ) { print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n") if $debug; my $eval_error = do { local $@; local $SIG{__DIE__} = 'DEFAULT'; eval { # The arg to <> cannot be the CallBack object # since it may be passed to other modules that # get confused (e.g., Archive::Tar). Well, # it's not relevant for this callback anyway. &$cb($tryopt); }; $@; }; print STDERR ("=> die($eval_error)\n") if $debug && $eval_error ne ''; if ( $eval_error =~ /^!/ ) { if ( $eval_error =~ /^!FINISH\b/ ) { $goon = 0; } } elsif ( $eval_error ne '' ) { warn ($eval_error); $error++; } } else { print STDERR ("=> saving \"$tryopt\" ", "(not an option, may permute)\n") if $debug; push (@ret, $tryopt); } next; } # ...otherwise, terminate. else { # Push this one back and exit. unshift (@$argv, $tryopt); return ($error == 0); } } # Finish. if ( @ret && ( $order == $PERMUTE || $passthrough ) ) { # Push back accumulated arguments print STDERR ("=> restoring \"", join('" "', @ret), "\"\n") if $debug; unshift (@$argv, @ret); } return ($error == 0); } # A readable representation of what's in an optbl. sub OptCtl ($) { my ($v) = @_; my @v = map { defined($_) ? ($_) : ("") } @$v; "[". join(",", "\"$v[CTL_TYPE]\"", "\"$v[CTL_CNAME]\"", "\"$v[CTL_DEFAULT]\"", ("\$","\@","\%","\&")[$v[CTL_DEST] || 0], $v[CTL_AMIN] || '', $v[CTL_AMAX] || '', # $v[CTL_RANGE] || '', # $v[CTL_REPEAT] || '', ). "]"; } # Parse an option specification and fill the tables. sub ParseOptionSpec ($$) { my ($opt, $opctl) = @_; # Match option spec. if ( $opt !~ m;^ ( # Option name (?: \w+[-\w]* ) # Aliases (?: \| (?: . [^|!+=:]* )? )* )? ( # Either modifiers ... [!+] | # ... or a value/dest/repeat specification [=:] [ionfs] [@%]? (?: \{\d*,?\d*\} )? | # ... or an optional-with-default spec : (?: -?\d+ | \+ ) [@%]? )? $;x ) { return (undef, "Error in option spec: \"$opt\"\n"); } my ($names, $spec) = ($1, $2); $spec = '' unless defined $spec; # $orig keeps track of the primary name the user specified. # This name will be used for the internal or external linkage. # In other words, if the user specifies "FoO|BaR", it will # match any case combinations of 'foo' and 'bar', but if a global # variable needs to be set, it will be $opt_FoO in the exact case # as specified. my $orig; my @names; if ( defined $names ) { @names = split (/\|/, $names); $orig = $names[0]; } else { @names = (''); $orig = ''; } # Construct the opctl entries. my $entry; if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) { # Fields are hard-wired here. $entry = [$spec,$orig,undef,CTL_DEST_SCALAR,0,0]; } elsif ( $spec =~ /^:(-?\d+|\+)([@%])?$/ ) { my $def = $1; my $dest = $2; my $type = $def eq '+' ? 'I' : 'i'; $dest ||= '$'; $dest = $dest eq '@' ? CTL_DEST_ARRAY : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR; # Fields are hard-wired here. $entry = [$type,$orig,$def eq '+' ? undef : $def, $dest,0,1]; } else { my ($mand, $type, $dest) = $spec =~ /^([=:])([ionfs])([@%])?(\{(\d+)?(,)?(\d+)?\})?$/; return (undef, "Cannot repeat while bundling: \"$opt\"\n") if $bundling && defined($4); my ($mi, $cm, $ma) = ($5, $6, $7); return (undef, "{0} is useless in option spec: \"$opt\"\n") if defined($mi) && !$mi && !defined($ma) && !defined($cm); $type = 'i' if $type eq 'n'; $dest ||= '$'; $dest = $dest eq '@' ? CTL_DEST_ARRAY : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR; # Default minargs to 1/0 depending on mand status. $mi = $mand eq '=' ? 1 : 0 unless defined $mi; # Adjust mand status according to minargs. $mand = $mi ? '=' : ':'; # Adjust maxargs. $ma = $mi ? $mi : 1 unless defined $ma || defined $cm; return (undef, "Max must be greater than zero in option spec: \"$opt\"\n") if defined($ma) && !$ma; return (undef, "Max less than min in option spec: \"$opt\"\n") if defined($ma) && $ma < $mi; # Fields are hard-wired here. $entry = [$type,$orig,undef,$dest,$mi,$ma||-1]; } # Process all names. First is canonical, the rest are aliases. my $dups = ''; foreach ( @names ) { $_ = lc ($_) if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0); if ( exists $opctl->{$_} ) { $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n"; } if ( $spec eq '!' ) { $opctl->{"no$_"} = $entry; $opctl->{"no-$_"} = $entry; $opctl->{$_} = [@$entry]; $opctl->{$_}->[CTL_TYPE] = ''; } else { $opctl->{$_} = $entry; } } if ( $dups && $^W ) { foreach ( split(/\n+/, $dups) ) { warn($_."\n"); } } ($names[0], $orig); } # Option lookup. sub FindOption ($$$$$) { # returns (1, $opt, $ctl, $arg, $key) if okay, # returns (1, undef) if option in error, # returns (0) otherwise. my ($argv, $prefix, $argend, $opt, $opctl) = @_; print STDERR ("=> find \"$opt\"\n") if $debug; return (0) unless defined($opt); return (0) unless $opt =~ /^($prefix)(.*)$/s; return (0) if $opt eq "-" && !defined $opctl->{''}; $opt = substr( $opt, length($1) ); # retain taintedness my $starter = $1; print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug; my $optarg; # value supplied with --opt=value my $rest; # remainder from unbundling # If it is a long option, it may include the value. # With getopt_compat, only if not bundling. if ( ($starter=~/^$longprefix$/ || ($getopt_compat && ($bundling == 0 || $bundling == 2))) && (my $oppos = index($opt, '=', 1)) > 0) { my $optorg = $opt; $opt = substr($optorg, 0, $oppos); $optarg = substr($optorg, $oppos + 1); # retain tainedness print STDERR ("=> option \"", $opt, "\", optarg = \"$optarg\"\n") if $debug; } #### Look it up ### my $tryopt = $opt; # option to try if ( ( $bundling || $bundling_values ) && $starter eq '-' ) { # To try overrides, obey case ignore. $tryopt = $ignorecase ? lc($opt) : $opt; # If bundling == 2, long options can override bundles. if ( $bundling == 2 && length($tryopt) > 1 && defined ($opctl->{$tryopt}) ) { print STDERR ("=> $starter$tryopt overrides unbundling\n") if $debug; } # If bundling_values, option may be followed by the value. elsif ( $bundling_values ) { $tryopt = $opt; # Unbundle single letter option. $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : ''; $tryopt = substr ($tryopt, 0, 1); $tryopt = lc ($tryopt) if $ignorecase > 1; print STDERR ("=> $starter$tryopt unbundled from ", "$starter$tryopt$rest\n") if $debug; # Whatever remains may not be considered an option. $optarg = $rest eq '' ? undef : $rest; $rest = undef; } # Split off a single letter and leave the rest for # further processing. else { $tryopt = $opt; # Unbundle single letter option. $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : ''; $tryopt = substr ($tryopt, 0, 1); $tryopt = lc ($tryopt) if $ignorecase > 1; print STDERR ("=> $starter$tryopt unbundled from ", "$starter$tryopt$rest\n") if $debug; $rest = undef unless $rest ne ''; } } # Try auto-abbreviation. elsif ( $autoabbrev && $opt ne "" ) { # Sort the possible long option names. my @names = sort(keys (%$opctl)); # Downcase if allowed. $opt = lc ($opt) if $ignorecase; $tryopt = $opt; # Turn option name into pattern. my $pat = quotemeta ($opt); # Look up in option names. my @hits = grep (/^$pat/, @names); print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ", "out of ", scalar(@names), "\n") if $debug; # Check for ambiguous results. unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) { # See if all matches are for the same option. my %hit; foreach ( @hits ) { my $hit = $opctl->{$_}->[CTL_CNAME] if defined $opctl->{$_}->[CTL_CNAME]; $hit = "no" . $hit if $opctl->{$_}->[CTL_TYPE] eq '!'; $hit{$hit} = 1; } # Remove auto-supplied options (version, help). if ( keys(%hit) == 2 ) { if ( $auto_version && exists($hit{version}) ) { delete $hit{version}; } elsif ( $auto_help && exists($hit{help}) ) { delete $hit{help}; } } # Now see if it really is ambiguous. unless ( keys(%hit) == 1 ) { return (0) if $passthrough; warn ("Option ", $opt, " is ambiguous (", join(", ", @hits), ")\n"); $error++; return (1, undef); } @hits = keys(%hit); } # Complete the option name, if appropriate. if ( @hits == 1 && $hits[0] ne $opt ) { $tryopt = $hits[0]; $tryopt = lc ($tryopt) if $ignorecase > (($bundling && length($tryopt) == 1) ? 1 : 0); print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n") if $debug; } } # Map to all lowercase if ignoring case. elsif ( $ignorecase ) { $tryopt = lc ($opt); } # Check validity by fetching the info. my $ctl = $opctl->{$tryopt}; unless ( defined $ctl ) { return (0) if $passthrough; # Pretend one char when bundling. if ( $bundling == 1 && length($starter) == 1 ) { $opt = substr($opt,0,1); unshift (@$argv, $starter.$rest) if defined $rest; } if ( $opt eq "" ) { warn ("Missing option after ", $starter, "\n"); } else { warn ("Unknown option: ", $opt, "\n"); } $error++; return (1, undef); } # Apparently valid. $opt = $tryopt; print STDERR ("=> found ", OptCtl($ctl), " for \"", $opt, "\"\n") if $debug; #### Determine argument status #### # If it is an option w/o argument, we're almost finished with it. my $type = $ctl->[CTL_TYPE]; my $arg; if ( $type eq '' || $type eq '!' || $type eq '+' ) { if ( defined $optarg ) { return (0) if $passthrough; warn ("Option ", $opt, " does not take an argument\n"); $error++; undef $opt; undef $optarg if $bundling_values; } elsif ( $type eq '' || $type eq '+' ) { # Supply explicit value. $arg = 1; } else { $opt =~ s/^no-?//i; # strip NO prefix $arg = 0; # supply explicit value } unshift (@$argv, $starter.$rest) if defined $rest; return (1, $opt, $ctl, $arg); } # Get mandatory status and type info. my $mand = $ctl->[CTL_AMIN]; # Check if there is an option argument available. if ( $gnu_compat ) { my $optargtype = 0; # none, 1 = empty, 2 = nonempty, 3 = aux if ( defined($optarg) ) { $optargtype = (length($optarg) == 0) ? 1 : 2; } elsif ( defined $rest || @$argv > 0 ) { # GNU getopt_long() does not accept the (optional) # argument to be passed to the option without = sign. # We do, since not doing so breaks existing scripts. $optargtype = 3; } if(($optargtype == 0) && !$mand) { if ( $type eq 'I' ) { # Fake incremental type. my @c = @$ctl; $c[CTL_TYPE] = '+'; return (1, $opt, \@c, 1); } my $val = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : $type eq 's' ? '' : 0; return (1, $opt, $ctl, $val); } return (1, $opt, $ctl, $type eq 's' ? '' : 0) if $optargtype == 1; # --foo= -> return nothing } # Check if there is an option argument available. if ( defined $optarg ? ($optarg eq '') : !(defined $rest || @$argv > 0) ) { # Complain if this option needs an argument. # if ( $mand && !($type eq 's' ? defined($optarg) : 0) ) { if ( $mand || $ctl->[CTL_DEST] == CTL_DEST_HASH ) { return (0) if $passthrough; warn ("Option ", $opt, " requires an argument\n"); $error++; return (1, undef); } if ( $type eq 'I' ) { # Fake incremental type. my @c = @$ctl; $c[CTL_TYPE] = '+'; return (1, $opt, \@c, 1); } return (1, $opt, $ctl, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : $type eq 's' ? '' : 0); } # Get (possibly optional) argument. $arg = (defined $rest ? $rest : (defined $optarg ? $optarg : shift (@$argv))); # Get key if this is a "name=value" pair for a hash option. my $key; if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) { ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2) : ($arg, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : ($mand ? undef : ($type eq 's' ? "" : 1))); if (! defined $arg) { warn ("Option $opt, key \"$key\", requires a value\n"); $error++; # Push back. unshift (@$argv, $starter.$rest) if defined $rest; return (1, undef); } } #### Check if the argument is valid for this option #### my $key_valid = $ctl->[CTL_DEST] == CTL_DEST_HASH ? "[^=]+=" : ""; if ( $type eq 's' ) { # string # A mandatory string takes anything. return (1, $opt, $ctl, $arg, $key) if $mand; # Same for optional string as a hash value return (1, $opt, $ctl, $arg, $key) if $ctl->[CTL_DEST] == CTL_DEST_HASH; # An optional string takes almost anything. return (1, $opt, $ctl, $arg, $key) if defined $optarg || defined $rest; return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ?? # Check for option or option list terminator. if ($arg eq $argend || $arg =~ /^$prefix.+/) { # Push back. unshift (@$argv, $arg); # Supply empty value. $arg = ''; } } elsif ( $type eq 'i' # numeric/integer || $type eq 'I' # numeric/integer w/ incr default || $type eq 'o' ) { # dec/oct/hex/bin value my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT; if ( $bundling && defined $rest && $rest =~ /^($key_valid)($o_valid)(.*)$/si ) { ($key, $arg, $rest) = ($1, $2, $+); chop($key) if $key; $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg; unshift (@$argv, $starter.$rest) if defined $rest && $rest ne ''; } elsif ( $arg =~ /^$o_valid$/si ) { $arg =~ tr/_//d; $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg; } else { if ( defined $optarg || $mand ) { if ( $passthrough ) { unshift (@$argv, defined $rest ? $starter.$rest : $arg) unless defined $optarg; return (0); } warn ("Value \"", $arg, "\" invalid for option ", $opt, " (", $type eq 'o' ? "extended " : '', "number expected)\n"); $error++; # Push back. unshift (@$argv, $starter.$rest) if defined $rest; return (1, undef); } else { # Push back. unshift (@$argv, defined $rest ? $starter.$rest : $arg); if ( $type eq 'I' ) { # Fake incremental type. my @c = @$ctl; $c[CTL_TYPE] = '+'; return (1, $opt, \@c, 1); } # Supply default value. $arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0; } } } elsif ( $type eq 'f' ) { # real number, int is also ok my $o_valid = PAT_FLOAT; if ( $bundling && defined $rest && $rest =~ /^($key_valid)($o_valid)(.*)$/s ) { $arg =~ tr/_//d; ($key, $arg, $rest) = ($1, $2, $+); chop($key) if $key; unshift (@$argv, $starter.$rest) if defined $rest && $rest ne ''; } elsif ( $arg =~ /^$o_valid$/ ) { $arg =~ tr/_//d; } else { if ( defined $optarg || $mand ) { if ( $passthrough ) { unshift (@$argv, defined $rest ? $starter.$rest : $arg) unless defined $optarg; return (0); } warn ("Value \"", $arg, "\" invalid for option ", $opt, " (real number expected)\n"); $error++; # Push back. unshift (@$argv, $starter.$rest) if defined $rest; return (1, undef); } else { # Push back. unshift (@$argv, defined $rest ? $starter.$rest : $arg); # Supply default value. $arg = 0.0; } } } else { die("Getopt::Long internal error (Can't happen)\n"); } return (1, $opt, $ctl, $arg, $key); } sub ValidValue ($$$$$) { my ($ctl, $arg, $mand, $argend, $prefix) = @_; if ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) { return 0 unless $arg =~ /[^=]+=(.*)/; $arg = $1; } my $type = $ctl->[CTL_TYPE]; if ( $type eq 's' ) { # string # A mandatory string takes anything. return (1) if $mand; return (1) if $arg eq "-"; # Check for option or option list terminator. return 0 if $arg eq $argend || $arg =~ /^$prefix.+/; return 1; } elsif ( $type eq 'i' # numeric/integer || $type eq 'I' # numeric/integer w/ incr default || $type eq 'o' ) { # dec/oct/hex/bin value my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT; return $arg =~ /^$o_valid$/si; } elsif ( $type eq 'f' ) { # real number, int is also ok my $o_valid = PAT_FLOAT; return $arg =~ /^$o_valid$/; } die("ValidValue: Cannot happen\n"); } # Getopt::Long Configuration. sub Configure (@) { my (@options) = @_; my $prevconfig = [ $error, $debug, $major_version, $minor_version, $caller, $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order, $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help, $longprefix, $bundling_values ]; if ( ref($options[0]) eq 'ARRAY' ) { ( $error, $debug, $major_version, $minor_version, $caller, $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order, $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help, $longprefix, $bundling_values ) = @{shift(@options)}; } my $opt; foreach $opt ( @options ) { my $try = lc ($opt); my $action = 1; if ( $try =~ /^no_?(.*)$/s ) { $action = 0; $try = $+; } if ( ($try eq 'default' or $try eq 'defaults') && $action ) { ConfigDefaults (); } elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) { local $ENV{POSIXLY_CORRECT}; $ENV{POSIXLY_CORRECT} = 1 if $action; ConfigDefaults (); } elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) { $autoabbrev = $action; } elsif ( $try eq 'getopt_compat' ) { $getopt_compat = $action; $genprefix = $action ? "(--|-|\\+)" : "(--|-)"; } elsif ( $try eq 'gnu_getopt' ) { if ( $action ) { $gnu_compat = 1; $bundling = 1; $getopt_compat = 0; $genprefix = "(--|-)"; $order = $PERMUTE; $bundling_values = 0; } } elsif ( $try eq 'gnu_compat' ) { $gnu_compat = $action; $bundling = 0; $bundling_values = 1; } elsif ( $try =~ /^(auto_?)?version$/ ) { $auto_version = $action; } elsif ( $try =~ /^(auto_?)?help$/ ) { $auto_help = $action; } elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) { $ignorecase = $action; } elsif ( $try eq 'ignorecase_always' or $try eq 'ignore_case_always' ) { $ignorecase = $action ? 2 : 0; } elsif ( $try eq 'bundling' ) { $bundling = $action; $bundling_values = 0 if $action; } elsif ( $try eq 'bundling_override' ) { $bundling = $action ? 2 : 0; $bundling_values = 0 if $action; } elsif ( $try eq 'bundling_values' ) { $bundling_values = $action; $bundling = 0 if $action; } elsif ( $try eq 'require_order' ) { $order = $action ? $REQUIRE_ORDER : $PERMUTE; } elsif ( $try eq 'permute' ) { $order = $action ? $PERMUTE : $REQUIRE_ORDER; } elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) { $passthrough = $action; } elsif ( $try =~ /^prefix=(.+)$/ && $action ) { $genprefix = $1; # Turn into regexp. Needs to be parenthesized! $genprefix = "(" . quotemeta($genprefix) . ")"; eval { '' =~ /$genprefix/; }; die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@; } elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) { $genprefix = $1; # Parenthesize if needed. $genprefix = "(" . $genprefix . ")" unless $genprefix =~ /^\(.*\)$/; eval { '' =~ m"$genprefix"; }; die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@; } elsif ( $try =~ /^long_prefix_pattern=(.+)$/ && $action ) { $longprefix = $1; # Parenthesize if needed. $longprefix = "(" . $longprefix . ")" unless $longprefix =~ /^\(.*\)$/; eval { '' =~ m"$longprefix"; }; die("Getopt::Long: invalid long prefix pattern \"$longprefix\"\n") if $@; } elsif ( $try eq 'debug' ) { $debug = $action; } else { die("Getopt::Long: unknown or erroneous config parameter \"$opt\"\n") } } $prevconfig; } # Deprecated name. sub config (@) { Configure (@_); } # Issue a standard message for --version. # # The arguments are mostly the same as for Pod::Usage::pod2usage: # # - a number (exit value) # - a string (lead in message) # - a hash with options. See Pod::Usage for details. # sub VersionMessage(@) { # Massage args. my $pa = setup_pa_args("version", @_); my $v = $main::VERSION; my $fh = $pa->{-output} || ( ($pa->{-exitval} eq "NOEXIT" || $pa->{-exitval} < 2) ? \*STDOUT : \*STDERR ); print $fh (defined($pa->{-message}) ? $pa->{-message} : (), $0, defined $v ? " version $v" : (), "\n", "(", __PACKAGE__, "::", "GetOptions", " version ", defined($Getopt::Long::VERSION_STRING) ? $Getopt::Long::VERSION_STRING : $VERSION, ";", " Perl version ", $] >= 5.006 ? sprintf("%vd", $^V) : $], ")\n"); exit($pa->{-exitval}) unless $pa->{-exitval} eq "NOEXIT"; } # Issue a standard message for --help. # # The arguments are the same as for Pod::Usage::pod2usage: # # - a number (exit value) # - a string (lead in message) # - a hash with options. See Pod::Usage for details. # sub HelpMessage(@) { eval { require Pod::Usage; import Pod::Usage; 1; } || die("Cannot provide help: cannot load Pod::Usage\n"); # Note that pod2usage will issue a warning if -exitval => NOEXIT. pod2usage(setup_pa_args("help", @_)); } # Helper routine to set up a normalized hash ref to be used as # argument to pod2usage. sub setup_pa_args($@) { my $tag = shift; # who's calling # If called by direct binding to an option, it will get the option # name and value as arguments. Remove these, if so. @_ = () if @_ == 2 && $_[0] eq $tag; my $pa; if ( @_ > 1 ) { $pa = { @_ }; } else { $pa = shift || {}; } # At this point, $pa can be a number (exit value), string # (message) or hash with options. if ( UNIVERSAL::isa($pa, 'HASH') ) { # Get rid of -msg vs. -message ambiguity. $pa->{-message} = $pa->{-msg}; delete($pa->{-msg}); } elsif ( $pa =~ /^-?\d+$/ ) { $pa = { -exitval => $pa }; } else { $pa = { -message => $pa }; } # These are _our_ defaults. $pa->{-verbose} = 0 unless exists($pa->{-verbose}); $pa->{-exitval} = 0 unless exists($pa->{-exitval}); $pa; } # Sneak way to know what version the user requested. sub VERSION { $requested_version = $_[1] if @_ > 1; shift->SUPER::VERSION(@_); } package Getopt::Long::CallBack; sub new { my ($pkg, %atts) = @_; bless { %atts }, $pkg; } sub name { my $self = shift; ''.$self->{name}; } sub given { my $self = shift; $self->{given}; } use overload # Treat this object as an ordinary string for legacy API. '""' => \&name, fallback => 1; 1; ################ Documentation ################ =head1 NAME Getopt::Long - Extended processing of command line options =head1 SYNOPSIS use Getopt::Long; my $data = "file.dat"; my $length = 24; my $verbose; GetOptions ("length=i" => \$length, # numeric "file=s" => \$data, # string "verbose" => \$verbose) # flag or die("Error in command line arguments\n"); =head1 DESCRIPTION The Getopt::Long module implements an extended getopt function called GetOptions(). It parses the command line from C<@ARGV>, recognizing and removing specified options and their possible values. This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default. =head1 Command Line Options, an Introduction Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line I as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did. Command line options come in several flavours. Historically, they are preceded by a single dash C<->, and consist of a single letter. -l -a -c Usually, these single-character options can be bundled: -lac Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not: -s 24 -s24 Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic C<-l> one could use the more descriptive C<--long>. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Early implementations of long options used a plus C<+> instead. Also, option values could be specified either like --size=24 or --size 24 The C<+> form is now obsolete and strongly deprecated. =head1 Getting Started with Getopt::Long Getopt::Long is the Perl5 successor of C. This was the first Perl module that provided support for handling the new style of command line options, in particular long option names, hence the Perl5 name Getopt::Long. This module also supports single-character options and bundling. To use Getopt::Long from a Perl program, you must include the following line in your Perl program: use Getopt::Long; This will load the core of the Getopt::Long module and prepare your program for using it. Most of the actual Getopt::Long code is not loaded until you really call one of its functions. In the default configuration, options names may be abbreviated to uniqueness, case does not matter, and a single dash is sufficient, even for long option names. Also, options may be placed between non-option arguments. See L for more details on how to configure Getopt::Long. =head2 Simple options The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are: --all --verbose --quiet --debug Handling simple options is straightforward: my $verbose = ''; # option variable with default value (false) my $all = ''; # option variable with default value (false) GetOptions ('verbose' => \$verbose, 'all' => \$all); The call to GetOptions() parses the command line arguments that are present in C<@ARGV> and sets the option variable to the value C<1> if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called I the option. The option name as specified to the GetOptions() function is called the option I. Later we'll see that this specification can contain more than just the option name. The reference to the variable is called the option I. GetOptions() will return a true value if the command line could be processed successfully. Otherwise, it will write error messages using die() and warn(), and return a false result. =head2 A little bit less simple options Getopt::Long supports two useful variants of simple options: I options and I options. A negatable option is specified with an exclamation mark C after the option name: my $verbose = ''; # option variable with default value (false) GetOptions ('verbose!' => \$verbose); Now, using C<--verbose> on the command line will enable C<$verbose>, as expected. But it is also allowed to use C<--noverbose>, which will disable C<$verbose> by setting its value to C<0>. Using a suitable default value, the program can find out whether C<$verbose> is false by default, or disabled by using C<--noverbose>. An incremental option is specified with a plus C<+> after the option name: my $verbose = ''; # option variable with default value (false) GetOptions ('verbose+' => \$verbose); Using C<--verbose> on the command line will increment the value of C<$verbose>. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of C<--verbose> could increase the verbosity level of the program. =head2 Mixing command line option with other arguments Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash C<--> on the command line: --size 24 -- --all In this example, C<--all> will I be treated as an option, but passed to the program unharmed, in C<@ARGV>. =head2 Options with values For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects. Three kinds of values are supported: integer numbers, floating point numbers, and strings. If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself. my $tag = ''; # option variable with default value GetOptions ('tag=s' => \$tag); In the option specification, the option name is followed by an equals sign C<=> and the letter C. The equals sign indicates that this option requires a value. The letter C indicates that this value is an arbitrary string. Other possible value types are C for integer values, and C for floating point values. Using a colon C<:> instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string C<''> assigned, while numeric options are set to C<0>. =head2 Options with multiple values Options sometimes take several values. For example, a program could use multiple directories to search for library files: --library lib/stdlib --library lib/extlib To accomplish this behaviour, simply specify an array reference as the destination for the option: GetOptions ("library=s" => \@libfiles); Alternatively, you can specify that the option can have multiple values by adding a "@", and pass a reference to a scalar as the destination: GetOptions ("library=s@" => \$libfiles); Used with the example above, C<@libfiles> c.q. C<@$libfiles> would contain two strings upon completion: C<"lib/stdlib"> and C<"lib/extlib">, in that order. It is also possible to specify that only integer or floating point numbers are acceptable values. Often it is useful to allow comma-separated lists of values as well as multiple occurrences of the options. This is easy using Perl's split() and join() operators: GetOptions ("library=s" => \@libfiles); @libfiles = split(/,/,join(',',@libfiles)); Of course, it is important to choose the right separator string for each purpose. Warning: What follows is an experimental feature. Options can take multiple values at once, for example --coordinates 52.2 16.4 --rgbcolor 255 255 149 This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the C<{...}> repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows: GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color); The destination for the option must be an array or array reference. It is also possible to specify the minimal and maximal number of arguments an option takes. C indicates an option that takes at least two and at most 4 arguments. C indicates one or more values; C indicates zero or more option values. =head2 Options with hash values If the option destination is a reference to a hash, the option will take, as value, strings of the form IC<=>I. The value will be stored with the specified key in the hash. GetOptions ("define=s" => \%defines); Alternatively you can use: GetOptions ("define=s%" => \$defines); When used with command line options: --define os=linux --define vendor=redhat the hash C<%defines> (or C<%$defines>) will contain two keys, C<"os"> with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings. =head2 User-defined subroutines to handle options Ultimate control over what should be done when (actually: each time) an option is encountered on the command line can be achieved by designating a reference to a subroutine (or an anonymous subroutine) as the option destination. When GetOptions() encounters the option, it will call the subroutine with two or three arguments. The first argument is the name of the option. (Actually, it is an object that stringifies to the name of the option.) For a scalar or array destination, the second argument is the value to be stored. For a hash destination, the second argument is the key to the hash, and the third argument the value to be stored. It is up to the subroutine to store the value, or do whatever it thinks is appropriate. A trivial application of this mechanism is to implement options that are related to each other. For example: my $verbose = ''; # option variable with default value (false) GetOptions ('verbose' => \$verbose, 'quiet' => sub { $verbose = 0 }); Here C<--verbose> and C<--quiet> control the same variable C<$verbose>, but with opposite values. If the subroutine needs to signal an error, it should call die() with the desired error message as its argument. GetOptions() will catch the die(), issue the error message, and record that an error result must be returned upon completion. If the text of the error message starts with an exclamation mark C it is interpreted specially by GetOptions(). There is currently one special command implemented: C will cause GetOptions() to stop processing options, as if it encountered a double dash C<-->. Here is an example of how to access the option name and value from within a subroutine: GetOptions ('opt=i' => \&handler); sub handler { my ($opt_name, $opt_value) = @_; print("Option name is $opt_name and value is $opt_value\n"); } =head2 Options with multiple names Often it is user friendly to supply alternate mnemonic names for options. For example C<--height> could be an alternate name for C<--length>. Alternate names can be included in the option specification, separated by vertical bar C<|> characters. To implement the above example: GetOptions ('length|height=f' => \$length); The first name is called the I name, the other names are called I. When using a hash to store options, the key will always be the primary name. Multiple alternate names are possible. =head2 Case and abbreviations Without additional configuration, GetOptions() will ignore the case of option names, and allow the options to be abbreviated to uniqueness. GetOptions ('length|height=f' => \$length, "head" => \$head); This call will allow C<--l> and C<--L> for the length option, but requires a least C<--hea> and C<--hei> for the head and height options. =head2 Summary of Option Specifications Each option specifier consists of two parts: the name specification and the argument specification. The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters. length option name is "length" length|size|l name is "length", aliases are "size" and "l" The argument specification is optional. If omitted, the option is considered boolean, a value of 1 will be assigned when the option is used on the command line. The argument specification can be =over 4 =item ! The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well. Using negation on a single letter option when bundling is in effect is pointless and will result in a warning. =item + The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. C<"more+">, when used with C<--more --more --more>, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at first). The C<+> specifier is ignored if the option destination is not a scalar. =item = I [ I ] [ I ] The option requires an argument of the given type. Supported types are: =over 4 =item s String. An arbitrary sequence of characters. It is valid for the argument to start with C<-> or C<-->. =item i Integer. An optional leading plus or minus sign, followed by a sequence of digits. =item o Extended integer, Perl style. This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (a zero, optionally followed by '0', '1', .. '7'), or a hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (C<0b> followed by a series of '0' and '1'). =item f Real number. For example C<3.14>, C<-6.23E24> and so on. =back The I can be C<@> or C<%> to specify that the option is list or a hash valued. This is only needed when the destination for the option value is not otherwise specified. It should be omitted when not needed. The I specifies the number of values this option takes per occurrence on the command line. It has the format C<{> [ I ] [ C<,> [ I ] ] C<}>. I denotes the minimal number of arguments. It defaults to 1 for options with C<=> and to 0 for options with C<:>, see below. Note that I overrules the C<=> / C<:> semantics. I denotes the maximum number of arguments. It must be at least I. If I is omitted, I, there is no upper bound to the number of argument values taken. =item : I [ I ] Like C<=>, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options. Note that if a string argument starts with C<-> or C<-->, it will be considered an option on itself. =item : I [ I ] Like C<:i>, but if the value is omitted, the I will be assigned. =item : + [ I ] Like C<:i>, but if the value is omitted, the current value for the option will be incremented. =back =head1 Advanced Possibilities =head2 Object oriented interface Getopt::Long can be used in an object oriented way as well: use Getopt::Long; $p = Getopt::Long::Parser->new; $p->configure(...configuration options...); if ($p->getoptions(...options descriptions...)) ... if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ... Configuration options can be passed to the constructor: $p = new Getopt::Long::Parser config => [...configuration options...]; =head2 Callback object In version 2.37 the first argument to the callback function was changed from string to object. This was done to make room for extensions and more detailed control. The object stringifies to the option name so this change should not introduce compatibility problems. The callback object has the following methods: =over =item name The name of the option, unabbreviated. For an option with multiple names it return the first (canonical) name. =item given The name of the option as actually used, unabbreveated. =back =head2 Thread Safety Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is I thread safe when using the older (experimental and now obsolete) threads implementation that was added to Perl 5.005. =head2 Documentation and help texts Getopt::Long encourages the use of Pod::Usage to produce help messages. For example: use Getopt::Long; use Pod::Usage; my $man = 0; my $help = 0; GetOptions('help|?' => \$help, man => \$man) or pod2usage(2); pod2usage(1) if $help; pod2usage(-exitval => 0, -verbose => 2) if $man; __END__ =head1 NAME sample - Using Getopt::Long and Pod::Usage =head1 SYNOPSIS sample [options] [file ...] Options: -help brief help message -man full documentation =head1 OPTIONS =over 8 =item B<-help> Print a brief help message and exits. =item B<-man> Prints the manual page and exits. =back =head1 DESCRIPTION B will read the given input file(s) and do something useful with the contents thereof. =cut See L for details. =head2 Parsing options from an arbitrary array By default, GetOptions parses the options that are present in the global array C<@ARGV>. A special entry C can be used to parse options from an arbitrary array. use Getopt::Long qw(GetOptionsFromArray); $ret = GetOptionsFromArray(\@myopts, ...); When used like this, options and their possible values are removed from C<@myopts>, the global C<@ARGV> is not touched at all. The following two calls behave identically: $ret = GetOptions( ... ); $ret = GetOptionsFromArray(\@ARGV, ... ); This also means that a first argument hash reference now becomes the second argument: $ret = GetOptions(\%opts, ... ); $ret = GetOptionsFromArray(\@ARGV, \%opts, ... ); =head2 Parsing options from an arbitrary string A special entry C can be used to parse options from an arbitrary string. use Getopt::Long qw(GetOptionsFromString); $ret = GetOptionsFromString($string, ...); The contents of the string are split into arguments using a call to C. As with C, the global C<@ARGV> is not touched. It is possible that, upon completion, not all arguments in the string have been processed. C will, when called in list context, return both the return status and an array reference to any remaining arguments: ($ret, $args) = GetOptionsFromString($string, ... ); If any arguments remain, and C was not called in list context, a message will be given and C will return failure. As with GetOptionsFromArray, a first argument hash reference now becomes the second argument. See the next section. =head2 Storing options values in a hash Sometimes, for example when there are a lot of options, having a separate variable for each of them can be cumbersome. GetOptions() supports, as an alternative mechanism, storing options values in a hash. To obtain this, a reference to a hash must be passed I to GetOptions(). For each option that is specified on the command line, the option value will be stored in the hash with the option name as key. Options that are not actually used on the command line will not be put in the hash, on other words, C (or defined()) can be used to test if an option was used. The drawback is that warnings will be issued if the program runs under C and uses C<$h{option}> without testing with exists() or defined() first. my %h = (); GetOptions (\%h, 'length=i'); # will store in $h{length} For options that take list or hash values, it is necessary to indicate this by appending an C<@> or C<%> sign after the type: GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}} To make things more complicated, the hash may contain references to the actual destinations, for example: my $len = 0; my %h = ('length' => \$len); GetOptions (\%h, 'length=i'); # will store in $len This example is fully equivalent with: my $len = 0; GetOptions ('length=i' => \$len); # will store in $len Any mixture is possible. For example, the most frequently used options could be stored in variables while all other options get stored in the hash: my $verbose = 0; # frequently referred my $debug = 0; # frequently referred my %h = ('verbose' => \$verbose, 'debug' => \$debug); GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i'); if ( $verbose ) { ... } if ( exists $h{filter} ) { ... option 'filter' was specified ... } =head2 Bundling With bundling it is possible to set several single-character options at once. For example if C, C and C are all valid options, -vax will set all three. Getopt::Long supports three styles of bundling. To enable bundling, a call to Getopt::Long::Configure is required. The simplest style of bundling can be enabled with: Getopt::Long::Configure ("bundling"); Configured this way, single-character options can be bundled but long options (and any of their auto-abbreviated shortened forms) B always start with a double dash C<--> to avoid ambiguity. For example, when C, C, C and C are all valid options, -vax will set C, C and C, but --vax will set C. The second style of bundling lifts this restriction. It can be enabled with: Getopt::Long::Configure ("bundling_override"); Now, C<-vax> will set the option C. In all of the above cases, option values may be inserted in the bundle. For example: -h24w80 is equivalent to -h 24 -w 80 A third style of bundling allows only values to be bundled with options. It can be enabled with: Getopt::Long::Configure ("bundling_values"); Now, C<-h24> will set the option C to C<24>, but option bundles like C<-vxa> and C<-h24w80> are flagged as errors. Enabling C will disable the other two styles of bundling. When configured for bundling, single-character options are matched case sensitive while long options are matched case insensitive. To have the single-character options matched case insensitive as well, use: Getopt::Long::Configure ("bundling", "ignorecase_always"); It goes without saying that bundling can be quite confusing. =head2 The lonesome dash Normally, a lone dash C<-> on the command line will not be considered an option. Option processing will terminate (unless "permute" is configured) and the dash will be left in C<@ARGV>. It is possible to get special treatment for a lone dash. This can be achieved by adding an option specification with an empty name, for example: GetOptions ('' => \$stdio); A lone dash on the command line will now be a legal option, and using it will set variable C<$stdio>. =head2 Argument callback A special option 'name' C<< <> >> can be used to designate a subroutine to handle non-option arguments. When GetOptions() encounters an argument that does not look like an option, it will immediately call this subroutine and passes it one parameter: the argument name. For example: my $width = 80; sub process { ... } GetOptions ('width=i' => \$width, '<>' => \&process); When applied to the following command line: arg1 --width=72 arg2 --width=60 arg3 This will call C while C<$width> is C<80>, C while C<$width> is C<72>, and C while C<$width> is C<60>. This feature requires configuration option B, see section L. =head1 Configuring Getopt::Long Getopt::Long can be configured by calling subroutine Getopt::Long::Configure(). This subroutine takes a list of quoted strings, each specifying a configuration option to be enabled, e.g. C. To disable, prefix with C or C, e.g. C. Case does not matter. Multiple calls to Configure() are possible. Alternatively, as of version 2.24, the configuration options may be passed together with the C statement: use Getopt::Long qw(:config no_ignore_case bundling); The following options are available: =over 12 =item default This option causes all configuration options to be reset to their default values. =item posix_default This option causes all configuration options to be reset to their default values as if the environment variable POSIXLY_CORRECT had been set. =item auto_abbrev Allow option names to be abbreviated to uniqueness. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case C is disabled. =item getopt_compat Allow C<+> to start options. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case C is disabled. =item gnu_compat C controls whether C<--opt=> is allowed, and what it should do. Without C, C<--opt=> gives an error. With C, C<--opt=> will give option C and empty value. This is the way GNU getopt_long() does it. Note that C<--opt value> is still accepted, even though GNU getopt_long() doesn't. =item gnu_getopt This is a short way of setting C C C C. With C, command line handling should be reasonably compatible with GNU getopt_long(). =item require_order Whether command line arguments are allowed to be mixed with options. Default is disabled unless environment variable POSIXLY_CORRECT has been set, in which case C is enabled. See also C, which is the opposite of C. =item permute Whether command line arguments are allowed to be mixed with options. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case C is disabled. Note that C is the opposite of C. If C is enabled, this means that --foo arg1 --bar arg2 arg3 is equivalent to --foo --bar arg1 arg2 arg3 If an argument callback routine is specified, C<@ARGV> will always be empty upon successful return of GetOptions() since all options have been processed. The only exception is when C<--> is used: --foo arg1 --bar arg2 -- arg3 This will call the callback routine for arg1 and arg2, and then terminate GetOptions() leaving C<"arg3"> in C<@ARGV>. If C is enabled, options processing terminates when the first non-option is encountered. --foo arg1 --bar arg2 arg3 is equivalent to --foo -- arg1 --bar arg2 arg3 If C is also enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first. =item bundling (default: disabled) Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options (and any of their auto-abbreviated shortened forms) I be introduced with C<--> and bundles with C<->. Note that, if you have options C, C and C, and auto_abbrev enabled, possible arguments and option settings are: using argument sets option(s) ------------------------------------------ -a, --a a -l, --l l -al, -la, -ala, -all,... a, l --al, --all all The surprising part is that C<--a> sets option C (due to auto completion), not C. Note: disabling C also disables C. =item bundling_override (default: disabled) If C is enabled, bundling is enabled as with C but now long option names override option bundles. Note: disabling C also disables C. B Using option bundling can easily lead to unexpected results, especially when mixing long options and bundles. Caveat emptor. =item ignore_case (default: enabled) If enabled, case is ignored when matching option names. If, however, bundling is enabled as well, single character options will be treated case-sensitive. With C, option specifications for options that only differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as duplicates. Note: disabling C also disables C. =item ignore_case_always (default: disabled) When bundling is in effect, case is ignored on single-character options also. Note: disabling C also disables C. =item auto_version (default:disabled) Automatically provide support for the B<--version> option if the application did not specify a handler for this option itself. Getopt::Long will provide a standard version message that includes the program name, its version (if $main::VERSION is defined), and the versions of Getopt::Long and Perl. The message will be written to standard output and processing will terminate. C will be enabled if the calling program explicitly specified a version number higher than 2.32 in the C or C statement. =item auto_help (default:disabled) Automatically provide support for the B<--help> and B<-?> options if the application did not specify a handler for this option itself. Getopt::Long will provide a help message using module L. The message, derived from the SYNOPSIS POD section, will be written to standard output and processing will terminate. C will be enabled if the calling program explicitly specified a version number higher than 2.32 in the C or C statement. =item pass_through (default: disabled) With C anything that is unknown, ambiguous or supplied with an invalid option will not be flagged as an error. Instead the unknown option(s) will be passed to the catchall C<< <> >> if present, otherwise through to C<@ARGV>. This makes it possible to write wrapper scripts that process only part of the user supplied command line arguments, and pass the remaining options to some other program. If C is enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first and all remaining arguments are passed to C<@ARGV> instead of the catchall C<< <> >> if present. However, if C is enabled instead, results can become confusing. Note that the options terminator (default C<-->), if present, will also be passed through in C<@ARGV>. =item prefix The string that starts options. If a constant string is not sufficient, see C. =item prefix_pattern A Perl pattern that identifies the strings that introduce options. Default is C<--|-|\+> unless environment variable POSIXLY_CORRECT has been set, in which case it is C<--|->. =item long_prefix_pattern A Perl pattern that allows the disambiguation of long and short prefixes. Default is C<-->. Typically you only need to set this if you are using nonstandard prefixes and want some or all of them to have the same semantics as '--' does under normal circumstances. For example, setting prefix_pattern to C<--|-|\+|\/> and long_prefix_pattern to C<--|\/> would add Win32 style argument handling. =item debug (default: disabled) Enable debugging output. =back =head1 Exportable Methods =over =item VersionMessage This subroutine provides a standard version message. Its argument can be: =over 4 =item * A string containing the text of a message to print I printing the standard message. =item * A numeric value corresponding to the desired exit status. =item * A reference to a hash. =back If more than one argument is given then the entire argument list is assumed to be a hash. If a hash is supplied (either as a reference or as a list) it should contain one or more elements with the following keys: =over 4 =item C<-message> =item C<-msg> The text of a message to print immediately prior to printing the program's usage message. =item C<-exitval> The desired exit status to pass to the B function. This should be an integer, or else the string "NOEXIT" to indicate that control should simply be returned without terminating the invoking process. =item C<-output> A reference to a filehandle, or the pathname of a file to which the usage message should be written. The default is C<\*STDERR> unless the exit value is less than 2 (in which case the default is C<\*STDOUT>). =back You cannot tie this routine directly to an option, e.g.: GetOptions("version" => \&VersionMessage); Use this instead: GetOptions("version" => sub { VersionMessage() }); =item HelpMessage This subroutine produces a standard help message, derived from the program's POD section SYNOPSIS using L. It takes the same arguments as VersionMessage(). In particular, you cannot tie it directly to an option, e.g.: GetOptions("help" => \&HelpMessage); Use this instead: GetOptions("help" => sub { HelpMessage() }); =back =head1 Return values and Errors Configuration errors and errors in the option definitions are signalled using die() and will terminate the calling program unless the call to Getopt::Long::GetOptions() was embedded in C, or die() was trapped using C<$SIG{__DIE__}>. GetOptions returns true to indicate success. It returns false when the function detected one or more errors during option parsing. These errors are signalled using warn() and can be trapped with C<$SIG{__WARN__}>. =head1 Legacy The earliest development of C started in 1990, with Perl version 4. As a result, its development, and the development of Getopt::Long, has gone through several stages. Since backward compatibility has always been extremely important, the current version of Getopt::Long still supports a lot of constructs that nowadays are no longer necessary or otherwise unwanted. This section describes briefly some of these 'features'. =head2 Default destinations When no destination is specified for an option, GetOptions will store the resultant value in a global variable named CI, where I is the primary name of this option. When a program executes under C (recommended), these variables must be pre-declared with our() or C. our $opt_length = 0; GetOptions ('length=i'); # will store in $opt_length To yield a usable Perl variable, characters that are not part of the syntax for variables are translated to underscores. For example, C<--fpp-struct-return> will set the variable C<$opt_fpp_struct_return>. Note that this variable resides in the namespace of the calling program, not necessarily C
. For example: GetOptions ("size=i", "sizes=i@"); with command line "-size 10 -sizes 24 -sizes 48" will perform the equivalent of the assignments $opt_size = 10; @opt_sizes = (24, 48); =head2 Alternative option starters A string of alternative option starter characters may be passed as the first argument (or the first argument after a leading hash reference argument). my $len = 0; GetOptions ('/', 'length=i' => $len); Now the command line may look like: /length 24 -- arg Note that to terminate options processing still requires a double dash C<-->. GetOptions() will not interpret a leading C<< "<>" >> as option starters if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as option starters, use C<< "><" >>. Confusing? Well, B anyway. =head2 Configuration variables Previous versions of Getopt::Long used variables for the purpose of configuring. Although manipulating these variables still work, it is strongly encouraged to use the C routine that was introduced in version 2.17. Besides, it is much easier. =head1 Tips and Techniques =head2 Pushing multiple values in a hash option Sometimes you want to combine the best of hashes and arrays. For example, the command line: --list add=first --list add=second --list add=third where each successive 'list add' option will push the value of add into array ref $list->{'add'}. The result would be like $list->{add} = [qw(first second third)]; This can be accomplished with a destination routine: GetOptions('list=s%' => sub { push(@{$list{$_[1]}}, $_[2]) }); =head1 Troubleshooting =head2 GetOptions does not return a false result when an option is not supplied That's why they're called 'options'. =head2 GetOptions does not split the command line correctly The command line is not split by GetOptions, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is COMMAND.COM or CMD.EXE. Other operating systems have other CLIs. It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (C<'>) and double quotes (C<">) to group words together. The following alternatives are equivalent on Unix: "two words" 'two words' two\ words In case of doubt, insert the following statement in front of your Perl program: print STDERR (join("|",@ARGV),"\n"); to verify how your CLI passes the arguments to the program. =head2 Undefined subroutine &main::GetOptions called Are you running Windows, and did you write use GetOpt::Long; (note the capital 'O')? =head2 How do I put a "-?" option into a Getopt::Long? You can only obtain this using an alias, and Getopt::Long of at least version 2.13. use Getopt::Long; GetOptions ("help|?"); # -help and -? will both set $opt_help Other characters that can't appear in Perl identifiers are also supported in aliases with Getopt::Long of at version 2.39. Note that the characters C, C<|>, C<+>, C<=>, and C<:> can only appear as the first (or only) character of an alias. As of version 2.32 Getopt::Long provides auto-help, a quick and easy way to add the options --help and -? to your program, and handle them. See C in section L. =head1 AUTHOR Johan Vromans =head1 COPYRIGHT AND DISCLAIMER This program is Copyright 1990,2015 by Johan Vromans. This program is free software; you can redistribute it and/or modify it under the terms of the Perl Artistic License or the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, 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. If you do not have a copy of the GNU General Public License write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. =cut PK!~þÔ¼¤5¤5perl5/Test2/Formatter/TAP.pmnuÏÃ6Ç$package Test2::Formatter::TAP; use strict; use warnings; our $VERSION = '1.302183'; use Test2::Util qw/clone_io/; use Test2::Util::HashBase qw{ no_numbers handles _encoding _last_fh -made_assertion }; sub OUT_STD() { 0 } sub OUT_ERR() { 1 } BEGIN { require Test2::Formatter; our @ISA = qw(Test2::Formatter) } my $supports_tables; sub supports_tables { if (!defined $supports_tables) { local $SIG{__DIE__} = 'DEFAULT'; local $@; $supports_tables = ($INC{'Term/Table.pm'} && $INC{'Term/Table/Util.pm'}) || eval { require Term::Table; require Term::Table::Util; 1 } || 0; } return $supports_tables; } sub _autoflush { my($fh) = pop; my $old_fh = select $fh; $| = 1; select $old_fh; } _autoflush(\*STDOUT); _autoflush(\*STDERR); sub hide_buffered { 1 } sub init { my $self = shift; $self->{+HANDLES} ||= $self->_open_handles; if(my $enc = delete $self->{encoding}) { $self->encoding($enc); } } sub _open_handles { my $self = shift; require Test2::API; my $out = clone_io(Test2::API::test2_stdout()); my $err = clone_io(Test2::API::test2_stderr()); _autoflush($out); _autoflush($err); return [$out, $err]; } sub encoding { my $self = shift; if ($] ge "5.007003" and @_) { my ($enc) = @_; my $handles = $self->{+HANDLES}; # https://rt.perl.org/Public/Bug/Display.html?id=31923 # If utf8 is requested we use ':utf8' instead of ':encoding(utf8)' in # order to avoid the thread segfault. if ($enc =~ m/^utf-?8$/i) { binmode($_, ":utf8") for @$handles; } else { binmode($_, ":encoding($enc)") for @$handles; } $self->{+_ENCODING} = $enc; } return $self->{+_ENCODING}; } if ($^C) { no warnings 'redefine'; *write = sub {}; } sub write { my ($self, $e, $num, $f) = @_; # The most common case, a pass event with no amnesty and a normal name. return if $self->print_optimal_pass($e, $num); $f ||= $e->facet_data; $self->encoding($f->{control}->{encoding}) if $f->{control}->{encoding}; my @tap = $self->event_tap($f, $num) or return; $self->{+MADE_ASSERTION} = 1 if $f->{assert}; my $nesting = $f->{trace}->{nested} || 0; my $handles = $self->{+HANDLES}; my $indent = ' ' x $nesting; # Local is expensive! Only do it if we really need to. local($\, $,) = (undef, '') if $\ || $,; for my $set (@tap) { no warnings 'uninitialized'; my ($hid, $msg) = @$set; next unless $msg; my $io = $handles->[$hid] or next; print $io "\n" if $ENV{HARNESS_ACTIVE} && $hid == OUT_ERR && $self->{+_LAST_FH} != $io && $msg =~ m/^#\s*Failed( \(TODO\))? test /; $msg =~ s/^/$indent/mg if $nesting; print $io $msg; $self->{+_LAST_FH} = $io; } } sub print_optimal_pass { my ($self, $e, $num) = @_; my $type = ref($e); # Only optimal if this is a Pass or a passing Ok return unless $type eq 'Test2::Event::Pass' || ($type eq 'Test2::Event::Ok' && $e->{pass}); # Amnesty requires further processing (todo is a form of amnesty) return if ($e->{amnesty} && @{$e->{amnesty}}) || defined($e->{todo}); # A name with a newline or hash symbol needs extra processing return if defined($e->{name}) && (-1 != index($e->{name}, "\n") || -1 != index($e->{name}, '#')); my $ok = 'ok'; $ok .= " $num" if $num && !$self->{+NO_NUMBERS}; $ok .= defined($e->{name}) ? " - $e->{name}\n" : "\n"; if (my $nesting = $e->{trace}->{nested}) { my $indent = ' ' x $nesting; $ok = "$indent$ok"; } my $io = $self->{+HANDLES}->[OUT_STD]; local($\, $,) = (undef, '') if $\ || $,; print $io $ok; $self->{+_LAST_FH} = $io; return 1; } sub event_tap { my ($self, $f, $num) = @_; my @tap; # If this IS the first event the plan should come first # (plan must be before or after assertions, not in the middle) push @tap => $self->plan_tap($f) if $f->{plan} && !$self->{+MADE_ASSERTION}; # The assertion is most important, if present. if ($f->{assert}) { push @tap => $self->assert_tap($f, $num); push @tap => $self->debug_tap($f, $num) unless $f->{assert}->{no_debug} || $f->{assert}->{pass}; } # Almost as important as an assertion push @tap => $self->error_tap($f) if $f->{errors}; # Now lets see the diagnostics messages push @tap => $self->info_tap($f) if $f->{info}; # If this IS NOT the first event the plan should come last # (plan must be before or after assertions, not in the middle) push @tap => $self->plan_tap($f) if $self->{+MADE_ASSERTION} && $f->{plan}; # Bail out push @tap => $self->halt_tap($f) if $f->{control}->{halt}; return @tap if @tap; return @tap if $f->{control}->{halt}; return @tap if grep { $f->{$_} } qw/assert plan info errors/; # Use the summary as a fallback if nothing else is usable. return $self->summary_tap($f, $num); } sub error_tap { my $self = shift; my ($f) = @_; my $IO = ($f->{amnesty} && @{$f->{amnesty}}) ? OUT_STD : OUT_ERR; return map { my $details = $_->{details}; my $msg; if (ref($details)) { require Data::Dumper; my $dumper = Data::Dumper->new([$details])->Indent(2)->Terse(1)->Pad('# ')->Useqq(1)->Sortkeys(1); chomp($msg = $dumper->Dump); } else { chomp($msg = $details); $msg =~ s/^/# /; $msg =~ s/\n/\n# /g; } [$IO, "$msg\n"]; } @{$f->{errors}}; } sub plan_tap { my $self = shift; my ($f) = @_; my $plan = $f->{plan} or return; return if $plan->{none}; if ($plan->{skip}) { my $reason = $plan->{details} or return [OUT_STD, "1..0 # SKIP\n"]; chomp($reason); return [OUT_STD, '1..0 # SKIP ' . $reason . "\n"]; } return [OUT_STD, "1.." . $plan->{count} . "\n"]; } sub no_subtest_space { 0 } sub assert_tap { my $self = shift; my ($f, $num) = @_; my $assert = $f->{assert} or return; my $pass = $assert->{pass}; my $name = $assert->{details}; my $ok = $pass ? 'ok' : 'not ok'; $ok .= " $num" if $num && !$self->{+NO_NUMBERS}; # The regex form is ~250ms, the index form is ~50ms my @extra; defined($name) && ( (index($name, "\n") != -1 && (($name, @extra) = split(/\n\r?/, $name, -1))), ((index($name, "#" ) != -1 || substr($name, -1) eq '\\') && (($name =~ s|\\|\\\\|g), ($name =~ s|#|\\#|g))) ); my $extra_space = @extra ? ' ' x (length($ok) + 2) : ''; my $extra_indent = ''; my ($directives, $reason, $is_skip); if ($f->{amnesty}) { my %directives; for my $am (@{$f->{amnesty}}) { next if $am->{inherited}; my $tag = $am->{tag} or next; $is_skip = 1 if $tag eq 'skip'; $directives{$tag} ||= $am->{details}; } my %seen; # Sort so that TODO comes before skip even on systems where lc sorts # before uc, as other code depends on that ordering. my @order = grep { !$seen{$_}++ } sort { lc $b cmp lc $a } keys %directives; $directives = ' # ' . join ' & ' => @order; for my $tag ('skip', @order) { next unless defined($directives{$tag}) && length($directives{$tag}); $reason = $directives{$tag}; last; } } $ok .= " - $name" if defined $name && !($is_skip && !$name); my @subtap; if ($f->{parent} && $f->{parent}->{buffered}) { $ok .= ' {'; # In a verbose harness we indent the extra since they will appear # inside the subtest braces. This helps readability. In a non-verbose # harness we do not do this because it is less readable. if ($ENV{HARNESS_IS_VERBOSE} || !$ENV{HARNESS_ACTIVE}) { $extra_indent = " "; $extra_space = ' '; } # Render the sub-events, we use our own counter for these. my $count = 0; @subtap = map { my $f2 = $_; # Bump the count for any event that should bump it. $count++ if $f2->{assert}; # This indents all output lines generated for the sub-events. # index 0 is the filehandle, index 1 is the message we want to indent. map { $_->[1] =~ s/^(.*\S.*)$/ $1/mg; $_ } $self->event_tap($f2, $count); } @{$f->{parent}->{children}}; push @subtap => [OUT_STD, "}\n"]; } if ($directives) { $directives = ' # TODO & SKIP' if $directives eq ' # TODO & skip'; $ok .= $directives; $ok .= " $reason" if defined($reason); } $extra_space = ' ' if $self->no_subtest_space; my @out = ([OUT_STD, "$ok\n"]); push @out => map {[OUT_STD, "${extra_indent}#${extra_space}$_\n"]} @extra if @extra; push @out => @subtap; return @out; } sub debug_tap { my ($self, $f, $num) = @_; # Figure out the debug info, this is typically the file name and line # number, but can also be a custom message. If no trace object is provided # then we have nothing useful to display. my $name = $f->{assert}->{details}; my $trace = $f->{trace}; my $debug = "[No trace info available]"; if ($trace->{details}) { $debug = $trace->{details}; } elsif ($trace->{frame}) { my ($pkg, $file, $line) = @{$trace->{frame}}; $debug = "at $file line $line." if $file && $line; } my $amnesty = $f->{amnesty} && @{$f->{amnesty}} ? ' (with amnesty)' : ''; # Create the initial diagnostics. If the test has a name we put the debug # info on a second line, this behavior is inherited from Test::Builder. my $msg = defined($name) ? qq[# Failed test${amnesty} '$name'\n# $debug\n] : qq[# Failed test${amnesty} $debug\n]; my $IO = $f->{amnesty} && @{$f->{amnesty}} ? OUT_STD : OUT_ERR; return [$IO, $msg]; } sub halt_tap { my ($self, $f) = @_; return if $f->{trace}->{nested} && !$f->{trace}->{buffered}; my $details = $f->{control}->{details}; return [OUT_STD, "Bail out!\n"] unless defined($details) && length($details); return [OUT_STD, "Bail out! $details\n"]; } sub info_tap { my ($self, $f) = @_; return map { my $details = $_->{details}; my $table = $_->{table}; my $IO = $_->{debug} && !($f->{amnesty} && @{$f->{amnesty}}) ? OUT_ERR : OUT_STD; my $msg; if ($table && $self->supports_tables) { $msg = join "\n" => map { "# $_" } Term::Table->new( header => $table->{header}, rows => $table->{rows}, collapse => $table->{collapse}, no_collapse => $table->{no_collapse}, sanitize => 1, mark_tail => 1, max_width => $self->calc_table_size($f), )->render(); } elsif (ref($details)) { require Data::Dumper; my $dumper = Data::Dumper->new([$details])->Indent(2)->Terse(1)->Pad('# ')->Useqq(1)->Sortkeys(1); chomp($msg = $dumper->Dump); } else { chomp($msg = $details); $msg =~ s/^/# /; $msg =~ s/\n/\n# /g; } [$IO, "$msg\n"]; } @{$f->{info}}; } sub summary_tap { my ($self, $f, $num) = @_; return if $f->{about}->{no_display}; my $summary = $f->{about}->{details} or return; chomp($summary); $summary =~ s/^/# /smg; return [OUT_STD, "$summary\n"]; } sub calc_table_size { my $self = shift; my ($f) = @_; my $term = Term::Table::Util::term_size(); my $nesting = 2 + (($f->{trace}->{nested} || 0) * 4); # 4 spaces per level, also '# ' prefix my $total = $term - $nesting; # Sane minimum width, any smaller and we are asking for pain return 50 if $total < 50; return $total; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Formatter::TAP - Standard TAP formatter =head1 DESCRIPTION This is what takes events and turns them into TAP. =head1 SYNOPSIS use Test2::Formatter::TAP; my $tap = Test2::Formatter::TAP->new(); # Switch to utf8 $tap->encoding('utf8'); $tap->write($event, $number); # Output an event =head1 METHODS =over 4 =item $bool = $tap->no_numbers =item $tap->set_no_numbers($bool) Use to turn numbers on and off. =item $arrayref = $tap->handles =item $tap->set_handles(\@handles); Can be used to get/set the filehandles. Indexes are identified by the C and C constants. =item $encoding = $tap->encoding =item $tap->encoding($encoding) Get or set the encoding. By default no encoding is set, the original settings of STDOUT and STDERR are used. This directly modifies the stored filehandles, it does not create new ones. =item $tap->write($e, $num) Write an event to the console. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =item Kent Fredric Ekentnl@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!Á™.))perl5/Test2/Util.pmnuÏÃ6Ç$package Test2::Util; use strict; use warnings; our $VERSION = '1.302183'; use POSIX(); use Config qw/%Config/; use Carp qw/croak/; BEGIN { local ($@, $!, $SIG{__DIE__}); *HAVE_PERLIO = eval { require PerlIO; PerlIO->VERSION(1.02); } ? sub() { 1 } : sub() { 0 }; } our @EXPORT_OK = qw{ try pkg_to_file get_tid USE_THREADS CAN_THREAD CAN_REALLY_FORK CAN_FORK CAN_SIGSYS IS_WIN32 ipc_separator gen_uid do_rename do_unlink try_sig_mask clone_io }; BEGIN { require Exporter; our @ISA = qw(Exporter) } BEGIN { *IS_WIN32 = ($^O eq 'MSWin32') ? sub() { 1 } : sub() { 0 }; } sub _can_thread { return 0 unless $] >= 5.008001; return 0 unless $Config{'useithreads'}; # Threads are broken on perl 5.10.0 built with gcc 4.8+ if ($] == 5.010000 && $Config{'ccname'} eq 'gcc' && $Config{'gccversion'}) { my @parts = split /\./, $Config{'gccversion'}; return 0 if $parts[0] > 4 || ($parts[0] == 4 && $parts[1] >= 8); } # Change to a version check if this ever changes return 0 if $INC{'Devel/Cover.pm'}; return 1; } sub _can_fork { return 1 if $Config{d_fork}; return 0 unless IS_WIN32 || $^O eq 'NetWare'; return 0 unless $Config{useithreads}; return 0 unless $Config{ccflags} =~ /-DPERL_IMPLICIT_SYS/; return _can_thread(); } BEGIN { no warnings 'once'; *CAN_THREAD = _can_thread() ? sub() { 1 } : sub() { 0 }; } my $can_fork; sub CAN_FORK () { return $can_fork if defined $can_fork; $can_fork = !!_can_fork(); no warnings 'redefine'; *CAN_FORK = $can_fork ? sub() { 1 } : sub() { 0 }; $can_fork; } my $can_really_fork; sub CAN_REALLY_FORK () { return $can_really_fork if defined $can_really_fork; $can_really_fork = !!$Config{d_fork}; no warnings 'redefine'; *CAN_REALLY_FORK = $can_really_fork ? sub() { 1 } : sub() { 0 }; $can_really_fork; } sub _manual_try(&;@) { my $code = shift; my $args = \@_; my $err; my $die = delete $SIG{__DIE__}; eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; $die ? $SIG{__DIE__} = $die : delete $SIG{__DIE__}; return (!defined($err), $err); } sub _local_try(&;@) { my $code = shift; my $args = \@_; my $err; no warnings; local $SIG{__DIE__}; eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; return (!defined($err), $err); } # Older versions of perl have a nasty bug on win32 when localizing a variable # before forking or starting a new thread. So for those systems we use the # non-local form. When possible though we use the faster 'local' form. BEGIN { if (IS_WIN32 && $] < 5.020002) { *try = \&_manual_try; } else { *try = \&_local_try; } } BEGIN { if (CAN_THREAD) { if ($INC{'threads.pm'}) { # Threads are already loaded, so we do not need to check if they # are loaded each time *USE_THREADS = sub() { 1 }; *get_tid = sub() { threads->tid() }; } else { # :-( Need to check each time to see if they have been loaded. *USE_THREADS = sub() { $INC{'threads.pm'} ? 1 : 0 }; *get_tid = sub() { $INC{'threads.pm'} ? threads->tid() : 0 }; } } else { # No threads, not now, not ever! *USE_THREADS = sub() { 0 }; *get_tid = sub() { 0 }; } } sub pkg_to_file { my $pkg = shift; my $file = $pkg; $file =~ s{(::|')}{/}g; $file .= '.pm'; return $file; } sub ipc_separator() { "~" } my $UID = 1; sub gen_uid() { join ipc_separator() => ($$, get_tid(), time, $UID++) } sub _check_for_sig_sys { my $sig_list = shift; return $sig_list =~ m/\bSYS\b/; } BEGIN { if (_check_for_sig_sys($Config{sig_name})) { *CAN_SIGSYS = sub() { 1 }; } else { *CAN_SIGSYS = sub() { 0 }; } } my %PERLIO_SKIP = ( unix => 1, via => 1, ); sub clone_io { my ($fh) = @_; my $fileno = eval { fileno($fh) }; return $fh if !defined($fileno) || !length($fileno) || $fileno < 0; open(my $out, '>&' . $fileno) or die "Can't dup fileno $fileno: $!"; my %seen; my @layers = HAVE_PERLIO ? grep { !$PERLIO_SKIP{$_} and !$seen{$_}++ } PerlIO::get_layers($fh) : (); binmode($out, join(":", "", "raw", @layers)); my $old = select $fh; my $af = $|; select $out; $| = $af; select $old; return $out; } BEGIN { if (IS_WIN32) { my $max_tries = 5; *do_rename = sub { my ($from, $to) = @_; my $err; for (1 .. $max_tries) { return (1) if rename($from, $to); $err = "$!"; last if $_ == $max_tries; sleep 1; } return (0, $err); }; *do_unlink = sub { my ($file) = @_; my $err; for (1 .. $max_tries) { return (1) if unlink($file); $err = "$!"; last if $_ == $max_tries; sleep 1; } return (0, "$!"); }; } else { *do_rename = sub { my ($from, $to) = @_; return (1) if rename($from, $to); return (0, "$!"); }; *do_unlink = sub { my ($file) = @_; return (1) if unlink($file); return (0, "$!"); }; } } sub try_sig_mask(&) { my $code = shift; my ($old, $blocked); unless(IS_WIN32) { my $to_block = POSIX::SigSet->new( POSIX::SIGINT(), POSIX::SIGALRM(), POSIX::SIGHUP(), POSIX::SIGTERM(), POSIX::SIGUSR1(), POSIX::SIGUSR2(), ); $old = POSIX::SigSet->new; $blocked = POSIX::sigprocmask(POSIX::SIG_BLOCK(), $to_block, $old); # Silently go on if we failed to log signals, not much we can do. } my ($ok, $err) = &try($code); # If our block was successful we want to restore the old mask. POSIX::sigprocmask(POSIX::SIG_SETMASK(), $old, POSIX::SigSet->new()) if defined $blocked; return ($ok, $err); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Util - Tools used by Test2 and friends. =head1 DESCRIPTION Collection of tools used by L and friends. =head1 EXPORTS All exports are optional. You must specify subs to import. =over 4 =item ($success, $error) = try { ... } Eval the codeblock, return success or failure, and the error message. This code protects $@ and $!, they will be restored by the end of the run. This code also temporarily blocks $SIG{DIE} handlers. =item protect { ... } Similar to try, except that it does not catch exceptions. The idea here is to protect $@ and $! from changes. $@ and $! will be restored to whatever they were before the run so long as it is successful. If the run fails $! will still be restored, but $@ will contain the exception being thrown. =item CAN_FORK True if this system is capable of true or pseudo-fork. =item CAN_REALLY_FORK True if the system can really fork. This will be false for systems where fork is emulated. =item CAN_THREAD True if this system is capable of using threads. =item USE_THREADS Returns true if threads are enabled, false if they are not. =item get_tid This will return the id of the current thread when threads are enabled, otherwise it returns 0. =item my $file = pkg_to_file($package) Convert a package name to a filename. =item $string = ipc_separator() Get the IPC separator. Currently this is always the string C<'~'>. =item $string = gen_uid() Generate a unique id (NOT A UUID). This will typically be the process id, the thread id, the time, and an incrementing integer all joined with the C. These ID's are unique enough for most purposes. For identical ids to be generated you must have 2 processes with the same PID generate IDs at the same time with the same current state of the incrementing integer. This is a perfectly reasonable thing to expect to happen across multiple machines, but is quite unlikely to happen on one machine. This can fail to be unique if a process generates an id, calls exec, and does it again after the exec and it all happens in less than a second. It can also happen if the systems process id's cycle in less than a second allowing 2 different programs that use this generator to run with the same PID in less than a second. Both these cases are sufficiently unlikely. If you need universally unique ids, or ids that are unique in these conditions, look at L. =item ($ok, $err) = do_rename($old_name, $new_name) Rename a file, this wraps C in a way that makes it more reliable cross-platform when trying to rename files you recently altered. =item ($ok, $err) = do_unlink($filename) Unlink a file, this wraps C in a way that makes it more reliable cross-platform when trying to unlink files you recently altered. =item ($ok, $err) = try_sig_mask { ... } Complete an action with several signals masked, they will be unmasked at the end allowing any signals that were intercepted to get handled. This is primarily used when you need to make several actions atomic (against some signals anyway). Signals that are intercepted: =over 4 =item SIGINT =item SIGALRM =item SIGHUP =item SIGTERM =item SIGUSR1 =item SIGUSR2 =back =back =head1 NOTES && CAVEATS =over 4 =item 5.10.0 Perl 5.10.0 has a bug when compiled with newer gcc versions. This bug causes a segfault whenever a new thread is launched. Test2 will attempt to detect this, and note that the system is not capable of forking when it is detected. =item Devel::Cover Devel::Cover does not support threads. CAN_THREAD will return false if Devel::Cover is loaded before the check is first run. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =item Kent Fredric Ekentnl@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!¬5�zzperl5/Test2/IPC/Driver.pmnuÏÃ6Ç$package Test2::IPC::Driver; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/confess/; use Test2::Util::HashBase qw{no_fatal no_bail}; use Test2::API qw/test2_ipc_add_driver/; my %ADDED; sub import { my $class = shift; return if $class eq __PACKAGE__; return if $ADDED{$class}++; test2_ipc_add_driver($class); } sub pending { -1 } sub set_pending { -1 } for my $meth (qw/send cull add_hub drop_hub waiting is_viable/) { no strict 'refs'; *$meth = sub { my $thing = shift; confess "'$thing' did not define the required method '$meth'." }; } # Print the error and call exit. We are not using 'die' cause this is a # catastrophic error that should never be caught. If we get here it # means some serious shit has happened in a child process, the only way # to inform the parent may be to exit false. sub abort { my $self = shift; chomp(my ($msg) = @_); $self->driver_abort($msg) if $self->can('driver_abort'); print STDERR "IPC Fatal Error: $msg\n"; print STDOUT "Bail out! IPC Fatal Error: $msg\n" unless $self->no_bail; CORE::exit(255) unless $self->no_fatal; } sub abort_trace { my $self = shift; my ($msg) = @_; # Older versions of Carp do not export longmess() function, so it needs to be called with package name $self->abort(Carp::longmess($msg)); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::IPC::Driver - Base class for Test2 IPC drivers. =head1 SYNOPSIS package Test2::IPC::Driver::MyDriver; use base 'Test2::IPC::Driver'; ... =head1 METHODS =over 4 =item $self->abort($msg) If an IPC encounters a fatal error it should use this. This will print the message to STDERR with C<'IPC Fatal Error: '> prefixed to it, then it will forcefully exit 255. IPC errors may occur in threads or processes other than the main one, this method provides the best chance of the harness noticing the error. =item $self->abort_trace($msg) This is the same as C<< $ipc->abort($msg) >> except that it uses C to add a stack trace to the message. =back =head1 LOADING DRIVERS Test2::IPC::Driver has an C method. All drivers inherit this import method. This import method registers the driver. In most cases you just need to load the desired IPC driver to make it work. You should load this driver as early as possible. A warning will be issued if you load it too late for it to be effective. use Test2::IPC::Driver::MyDriver; ... =head1 WRITING DRIVERS package Test2::IPC::Driver::MyDriver; use strict; use warnings; use base 'Test2::IPC::Driver'; sub is_viable { return 0 if $^O eq 'win32'; # Will not work on windows. return 1; } sub add_hub { my $self = shift; my ($hid) = @_; ... # Make it possible to contact the hub } sub drop_hub { my $self = shift; my ($hid) = @_; ... # Nothing should try to reach the hub anymore. } sub send { my $self = shift; my ($hid, $e, $global) = @_; ... # Send the event to the proper hub. # This may notify other procs/threads that there is a pending event. Test2::API::test2_ipc_set_pending($uniq_val); } sub cull { my $self = shift; my ($hid) = @_; my @events = ...; # Here is where you get the events for the hub return @events; } sub waiting { my $self = shift; ... # Notify all listening procs and threads that the main ... # process/thread is waiting for them to finish. } 1; =head2 METHODS SUBCLASSES MUST IMPLEMENT =over 4 =item $ipc->is_viable This should return true if the driver works in the current environment. This should return false if it does not. This is a CLASS method. =item $ipc->add_hub($hid) This is used to alert the driver that a new hub is expecting events. The driver should keep track of the process and thread ids, the hub should only be dropped by the proc+thread that started it. sub add_hub { my $self = shift; my ($hid) = @_; ... # Make it possible to contact the hub } =item $ipc->drop_hub($hid) This is used to alert the driver that a hub is no longer accepting events. The driver should keep track of the process and thread ids, the hub should only be dropped by the proc+thread that started it (This is the drivers responsibility to enforce). sub drop_hub { my $self = shift; my ($hid) = @_; ... # Nothing should try to reach the hub anymore. } =item $ipc->send($hid, $event); =item $ipc->send($hid, $event, $global); Used to send events from the current process/thread to the specified hub in its process+thread. sub send { my $self = shift; my ($hid, $e) = @_; ... # Send the event to the proper hub. # This may notify other procs/threads that there is a pending event. Test2::API::test2_ipc_set_pending($uniq_val); } If C<$global> is true then the driver should send the event to all hubs in all processes and threads. =item @events = $ipc->cull($hid) Used to collect events that have been sent to the specified hub. sub cull { my $self = shift; my ($hid) = @_; my @events = ...; # Here is where you get the events for the hub return @events; } =item $ipc->waiting() This is called in the parent process when it is complete and waiting for all child processes and threads to complete. sub waiting { my $self = shift; ... # Notify all listening procs and threads that the main ... # process/thread is waiting for them to finish. } =back =head2 METHODS SUBCLASSES MAY IMPLEMENT OR OVERRIDE =over 4 =item $ipc->driver_abort($msg) This is a hook called by C<< Test2::IPC::Driver->abort() >>. This is your chance to cleanup when an abort happens. You cannot prevent the abort, but you can gracefully except it. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!Uú\ü4ü4perl5/Test2/IPC/Driver/Files.pmnuÏÃ6Ç$package Test2::IPC::Driver::Files; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::IPC::Driver; our @ISA = qw(Test2::IPC::Driver) } use Test2::Util::HashBase qw{tempdir event_ids read_ids timeouts tid pid globals}; use Scalar::Util qw/blessed/; use File::Temp(); use Storable(); use File::Spec(); use POSIX(); use Test2::Util qw/try get_tid pkg_to_file IS_WIN32 ipc_separator do_rename do_unlink try_sig_mask/; use Test2::API qw/test2_ipc_set_pending/; sub is_viable { 1 } sub init { my $self = shift; my $tmpdir = File::Temp::tempdir( $ENV{T2_TEMPDIR_TEMPLATE} || "test2" . ipc_separator . $$ . ipc_separator . "XXXXXX", CLEANUP => 0, TMPDIR => 1, ); $self->abort_trace("Could not get a temp dir") unless $tmpdir; $self->{+TEMPDIR} = File::Spec->canonpath($tmpdir); print STDERR "\nIPC Temp Dir: $tmpdir\n\n" if $ENV{T2_KEEP_TEMPDIR}; $self->{+EVENT_IDS} = {}; $self->{+READ_IDS} = {}; $self->{+TIMEOUTS} = {}; $self->{+TID} = get_tid(); $self->{+PID} = $$; $self->{+GLOBALS} = {}; return $self; } sub hub_file { my $self = shift; my ($hid) = @_; my $tdir = $self->{+TEMPDIR}; return File::Spec->catfile($tdir, "HUB" . ipc_separator . $hid); } sub event_file { my $self = shift; my ($hid, $e) = @_; my $tempdir = $self->{+TEMPDIR}; my $type = blessed($e) or $self->abort("'$e' is not a blessed object!"); $self->abort("'$e' is not an event object!") unless $type->isa('Test2::Event'); my $tid = get_tid(); my $eid = $self->{+EVENT_IDS}->{$hid}->{$$}->{$tid} += 1; my @type = split '::', $type; my $name = join(ipc_separator, $hid, $$, $tid, $eid, @type); return File::Spec->catfile($tempdir, $name); } sub add_hub { my $self = shift; my ($hid) = @_; my $hfile = $self->hub_file($hid); $self->abort_trace("File for hub '$hid' already exists") if -e $hfile; open(my $fh, '>', $hfile) or $self->abort_trace("Could not create hub file '$hid': $!"); print $fh "$$\n" . get_tid() . "\n"; close($fh); } sub drop_hub { my $self = shift; my ($hid) = @_; my $tdir = $self->{+TEMPDIR}; my $hfile = $self->hub_file($hid); $self->abort_trace("File for hub '$hid' does not exist") unless -e $hfile; open(my $fh, '<', $hfile) or $self->abort_trace("Could not open hub file '$hid': $!"); my ($pid, $tid) = <$fh>; close($fh); $self->abort_trace("A hub file can only be closed by the process that started it\nExpected $pid, got $$") unless $pid == $$; $self->abort_trace("A hub file can only be closed by the thread that started it\nExpected $tid, got " . get_tid()) unless get_tid() == $tid; if ($ENV{T2_KEEP_TEMPDIR}) { my ($ok, $err) = do_rename($hfile, File::Spec->canonpath("$hfile.complete")); $self->abort_trace("Could not rename file '$hfile' -> '$hfile.complete': $err") unless $ok } else { my ($ok, $err) = do_unlink($hfile); $self->abort_trace("Could not remove file for hub '$hid': $err") unless $ok } opendir(my $dh, $tdir) or $self->abort_trace("Could not open temp dir!"); my %bad; for my $file (readdir($dh)) { next if $file =~ m{\.complete$}; next unless $file =~ m{^$hid}; eval { $bad{$file} = $self->read_event_file(File::Spec->catfile($tdir, $file)); 1 } or $bad{$file} = $@ || "Unknown error reading file"; } closedir($dh); return unless keys %bad; my $data; my $ok = eval { require JSON::PP; local *UNIVERSAL::TO_JSON = sub { +{ %{$_[0]} } }; my $json = JSON::PP->new->ascii->pretty->canonical->allow_unknown->allow_blessed->convert_blessed; $data = $json->encode(\%bad); 1; }; $ok ||= eval { require Data::Dumper; local $Data::Dumper::Sortkeys = 1; $data = Data::Dumper::Dumper(\%bad); 1; }; $data = "Could not dump data... sorry." unless defined $data; $self->abort_trace("Not all files from hub '$hid' have been collected!\nHere is the leftover data:\n========================\n$data\n===================\n"); } sub send { my $self = shift; my ($hid, $e, $global) = @_; my $tempdir = $self->{+TEMPDIR}; my $hfile = $self->hub_file($hid); my $dest = $global ? 'GLOBAL' : $hid; $self->abort(<<" EOT") unless $global || -f $hfile; hub '$hid' is not available, failed to send event! There was an attempt to send an event to a hub in a parent process or thread, but that hub appears to be gone. This can happen if you fork, or start a new thread from inside subtest, and the parent finishes the subtest before the child returns. This can also happen if the parent process is done testing before the child finishes. Test2 normally waits automatically in the root process, but will not do so if Test::Builder is loaded for legacy reasons. EOT my $file = $self->event_file($dest, $e); my $ready = File::Spec->canonpath("$file.ready"); if ($global) { my $name = $ready; $name =~ s{^.*(GLOBAL)}{GLOBAL}; $self->{+GLOBALS}->{$hid}->{$name}++; } # Write and rename the file. my ($ren_ok, $ren_err); my ($ok, $err) = try_sig_mask(sub { Storable::store($e, $file); ($ren_ok, $ren_err) = do_rename("$file", $ready); }); if ($ok) { $self->abort("Could not rename file '$file' -> '$ready': $ren_err") unless $ren_ok; test2_ipc_set_pending($file); } else { my $src_file = __FILE__; $err =~ s{ at \Q$src_file\E.*$}{}; chomp($err); my $tid = get_tid(); my $trace = $e->trace->debug; my $type = blessed($e); $self->abort(<<" EOT"); ******************************************************************************* There was an error writing an event: Destination: $dest Origin PID: $$ Origin TID: $tid Event Type: $type Event Trace: $trace File Name: $file Ready Name: $ready Error: $err ******************************************************************************* EOT } return 1; } sub driver_abort { my $self = shift; my ($msg) = @_; local ($@, $!, $?, $^E); eval { my $abort = File::Spec->catfile($self->{+TEMPDIR}, "ABORT"); open(my $fh, '>>', $abort) or die "Could not open abort file: $!"; print $fh $msg, "\n"; close($fh) or die "Could not close abort file: $!"; 1; } or warn $@; } sub cull { my $self = shift; my ($hid) = @_; my $tempdir = $self->{+TEMPDIR}; opendir(my $dh, $tempdir) or $self->abort("could not open IPC temp dir ($tempdir)!"); my $read = $self->{+READ_IDS}; my $timeouts = $self->{+TIMEOUTS}; my @out; for my $info (sort cmp_events map { $self->should_read_event($hid, $_) } readdir($dh)) { unless ($info->{global}) { my $next = $self->{+READ_IDS}->{$info->{hid}}->{$info->{pid}}->{$info->{tid}} ||= 1; $timeouts->{$info->{file}} ||= time; if ($next != $info->{eid}) { # Wait up to N seconds for missing events next unless 5 < time - $timeouts->{$info->{file}}; $self->abort("Missing event HID: $info->{hid}, PID: $info->{pid}, TID: $info->{tid}, EID: $info->{eid}."); } $self->{+READ_IDS}->{$info->{hid}}->{$info->{pid}}->{$info->{tid}} = $info->{eid} + 1; } my $full = $info->{full_path}; my $obj = $self->read_event_file($full); push @out => $obj; # Do not remove global events next if $info->{global}; if ($ENV{T2_KEEP_TEMPDIR}) { my $complete = File::Spec->canonpath("$full.complete"); my ($ok, $err) = do_rename($full, $complete); $self->abort("Could not rename IPC file '$full', '$complete': $err") unless $ok; } else { my ($ok, $err) = do_unlink("$full"); $self->abort("Could not unlink IPC file '$full': $err") unless $ok; } } closedir($dh); return @out; } sub parse_event_filename { my $self = shift; my ($file) = @_; # The || is to force 0 in false my $complete = substr($file, -9, 9) eq '.complete' || 0 and substr($file, -9, 9, ""); my $ready = substr($file, -6, 6) eq '.ready' || 0 and substr($file, -6, 6, ""); my @parts = split ipc_separator, $file; my ($global, $hid) = $parts[0] eq 'GLOBAL' ? (1, shift @parts) : (0, join ipc_separator, splice(@parts, 0, 4)); my ($pid, $tid, $eid) = splice(@parts, 0, 3); my $type = join '::' => @parts; return { file => $file, ready => $ready, complete => $complete, global => $global, type => $type, hid => $hid, pid => $pid, tid => $tid, eid => $eid, }; } sub should_read_event { my $self = shift; my ($hid, $file) = @_; return if substr($file, 0, 1) eq '.'; return if substr($file, 0, 3) eq 'HUB'; CORE::exit(255) if $file eq 'ABORT'; my $parsed = $self->parse_event_filename($file); return if $parsed->{complete}; return unless $parsed->{ready}; return unless $parsed->{global} || $parsed->{hid} eq $hid; return if $parsed->{global} && $self->{+GLOBALS}->{$hid}->{$file}++; # Untaint the path. my $full = File::Spec->catfile($self->{+TEMPDIR}, $file); ($full) = ($full =~ m/^(.*)$/gs) if ${^TAINT}; $parsed->{full_path} = $full; return $parsed; } sub cmp_events { # Globals first return -1 if $a->{global} && !$b->{global}; return 1 if $b->{global} && !$a->{global}; return $a->{pid} <=> $b->{pid} || $a->{tid} <=> $b->{tid} || $a->{eid} <=> $b->{eid}; } sub read_event_file { my $self = shift; my ($file) = @_; my $obj = Storable::retrieve($file); $self->abort("Got an unblessed object: '$obj'") unless blessed($obj); unless ($obj->isa('Test2::Event')) { my $pkg = blessed($obj); my $mod_file = pkg_to_file($pkg); my ($ok, $err) = try { require $mod_file }; $self->abort("Event has unknown type ($pkg), tried to load '$mod_file' but failed: $err") unless $ok; $self->abort("'$obj' is not a 'Test2::Event' object") unless $obj->isa('Test2::Event'); } return $obj; } sub waiting { my $self = shift; require Test2::Event::Waiting; $self->send( GLOBAL => Test2::Event::Waiting->new( trace => Test2::EventFacet::Trace->new(frame => [caller()]), ), 'GLOBAL' ); return; } sub DESTROY { my $self = shift; return unless defined $self->pid; return unless defined $self->tid; return unless $$ == $self->pid; return unless get_tid() == $self->tid; my $tempdir = $self->{+TEMPDIR}; my $aborted = 0; my $abort_file = File::Spec->catfile($self->{+TEMPDIR}, "ABORT"); if (-e $abort_file) { $aborted = 1; my ($ok, $err) = do_unlink($abort_file); warn $err unless $ok; } opendir(my $dh, $tempdir) or $self->abort("Could not open temp dir! ($tempdir)"); while(my $file = readdir($dh)) { next if $file =~ m/^\.+$/; next if $file =~ m/\.complete$/; my $full = File::Spec->catfile($tempdir, $file); my $sep = ipc_separator; if ($aborted || $file =~ m/^(GLOBAL|HUB$sep)/) { $full =~ m/^(.*)$/; $full = $1; # Untaint it next if $ENV{T2_KEEP_TEMPDIR}; my ($ok, $err) = do_unlink($full); $self->abort("Could not unlink IPC file '$full': $err") unless $ok; next; } $self->abort("Leftover files in the directory ($full)!\n"); } closedir($dh); if ($ENV{T2_KEEP_TEMPDIR}) { print STDERR "# Not removing temp dir: $tempdir\n"; return; } my $abort = File::Spec->catfile($self->{+TEMPDIR}, "ABORT"); unlink($abort) if -e $abort; rmdir($tempdir) or warn "Could not remove IPC temp dir ($tempdir)"; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::IPC::Driver::Files - Temp dir + Files concurrency model. =head1 DESCRIPTION This is the default, and fallback concurrency model for L. This sends events between processes and threads using serialized files in a temporary directory. This is not particularly fast, but it works everywhere. =head1 SYNOPSIS use Test2::IPC::Driver::Files; # IPC is now enabled =head1 ENVIRONMENT VARIABLES =over 4 =item T2_KEEP_TEMPDIR=0 When true, the tempdir used by the IPC driver will not be deleted when the test is done. =item T2_TEMPDIR_TEMPLATE='test2-XXXXXX' This can be used to set the template for the IPC temp dir. The template should follow template specifications from L. =back =head1 SEE ALSO See L for methods. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ûÂRyÖÖperl5/Test2/Event/Waiting.pmnuÏÃ6Ç$package Test2::Event::Waiting; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase; sub global { 1 }; sub summary { "IPC is waiting for children to finish..." } sub facet_data { my $self = shift; my $out = $self->common_facet_data; push @{$out->{info}} => { tag => 'INFO', debug => 0, details => $self->summary, }; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Waiting - Tell all procs/threads it is time to be done =head1 DESCRIPTION This event has no data of its own. This event is sent out by the IPC system when the main process/thread is ready to end. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ã#ûí  perl5/Test2/Event/Bail.pmnuÏÃ6Ç$package Test2::Event::Bail; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw{reason buffered}; # Make sure the tests terminate sub terminate { 255 }; sub global { 1 }; sub causes_fail { 1 } sub summary { my $self = shift; return "Bail out! " . $self->{+REASON} if $self->{+REASON}; return "Bail out!"; } sub diagnostics { 1 } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{control} = { global => 1, halt => 1, details => $self->{+REASON}, terminate => 255, }; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Bail - Bailout! =head1 DESCRIPTION The bailout event is generated when things go horribly wrong and you need to halt all testing in the current file. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Bail; my $ctx = context(); my $event = $ctx->bail('Stuff is broken'); =head1 METHODS Inherits from L. Also defines: =over 4 =item $reason = $e->reason The reason for the bailout. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!8Ìê½ééperl5/Test2/Event/Encoding.pmnuÏÃ6Ç$package Test2::Event::Encoding; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/croak/; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw/encoding/; sub init { my $self = shift; defined $self->{+ENCODING} or croak "'encoding' is a required attribute"; } sub summary { 'Encoding set to ' . $_[0]->{+ENCODING} } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{control}->{encoding} = $self->{+ENCODING}; $out->{about}->{details} = $self->summary; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Encoding - Set the encoding for the output stream =head1 DESCRIPTION The encoding event is generated when a test file wants to specify the encoding to be used when formatting its output. This event is intended to be produced by formatter classes and used for interpreting test names, message contents, etc. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Encoding; my $ctx = context(); my $event = $ctx->send_event('Encoding', encoding => 'UTF-8'); =head1 METHODS Inherits from L. Also defines: =over 4 =item $encoding = $e->encoding The encoding being specified. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!DÚ‘•õõperl5/Test2/Event/Exception.pmnuÏÃ6Ç$package Test2::Event::Exception; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw{error}; sub init { my $self = shift; $self->{+ERROR} = "$self->{+ERROR}"; } sub causes_fail { 1 } sub summary { my $self = shift; chomp(my $msg = "Exception: " . $self->{+ERROR}); return $msg; } sub diagnostics { 1 } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{errors} = [ { tag => 'ERROR', fail => 1, details => $self->{+ERROR}, } ]; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Exception - Exception event =head1 DESCRIPTION An exception event will display to STDERR, and will prevent the overall test file from passing. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Exception; my $ctx = context(); my $event = $ctx->send_event('Exception', error => 'Stuff is broken'); =head1 METHODS Inherits from L. Also defines: =over 4 =item $reason = $e->error The reason for the exception. =back =head1 CAVEATS Be aware that all exceptions are stringified during construction. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!H9½�perl5/Test2/Event/Generic.pmnuÏÃ6Ç$package Test2::Event::Generic; use strict; use warnings; use Carp qw/croak/; use Scalar::Util qw/reftype/; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase; my @FIELDS = qw{ causes_fail increments_count diagnostics no_display callback terminate global sets_plan summary facet_data }; my %DEFAULTS = ( causes_fail => 0, increments_count => 0, diagnostics => 0, no_display => 0, ); sub init { my $self = shift; for my $field (@FIELDS) { my $val = defined $self->{$field} ? delete $self->{$field} : $DEFAULTS{$field}; next unless defined $val; my $set = "set_$field"; $self->$set($val); } } for my $field (@FIELDS) { no strict 'refs'; *$field = sub { exists $_[0]->{$field} ? $_[0]->{$field} : () } unless exists &{$field}; *{"set_$field"} = sub { $_[0]->{$field} = $_[1] } unless exists &{"set_$field"}; } sub can { my $self = shift; my ($name) = @_; return $self->SUPER::can($name) unless $name eq 'callback'; return $self->{callback} || \&Test2::Event::callback; } sub facet_data { my $self = shift; return $self->{facet_data} || $self->SUPER::facet_data(); } sub summary { my $self = shift; return $self->{summary} if defined $self->{summary}; $self->SUPER::summary(); } sub sets_plan { my $self = shift; return unless $self->{sets_plan}; return @{$self->{sets_plan}}; } sub callback { my $self = shift; my $cb = $self->{callback} || return; $self->$cb(@_); } sub set_global { my $self = shift; my ($bool) = @_; if(!defined $bool) { delete $self->{global}; return undef; } $self->{global} = $bool; } sub set_callback { my $self = shift; my ($cb) = @_; if(!defined $cb) { delete $self->{callback}; return undef; } croak "callback must be a code reference" unless ref($cb) && reftype($cb) eq 'CODE'; $self->{callback} = $cb; } sub set_terminate { my $self = shift; my ($exit) = @_; if(!defined $exit) { delete $self->{terminate}; return undef; } croak "terminate must be a positive integer" unless $exit =~ m/^\d+$/; $self->{terminate} = $exit; } sub set_sets_plan { my $self = shift; my ($plan) = @_; if(!defined $plan) { delete $self->{sets_plan}; return undef; } croak "'sets_plan' must be an array reference" unless ref($plan) && reftype($plan) eq 'ARRAY'; $self->{sets_plan} = $plan; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Generic - Generic event type. =head1 DESCRIPTION This is a generic event that lets you customize all fields in the event API. This is useful if you have need for a custom event that does not make sense as a published reusable event subclass. =head1 SYNOPSIS use Test2::API qw/context/; sub send_custom_fail { my $ctx = shift; $ctx->send_event('Generic', causes_fail => 1, summary => 'The sky is falling'); $ctx->release; } send_custom_fail(); =head1 METHODS =over 4 =item $e->facet_data($data) =item $data = $e->facet_data Get or set the facet data (see L). If no facet_data is set then C<< Test2::Event->facet_data >> will be called to produce facets from the other data. =item $e->callback($hub) Call the custom callback if one is set, otherwise this does nothing. =item $e->set_callback(sub { ... }) Set the custom callback. The custom callback must be a coderef. The first argument to your callback will be the event itself, the second will be the L that is using the callback. =item $bool = $e->causes_fail =item $e->set_causes_fail($bool) Get/Set the C attribute. This defaults to C<0>. =item $bool = $e->diagnostics =item $e->set_diagnostics($bool) Get/Set the C attribute. This defaults to C<0>. =item $bool_or_undef = $e->global =item @bool_or_empty = $e->global =item $e->set_global($bool_or_undef) Get/Set the C attribute. This defaults to an empty list which is undef in scalar context. =item $bool = $e->increments_count =item $e->set_increments_count($bool) Get/Set the C attribute. This defaults to C<0>. =item $bool = $e->no_display =item $e->set_no_display($bool) Get/Set the C attribute. This defaults to C<0>. =item @plan = $e->sets_plan Get the plan if this event sets one. The plan is a list of up to 3 items: C<($count, $directive, $reason)>. C<$count> must be defined, the others may be undef, or may not exist at all. =item $e->set_sets_plan(\@plan) Set the plan. You must pass in an arrayref with up to 3 elements. =item $summary = $e->summary =item $e->set_summary($summary_or_undef) Get/Set the summary. This will default to the event package C<'Test2::Event::Generic'>. You can set it to any value. Setting this to C will reset it to the default. =item $int_or_undef = $e->terminate =item @int_or_empty = $e->terminate =item $e->set_terminate($int_or_undef) This will get/set the C attribute. This defaults to undef in scalar context, or an empty list in list context. Setting this to undef will clear it completely. This must be set to a positive integer (0 or larger). =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!v]_ò< < perl5/Test2/Event/Plan.pmnuÏÃ6Ç$package Test2::Event::Plan; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw{max directive reason}; use Carp qw/confess/; my %ALLOWED = ( 'SKIP' => 1, 'NO PLAN' => 1, ); sub init { if ($_[0]->{+DIRECTIVE}) { $_[0]->{+DIRECTIVE} = 'SKIP' if $_[0]->{+DIRECTIVE} eq 'skip_all'; $_[0]->{+DIRECTIVE} = 'NO PLAN' if $_[0]->{+DIRECTIVE} eq 'no_plan'; confess "'" . $_[0]->{+DIRECTIVE} . "' is not a valid plan directive" unless $ALLOWED{$_[0]->{+DIRECTIVE}}; } else { confess "Cannot have a reason without a directive!" if defined $_[0]->{+REASON}; confess "No number of tests specified" unless defined $_[0]->{+MAX}; confess "Plan test count '" . $_[0]->{+MAX} . "' does not appear to be a valid positive integer" unless $_[0]->{+MAX} =~ m/^\d+$/; $_[0]->{+DIRECTIVE} = ''; } } sub sets_plan { my $self = shift; return ( $self->{+MAX}, $self->{+DIRECTIVE}, $self->{+REASON}, ); } sub terminate { my $self = shift; # On skip_all we want to terminate the hub return 0 if $self->{+DIRECTIVE} && $self->{+DIRECTIVE} eq 'SKIP'; return undef; } sub summary { my $self = shift; my $max = $self->{+MAX}; my $directive = $self->{+DIRECTIVE}; my $reason = $self->{+REASON}; return "Plan is $max assertions" if $max || !$directive; return "Plan is '$directive', $reason" if $reason; return "Plan is '$directive'"; } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{control}->{terminate} = $self->{+DIRECTIVE} eq 'SKIP' ? 0 : undef unless defined $out->{control}->{terminate}; $out->{plan} = {count => $self->{+MAX}}; $out->{plan}->{details} = $self->{+REASON} if defined $self->{+REASON}; if (my $dir = $self->{+DIRECTIVE}) { $out->{plan}->{skip} = 1 if $dir eq 'SKIP'; $out->{plan}->{none} = 1 if $dir eq 'NO PLAN'; } return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Plan - The event of a plan =head1 DESCRIPTION Plan events are fired off whenever a plan is declared, done testing is called, or a subtext completes. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Plan; my $ctx = context(); # Plan for 10 tests to run my $event = $ctx->plan(10); # Plan to skip all tests (will exit 0) $ctx->plan(0, skip_all => "These tests need to be skipped"); =head1 ACCESSORS =over 4 =item $num = $plan->max Get the number of expected tests =item $dir = $plan->directive Get the directive (such as TODO, skip_all, or no_plan). =item $reason = $plan->reason Get the reason for the directive. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!+ÔÊ~ÚÚperl5/Test2/Event/Skip.pmnuÏÃ6Ç$package Test2::Event::Skip; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event::Ok; our @ISA = qw(Test2::Event::Ok) } use Test2::Util::HashBase qw{reason}; sub init { my $self = shift; $self->SUPER::init; $self->{+EFFECTIVE_PASS} = 1; } sub causes_fail { 0 } sub summary { my $self = shift; my $out = $self->SUPER::summary(@_); if (my $reason = $self->reason) { $out .= " (SKIP: $reason)"; } else { $out .= " (SKIP)"; } return $out; } sub extra_amnesty { my $self = shift; my @out; push @out => { tag => 'TODO', details => $self->{+TODO}, } if defined $self->{+TODO}; push @out => { tag => 'skip', details => $self->{+REASON}, inherited => 0, }; return @out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Skip - Skip event type =head1 DESCRIPTION Skip events bump test counts just like L events, but they can never fail. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Skip; my $ctx = context(); my $event = $ctx->skip($name, $reason); or: my $ctx = context(); my $event = $ctx->send_event( 'Skip', name => $name, reason => $reason, ); =head1 ACCESSORS =over 4 =item $reason = $e->reason The original true/false value of whatever was passed into the event (but reduced down to 1 or 0). =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!õòãUŽŽperl5/Test2/Event/Pass.pmnuÏÃ6Ç$package Test2::Event::Pass; use strict; use warnings; our $VERSION = '1.302183'; use Test2::EventFacet::Info; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event); *META_KEY = \&Test2::Util::ExternalMeta::META_KEY; } use Test2::Util::HashBase qw{ -name -info }; ############## # Old API sub summary { "pass" } sub increments_count { 1 } sub causes_fail { 0 } sub diagnostics { 0 } sub no_display { 0 } sub subtest_id { undef } sub terminate { () } sub global { () } sub sets_plan { () } ############## # New API sub add_info { my $self = shift; for my $in (@_) { $in = {%$in} if ref($in) ne 'ARRAY'; $in = Test2::EventFacet::Info->new($in); push @{$self->{+INFO}} => $in; } } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{about}->{details} = 'pass'; $out->{assert} = {pass => 1, details => $self->{+NAME}}; $out->{info} = [map {{ %{$_} }} @{$self->{+INFO}}] if $self->{+INFO}; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Pass - Event for a simple passing assertion =head1 DESCRIPTION This is an optimal representation of a passing assertion. =head1 SYNOPSIS use Test2::API qw/context/; sub pass { my ($name) = @_; my $ctx = context(); $ctx->pass($name); $ctx->release; } =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!€ÏÿLll perl5/Test2/Event/TAP/Version.pmnuÏÃ6Ç$package Test2::Event::TAP::Version; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/croak/; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw/version/; sub init { my $self = shift; defined $self->{+VERSION} or croak "'version' is a required attribute"; } sub summary { 'TAP version ' . $_[0]->{+VERSION} } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{about}->{details} = $self->summary; push @{$out->{info}} => { tag => 'INFO', debug => 0, details => $self->summary, }; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::TAP::Version - Event for TAP version. =head1 DESCRIPTION This event is used if a TAP formatter wishes to set a version. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Encoding; my $ctx = context(); my $event = $ctx->send_event('TAP::Version', version => 42); =head1 METHODS Inherits from L. Also defines: =over 4 =item $version = $e->version The TAP version being parsed. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!QAx¯¯perl5/Test2/Event/Diag.pmnuÏÃ6Ç$package Test2::Event::Diag; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw/message/; sub init { $_[0]->{+MESSAGE} = 'undef' unless defined $_[0]->{+MESSAGE}; } sub summary { $_[0]->{+MESSAGE} } sub diagnostics { 1 } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{info} = [ { tag => 'DIAG', debug => 1, details => $self->{+MESSAGE}, } ]; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Diag - Diag event type =head1 DESCRIPTION Diagnostics messages, typically rendered to STDERR. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Diag; my $ctx = context(); my $event = $ctx->diag($message); =head1 ACCESSORS =over 4 =item $diag->message The message for the diag. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK![›¾èââperl5/Test2/Event/Fail.pmnuÏÃ6Ç$package Test2::Event::Fail; use strict; use warnings; our $VERSION = '1.302183'; use Test2::EventFacet::Info; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event); *META_KEY = \&Test2::Util::ExternalMeta::META_KEY; } use Test2::Util::HashBase qw{ -name -info }; ############# # Old API sub summary { "fail" } sub increments_count { 1 } sub diagnostics { 0 } sub no_display { 0 } sub subtest_id { undef } sub terminate { () } sub global { () } sub sets_plan { () } sub causes_fail { my $self = shift; return 0 if $self->{+AMNESTY} && @{$self->{+AMNESTY}}; return 1; } ############# # New API sub add_info { my $self = shift; for my $in (@_) { $in = {%$in} if ref($in) ne 'ARRAY'; $in = Test2::EventFacet::Info->new($in); push @{$self->{+INFO}} => $in; } } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{about}->{details} = 'fail'; $out->{assert} = {pass => 0, details => $self->{+NAME}}; $out->{info} = [map {{ %{$_} }} @{$self->{+INFO}}] if $self->{+INFO}; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Fail - Event for a simple failed assertion =head1 DESCRIPTION This is an optimal representation of a failed assertion. =head1 SYNOPSIS use Test2::API qw/context/; sub fail { my ($name) = @_; my $ctx = context(); $ctx->fail($name); $ctx->release; } =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!¾óŽÛ} } perl5/Test2/Event/Subtest.pmnuÏÃ6Ç$package Test2::Event::Subtest; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event::Ok; our @ISA = qw(Test2::Event::Ok) } use Test2::Util::HashBase qw{subevents buffered subtest_id subtest_uuid}; sub init { my $self = shift; $self->SUPER::init(); $self->{+SUBEVENTS} ||= []; if ($self->{+EFFECTIVE_PASS}) { $_->set_effective_pass(1) for grep { $_->can('effective_pass') } @{$self->{+SUBEVENTS}}; } } { no warnings 'redefine'; sub set_subevents { my $self = shift; my @subevents = @_; if ($self->{+EFFECTIVE_PASS}) { $_->set_effective_pass(1) for grep { $_->can('effective_pass') } @subevents; } $self->{+SUBEVENTS} = \@subevents; } sub set_effective_pass { my $self = shift; my ($pass) = @_; if ($pass) { $_->set_effective_pass(1) for grep { $_->can('effective_pass') } @{$self->{+SUBEVENTS}}; } elsif ($self->{+EFFECTIVE_PASS} && !$pass) { for my $s (grep { $_->can('effective_pass') } @{$self->{+SUBEVENTS}}) { $_->set_effective_pass(0) unless $s->can('todo') && defined $s->todo; } } $self->{+EFFECTIVE_PASS} = $pass; } } sub summary { my $self = shift; my $name = $self->{+NAME} || "Nameless Subtest"; my $todo = $self->{+TODO}; if ($todo) { $name .= " (TODO: $todo)"; } elsif (defined $todo) { $name .= " (TODO)"; } return $name; } sub facet_data { my $self = shift; my $out = $self->SUPER::facet_data(); $out->{parent} = { hid => $self->subtest_id, children => [map {$_->facet_data} @{$self->{+SUBEVENTS}}], buffered => $self->{+BUFFERED}, }; return $out; } sub add_amnesty { my $self = shift; for my $am (@_) { $am = {%$am} if ref($am) ne 'ARRAY'; $am = Test2::EventFacet::Amnesty->new($am); push @{$self->{+AMNESTY}} => $am; for my $e (@{$self->{+SUBEVENTS}}) { $e->add_amnesty($am->clone(inherited => 1)); } } } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Subtest - Event for subtest types =head1 DESCRIPTION This class represents a subtest. This class is a subclass of L. =head1 ACCESSORS This class inherits from L. =over 4 =item $arrayref = $e->subevents Returns the arrayref containing all the events from the subtest =item $bool = $e->buffered True if the subtest is buffered, that is all subevents render at once. If this is false it means all subevents render as they are produced. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!7øډ‰perl5/Test2/Event/Note.pmnuÏÃ6Ç$package Test2::Event::Note; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw/message/; sub init { $_[0]->{+MESSAGE} = 'undef' unless defined $_[0]->{+MESSAGE}; } sub summary { $_[0]->{+MESSAGE} } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{info} = [ { tag => 'NOTE', debug => 0, details => $self->{+MESSAGE}, } ]; return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Note - Note event type =head1 DESCRIPTION Notes, typically rendered to STDOUT. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Note; my $ctx = context(); my $event = $ctx->Note($message); =head1 ACCESSORS =over 4 =item $note->message The message for the note. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!p…iûZ Z perl5/Test2/Event/Ok.pmnuÏÃ6Ç$package Test2::Event::Ok; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::HashBase qw{ pass effective_pass name todo }; sub init { my $self = shift; # Do not store objects here, only true or false $self->{+PASS} = $self->{+PASS} ? 1 : 0; $self->{+EFFECTIVE_PASS} = $self->{+PASS} || (defined($self->{+TODO}) ? 1 : 0); } { no warnings 'redefine'; sub set_todo { my $self = shift; my ($todo) = @_; $self->{+TODO} = $todo; $self->{+EFFECTIVE_PASS} = defined($todo) ? 1 : $self->{+PASS}; } } sub increments_count { 1 }; sub causes_fail { !$_[0]->{+EFFECTIVE_PASS} } sub summary { my $self = shift; my $name = $self->{+NAME} || "Nameless Assertion"; my $todo = $self->{+TODO}; if ($todo) { $name .= " (TODO: $todo)"; } elsif (defined $todo) { $name .= " (TODO)" } return $name; } sub extra_amnesty { my $self = shift; return unless defined($self->{+TODO}) || ($self->{+EFFECTIVE_PASS} && !$self->{+PASS}); return { tag => 'TODO', details => $self->{+TODO}, }; } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{assert} = { no_debug => 1, # Legacy behavior pass => $self->{+PASS}, details => $self->{+NAME}, }; if (my @exra_amnesty = $self->extra_amnesty) { my %seen; # It is possible the extra amnesty can be a duplicate, so filter it. $out->{amnesty} = [ grep { !$seen{defined($_->{tag}) ? $_->{tag} : ''}->{defined($_->{details}) ? $_->{details} : ''}++ } @exra_amnesty, @{$out->{amnesty}}, ]; } return $out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::Ok - Ok event type =head1 DESCRIPTION Ok events are generated whenever you run a test that produces a result. Examples are C, and C. =head1 SYNOPSIS use Test2::API qw/context/; use Test2::Event::Ok; my $ctx = context(); my $event = $ctx->ok($bool, $name, \@diag); or: my $ctx = context(); my $event = $ctx->send_event( 'Ok', pass => $bool, name => $name, ); =head1 ACCESSORS =over 4 =item $rb = $e->pass The original true/false value of whatever was passed into the event (but reduced down to 1 or 0). =item $name = $e->name Name of the test. =item $b = $e->effective_pass This is the true/false value of the test after TODO and similar modifiers are taken into account. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ÑðàH++perl5/Test2/Event/V2.pmnuÏÃ6Ç$package Test2::Event::V2; use strict; use warnings; our $VERSION = '1.302183'; use Scalar::Util qw/reftype/; use Carp qw/croak/; BEGIN { require Test2::Event; our @ISA = qw(Test2::Event) } use Test2::Util::Facets2Legacy qw{ causes_fail diagnostics global increments_count no_display sets_plan subtest_id summary terminate }; use Test2::Util::HashBase qw/-about/; sub non_facet_keys { return ( +UUID, Test2::Util::ExternalMeta::META_KEY(), ); } sub init { my $self = shift; my $uuid; if ($uuid = $self->{+UUID}) { croak "uuid '$uuid' passed to constructor, but uuid '$self->{+ABOUT}->{uuid}' is already set in the 'about' facet" if $self->{+ABOUT}->{uuid} && $self->{+ABOUT}->{uuid} ne $uuid; $self->{+ABOUT}->{uuid} = $uuid; } elsif ($self->{+ABOUT} && $self->{+ABOUT}->{uuid}) { $uuid = $self->{+ABOUT}->{uuid}; $self->SUPER::set_uuid($uuid); } # Clone the trace, make sure it is blessed if (my $trace = $self->{+TRACE}) { $self->{+TRACE} = Test2::EventFacet::Trace->new(%$trace); } } sub set_uuid { my $self = shift; my ($uuid) = @_; $self->{+ABOUT}->{uuid} = $uuid; $self->SUPER::set_uuid($uuid); } sub facet_data { my $self = shift; my $f = { %{$self} }; delete $f->{$_} for $self->non_facet_keys; my %out; for my $k (keys %$f) { next if substr($k, 0, 1) eq '_'; my $data = $f->{$k} or next; # Key is there, but no facet my $is_list = 'ARRAY' eq (reftype($data) || ''); $out{$k} = $is_list ? [ map { {%{$_}} } @$data ] : {%$data}; } if (my $meta = $self->meta_facet_data) { $out{meta} = {%$meta, %{$out{meta} || {}}}; } return \%out; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event::V2 - Second generation event. =head1 DESCRIPTION This is the event type that should be used instead of L or its legacy subclasses. =head1 SYNOPSIS =head2 USING A CONTEXT use Test2::API qw/context/; sub my_tool { my $ctx = context(); my $event = $ctx->send_ev2(info => [{tag => 'NOTE', details => "This is a note"}]); $ctx->release; return $event; } =head2 USING THE CONSTRUCTOR use Test2::Event::V2; my $e = Test2::Event::V2->new( trace => {frame => [$PKG, $FILE, $LINE, $SUBNAME]}, info => [{tag => 'NOTE', details => "This is a note"}], ); =head1 METHODS This class inherits from L. =over 4 =item $fd = $e->facet_data() This will return a hashref of facet data. Each facet hash will be a shallow copy of the original. =item $about = $e->about() This will return the 'about' facet hashref. B This will return the internal hashref, not a copy. =item $trace = $e->trace() This will return the 'trace' facet, normally blessed (but this is not enforced when the trace is set using C. B This will return the internal trace, not a copy. =back =head2 MUTATION =over 4 =item $e->add_amnesty({...}) Inherited from L. This can be used to add 'amnesty' facets to an existing event. Each new item is added to the B of the list. B Items B blessed when added. =item $e->add_hub({...}) Inherited from L. This is used by hubs to stamp events as they pass through. New items are added to the B of the list. B Items B blessed when added. =item $e->set_uuid($UUID) Inherited from L, overridden to also vivify/mutate the 'about' facet. =item $e->set_trace($trace) Inherited from L which allows you to change the trace. B This method does not bless/clone the trace for you. Many things will expect the trace to be blessed, so you should probably do that. =back =head2 LEGACY SUPPORT METHODS These are all imported from L, see that module or L for documentation on what they do. =over 4 =item causes_fail =item diagnostics =item global =item increments_count =item no_display =item sets_plan =item subtest_id =item summary =item terminate =back =head1 THIRD PARTY META-DATA This object consumes L which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!¥?0qÖÖperl5/Test2/EventFacet.pmnuÏÃ6Ç$package Test2::EventFacet; use strict; use warnings; our $VERSION = '1.302183'; use Test2::Util::HashBase qw/-details/; use Carp qw/croak/; my $SUBLEN = length(__PACKAGE__ . '::'); sub facet_key { my $key = ref($_[0]) || $_[0]; substr($key, 0, $SUBLEN, ''); return lc($key); } sub is_list { 0 } sub clone { my $self = shift; my $type = ref($self); return bless {%$self, @_}, $type; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet - Base class for all event facets. =head1 DESCRIPTION Base class for all event facets. =head1 METHODS =over 4 =item $key = $facet_class->facet_key() This will return the key for the facet in the facet data hash. =item $bool = $facet_class->is_list() This will return true if the facet should be in a list instead of a single item. =item $clone = $facet->clone() =item $clone = $facet->clone(%replace) This will make a shallow clone of the facet. You may specify fields to override as arguments. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!åE”صµperl5/Test2/EventFacet/Trace.pmnuÏÃ6Ç$package Test2::EventFacet::Trace; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util qw/get_tid pkg_to_file gen_uid/; use Carp qw/confess/; use Test2::Util::HashBase qw{^frame ^pid ^tid ^cid -hid -nested details -buffered -uuid -huuid {+FRAME}; $_[0]->{+DETAILS} = delete $_[0]->{detail} if $_[0]->{detail}; unless (defined($_[0]->{+PID}) || defined($_[0]->{+TID}) || defined($_[0]->{+CID})) { $_[0]->{+PID} = $$ unless defined $_[0]->{+PID}; $_[0]->{+TID} = get_tid() unless defined $_[0]->{+TID}; } } sub snapshot { my ($orig, @override) = @_; bless {%$orig, @override}, __PACKAGE__; } sub signature { my $self = shift; # Signature is only valid if all of these fields are defined, there is no # signature if any is missing. '0' is ok, but '' is not. return join ':' => map { (defined($_) && length($_)) ? $_ : return undef } ( $self->{+CID}, $self->{+PID}, $self->{+TID}, $self->{+FRAME}->[1], $self->{+FRAME}->[2], ); } sub debug { my $self = shift; return $self->{+DETAILS} if $self->{+DETAILS}; my ($pkg, $file, $line) = $self->call; return "at $file line $line"; } sub alert { my $self = shift; my ($msg) = @_; warn $msg . ' ' . $self->debug . ".\n"; } sub throw { my $self = shift; my ($msg) = @_; die $msg . ' ' . $self->debug . ".\n"; } sub call { @{$_[0]->{+FRAME}} } sub full_call { @{$_[0]->{+FULL_CALLER}} } sub package { $_[0]->{+FRAME}->[0] } sub file { $_[0]->{+FRAME}->[1] } sub line { $_[0]->{+FRAME}->[2] } sub subname { $_[0]->{+FRAME}->[3] } sub warning_bits { $_[0]->{+FULL_CALLER} ? $_[0]->{+FULL_CALLER}->[9] : undef } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Trace - Debug information for events =head1 DESCRIPTION The L object, as well as all L types need to have access to information about where they were created. This object represents that information. =head1 SYNOPSIS use Test2::EventFacet::Trace; my $trace = Test2::EventFacet::Trace->new( frame => [$package, $file, $line, $subname], ); =head1 FACET FIELDS =over 4 =item $string = $trace->{details} =item $string = $trace->details() Used as a custom trace message that will be used INSTEAD of C<< at line >> when calling C<< $trace->debug >>. =item $frame = $trace->{frame} =item $frame = $trace->frame() Get the call frame arrayref. [$package, $file, $line, $subname] =item $int = $trace->{pid} =item $int = $trace->pid() The process ID in which the event was generated. =item $int = $trace->{tid} =item $int = $trace->tid() The thread ID in which the event was generated. =item $id = $trace->{cid} =item $id = $trace->cid() The ID of the context that was used to create the event. =item $uuid = $trace->{uuid} =item $uuid = $trace->uuid() The UUID of the context that was used to create the event. (If uuid tagging was enabled) =item ($pkg, $file, $line, $subname) = $trace->call Get the basic call info as a list. =item @caller = $trace->full_call Get the full caller(N) results. =item $warning_bits = $trace->warning_bits Get index 9 from the full caller info. This is the warnings_bits field. The value of this is not portable across perl versions or even processes. However it can be used in the process that generated it to reproduce the warnings settings in a new scope. eval <warning_bits }; ... context's warning settings apply here ... EOT =back =head2 DISCOURAGED HUB RELATED FIELDS These fields were not always set properly by tools. These are B deprecated by the L facets. These fields are not required, and may only reflect the hub that was current when the event was created, which is not necessarily the same as the hub the event was sent through. Some tools did do a good job setting these to the correct hub, but you cannot always rely on that. Use the 'hubs' facet list instead. =over 4 =item $hid = $trace->{hid} =item $hid = $trace->hid() The ID of the hub that was current when the event was created. =item $huuid = $trace->{huuid} =item $huuid = $trace->huuid() The UUID of the hub that was current when the event was created. (If uuid tagging was enabled). =item $int = $trace->{nested} =item $int = $trace->nested() How deeply nested the event is. =item $bool = $trace->{buffered} =item $bool = $trace->buffered() True if the event was buffered and not sent to the formatter independent of a parent (This should never be set when nested is C<0> or C). =back =head1 METHODS B All facet frames are also methods. =over 4 =item $trace->set_detail($msg) =item $msg = $trace->detail Used to get/set a custom trace message that will be used INSTEAD of C<< at line >> when calling C<< $trace->debug >>. C is an alias to the C
facet field for backwards compatibility. =item $str = $trace->debug Typically returns the string C<< at line >>. If C is set then its value will be returned instead. =item $trace->alert($MESSAGE) This issues a warning at the frame (filename and line number where errors should be reported). =item $trace->throw($MESSAGE) This throws an exception at the frame (filename and line number where errors should be reported). =item ($package, $file, $line, $subname) = $trace->call() Get the caller details for the debug-info. This is where errors should be reported. =item $pkg = $trace->package Get the debug-info package. =item $file = $trace->file Get the debug-info filename. =item $line = $trace->line Get the debug-info line number. =item $subname = $trace->subname Get the debug-info subroutine name. =item $sig = trace->signature Get a signature string that identifies this trace. This is used to check if multiple events are related. The signature includes pid, tid, file, line number, and the cid. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!:vO”' ' $perl5/Test2/EventFacet/Info/Table.pmnuÏÃ6Ç$package Test2::EventFacet::Info::Table; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/confess/; use Test2::Util::HashBase qw{-header -rows -collapse -no_collapse -as_string}; sub init { my $self = shift; confess "Table may not be empty" unless ref($self->{+ROWS}) eq 'ARRAY' && @{$self->{+ROWS}}; $self->{+AS_STRING} ||= ''; } sub as_hash { my $out = +{%{$_[0]}}; delete $out->{as_string}; $out } sub info_args { my $self = shift; my $hash = $self->as_hash; my $desc = $self->as_string; return (table => $hash, details => $desc); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Info::Table - Intermediary representation of a table. =head1 DESCRIPTION Intermediary representation of a table for use in specialized L methods which generate L facets. =head1 SYNOPSIS use Test2::EventFacet::Info::Table; use Test2::API qw/context/; sub my_tool { my $ctx = context(); ... $ctx->fail( $name, "failure diag message", Test2::EventFacet::Info::Table->new( # Required rows => [['a', 'b'], ['c', 'd'], ...], # Strongly Recommended as_string => "... string to print when table cannot be rendered ...", # Optional header => ['col1', 'col2'], collapse => $bool, no_collapse => ['col1', ...], ), ); ... $ctx->release; } my_tool(); =head1 ATTRIBUTES =over 4 =item $header_aref = $t->header() =item $rows_aref = $t->rows() =item $bool = $t->collapse() =item $aref = $t->no_collapse() The above are all directly tied to the table hashref structure described in L. =item $str = $t->as_string() This returns the string form of the table if it was set, otherwise it returns the string C<< "
" >>. =item $href = $t->as_hash() This returns the data structure used for tables by L. =item %args = $t->info_args() This returns the arguments that should be used to construct the proper L structure. return (table => $t->as_hash(), details => $t->as_string()); =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!JF…  perl5/Test2/EventFacet/Error.pmnuÏÃ6Ç$package Test2::EventFacet::Error; use strict; use warnings; our $VERSION = '1.302183'; sub facet_key { 'errors' } sub is_list { 1 } BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -tag -fail }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Error - Facet for errors that need to be shown. =head1 DESCRIPTION This facet is used when an event needs to convey errors. =head1 NOTES This facet has the hash key C<'errors'>, and is a list of facets instead of a single item. =head1 FIELDS =over 4 =item $string = $error->{details} =item $string = $error->details() Explanation of the error, or the error itself (such as an exception). In perl exceptions may be blessed objects, so this field may contain a blessed object. =item $short_string = $error->{tag} =item $short_string = $error->tag() Short tag to categorize the error. This is usually 10 characters or less, formatters may truncate longer tags. =item $bool = $error->{fail} =item $bool = $error->fail() Not all errors are fatal, some are displayed having already been handled. Set this to true if you want the error to cause the test to fail. Without this the error is simply a diagnostics message that has no effect on the overall pass/fail result. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!® ü^^perl5/Test2/EventFacet/Plan.pmnuÏÃ6Ç$package Test2::EventFacet::Plan; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -count -skip -none }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Plan - Facet for setting the plan =head1 DESCRIPTION Events use this facet when they need to set the plan. =head1 FIELDS =over 4 =item $string = $plan->{details} =item $string = $plan->details() Human readable explanation for the plan being set. This is normally not rendered by most formatters except when the C field is also set. =item $positive_int = $plan->{count} =item $positive_int = $plan->count() Set the number of expected assertions. This should usually be set to C<0> when C or C are also set. =item $bool = $plan->{skip} =item $bool = $plan->skip() When true the entire test should be skipped. This is usually paired with an explanation in the C
field, and a C facet that has C set to C<0>. =item $bool = $plan->{none} =item $bool = $plan->none() This is mainly used by legacy L tests which set the plan to C, a construct that predates the much better C. If you are using this in non-legacy code you may need to reconsider the course of your life, maybe a hermitage would suite you? =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!üO9hÿÿ perl5/Test2/EventFacet/Render.pmnuÏÃ6Ç$package Test2::EventFacet::Render; use strict; use warnings; our $VERSION = '1.302183'; sub is_list { 1 } BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -tag -facet -mode }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Render - Facet that dictates how to render an event. =head1 DESCRIPTION This facet is used to dictate how the event should be rendered by the standard test2 rendering tools. If this facet is present then ONLY what is specified by it will be rendered. It is assumed that anything important or note-worthy will be present here, no other facets will be considered for rendering/display. This facet is a list type, you can add as many items as needed. =head1 FIELDS =over 4 =item $string = $render->[#]->{details} =item $string = $render->[#]->details() Human readable text for display. =item $string = $render->[#]->{tag} =item $string = $render->[#]->tag() Tag that should prefix/identify the main text. =item $string = $render->[#]->{facet} =item $string = $render->[#]->facet() Optional, if the display text was generated from another facet this should state what facet it was. =item $mode = $render->[#]->{mode} =item $mode = $render->[#]->mode() =over 4 =item calculated Calculated means the facet was generated from another facet. Calculated facets may be cleared and regenerated whenever the event state changes. =item replace Replace means the facet is intended to replace the normal rendering of the event. =back =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!~$òÂFFperl5/Test2/EventFacet/Meta.pmnuÏÃ6Ç$package Test2::EventFacet::Meta; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use vars qw/$AUTOLOAD/; # replace set_details { no warnings 'redefine'; sub set_details { $_[0]->{'set_details'} } } sub can { my $self = shift; my ($name) = @_; my $existing = $self->SUPER::can($name); return $existing if $existing; # Only vivify when called on an instance, do not vivify for a class. There # are a lot of magic class methods used in things like serialization (or # the forks.pm module) which cause problems when vivified. return undef unless ref($self); my $sub = sub { $_[0]->{$name} }; { no strict 'refs'; *$name = $sub; } return $sub; } sub AUTOLOAD { my $name = $AUTOLOAD; $name =~ s/^.*:://g; my $sub = $_[0]->can($name); goto &$sub; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Meta - Facet for meta-data =head1 DESCRIPTION This facet can contain any random meta-data that has been attached to the event. =head1 METHODS AND FIELDS Any/all fields and accessors are autovivified into existence. There is no way to know what metadata may be added, so any is allowed. =over 4 =item $anything = $meta->{anything} =item $anything = $meta->anything() =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!»DÞOÌÌperl5/Test2/EventFacet/About.pmnuÏÃ6Ç$package Test2::EventFacet::About; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -package -no_display -uuid -eid }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::About - Facet with event details. =head1 DESCRIPTION This facet has information about the event, such as event package. =head1 FIELDS =over 4 =item $string = $about->{details} =item $string = $about->details() Summary about the event. =item $package = $about->{package} =item $package = $about->package() Event package name. =item $bool = $about->{no_display} =item $bool = $about->no_display() True if the event should be skipped by formatters. =item $uuid = $about->{uuid} =item $uuid = $about->uuid() Will be set to a uuid if uuid tagging was enabled. =item $uuid = $about->{eid} =item $uuid = $about->eid() A unique (for the test job) identifier for the event. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!19¥ 6 6 perl5/Test2/EventFacet/Info.pmnuÏÃ6Ç$package Test2::EventFacet::Info; use strict; use warnings; our $VERSION = '1.302183'; sub is_list { 1 } BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{-tag -debug -important -table}; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Info - Facet for information a developer might care about. =head1 DESCRIPTION This facet represents messages intended for humans that will help them either understand a result, or diagnose a failure. =head1 NOTES This facet appears in a list instead of being a single item. =head1 FIELDS =over 4 =item $string_or_structure = $info->{details} =item $string_or_structure = $info->details() Human readable string or data structure, this is the information to display. Formatters are free to render the structures however they please. This may contain a blessed object. If the C
attribute (see below) is set then a renderer may choose to display the table instead of the details. =item $structure = $info->{table} =item $structure = $info->table() If the data the C facet needs to convey can be represented as a table then the data may be placed in this attribute in a more raw form for better display. The data must also be represented in the C
attribute for renderers which do not support rendering tables directly. The table structure: my %table = { header => [ 'column 1 header', 'column 2 header', ... ], # Optional rows => [ ['row 1 column 1', 'row 1, column 2', ... ], ['row 2 column 1', 'row 2, column 2', ... ], ... ], # Allow the renderer to hide empty columns when true, Optional collapse => $BOOL, # List by name or number columns that should never be collapsed no_collapse => \@LIST, } =item $short_string = $info->{tag} =item $short_string = $info->tag() Short tag to categorize the info. This is usually 10 characters or less, formatters may truncate longer tags. =item $bool = $info->{debug} =item $bool = $info->debug() Set this to true if the message is critical, or explains a failure. This is info that should be displayed by formatters even in less-verbose modes. When false the information is not considered critical and may not be rendered in less-verbose modes. =item $bool = $info->{important} =item $bool = $info->important This should be set for non debug messages that are still important enough to show when a formatter is in quiet mode. A formatter should send these to STDOUT not STDERR, but should show them even in non-verbose mode. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!›&¼£ØØ!perl5/Test2/EventFacet/Control.pmnuÏÃ6Ç$package Test2::EventFacet::Control; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -global -terminate -halt -has_callback -encoding -phase }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Control - Facet for hub actions and behaviors. =head1 DESCRIPTION This facet is used when the event needs to give instructions to the Test2 internals. =head1 FIELDS =over 4 =item $string = $control->{details} =item $string = $control->details() Human readable explanation for the special behavior. =item $bool = $control->{global} =item $bool = $control->global() True if the event is global in nature and should be seen by all hubs. =item $exit = $control->{terminate} =item $exit = $control->terminate() Defined if the test should immediately exit, the value is the exit code and may be C<0>. =item $bool = $control->{halt} =item $bool = $control->halt() True if all testing should be halted immediately. =item $bool = $control->{has_callback} =item $bool = $control->has_callback() True if the C method on the event should be called. =item $encoding = $control->{encoding} =item $encoding = $control->encoding() This can be used to change the encoding from this event onward. =item $phase = $control->{phase} =item $phase = $control->phase() Used to signal that a phase change has occurred. Currently only the perl END phase is signaled. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!,±ÆUUperl5/Test2/EventFacet/Hub.pmnuÏÃ6Ç$package Test2::EventFacet::Hub; use strict; use warnings; our $VERSION = '1.302183'; sub is_list { 1 } sub facet_key { 'hubs' } BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{-pid -tid -hid -nested -buffered -uuid -ipc}; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Hub - Facet for the hubs an event passes through. =head1 DESCRIPTION These are a record of the hubs an event passes through. Most recent hub is the first one in the list. =head1 FACET FIELDS =over 4 =item $string = $trace->{details} =item $string = $trace->details() The hub class or subclass =item $int = $trace->{pid} =item $int = $trace->pid() PID of the hub this event was sent to. =item $int = $trace->{tid} =item $int = $trace->tid() The thread ID of the hub the event was sent to. =item $hid = $trace->{hid} =item $hid = $trace->hid() The ID of the hub that the event was send to. =item $huuid = $trace->{huuid} =item $huuid = $trace->huuid() The UUID of the hub that the event was sent to. =item $int = $trace->{nested} =item $int = $trace->nested() How deeply nested the hub was. =item $bool = $trace->{buffered} =item $bool = $trace->buffered() True if the event was buffered and not sent to the formatter independent of a parent (This should never be set when nested is C<0> or C). =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!n�*°° perl5/Test2/EventFacet/Assert.pmnuÏÃ6Ç$package Test2::EventFacet::Assert; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -pass -no_debug -number }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Assert - Facet representing an assertion. =head1 DESCRIPTION The assertion facet is provided by any event representing an assertion that was made. =head1 FIELDS =over 4 =item $string = $assert->{details} =item $string = $assert->details() Human readable description of the assertion. =item $bool = $assert->{pass} =item $bool = $assert->pass() True if the assertion passed. =item $bool = $assert->{no_debug} =item $bool = $assert->no_debug() Set this to true if you have provided custom diagnostics and do not want the defaults to be displayed. =item $int = $assert->{number} =item $int = $assert->number() (Optional) assertion number. This may be omitted or ignored. This is usually only useful when parsing/processing TAP. B: This is not set by the Test2 system, assertion number is not known until AFTER the assertion has been processed. This attribute is part of the spec only for harnesses. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!]zÕ‘ÖÖ perl5/Test2/EventFacet/Parent.pmnuÏÃ6Ç$package Test2::EventFacet::Parent; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/confess/; BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -hid -children -buffered }; sub init { confess "Attribute 'hid' must be set" unless defined $_[0]->{+HID}; $_[0]->{+CHILDREN} ||= []; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Parent - Facet for events contains other events =head1 DESCRIPTION This facet is used when an event contains other events, such as a subtest. =head1 FIELDS =over 4 =item $string = $parent->{details} =item $string = $parent->details() Human readable description of the event. =item $hid = $parent->{hid} =item $hid = $parent->hid() Hub ID of the hub that is represented in the parent-child relationship. =item $arrayref = $parent->{children} =item $arrayref = $parent->children() Arrayref containing the facet-data hashes of events nested under this one. I =item $bool = $parent->{buffered} =item $bool = $parent->buffered() True if the subtest is buffered (meaning the formatter has probably not seen them yet). =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ЈžPkk!perl5/Test2/EventFacet/Amnesty.pmnuÏÃ6Ç$package Test2::EventFacet::Amnesty; use strict; use warnings; our $VERSION = '1.302183'; sub is_list { 1 } BEGIN { require Test2::EventFacet; our @ISA = qw(Test2::EventFacet) } use Test2::Util::HashBase qw{ -tag -inherited }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::EventFacet::Amnesty - Facet for assertion amnesty. =head1 DESCRIPTION This package represents what is expected in units of amnesty. =head1 NOTES This facet appears in a list instead of being a single item. =head1 FIELDS =over 4 =item $string = $amnesty->{details} =item $string = $amnesty->details() Human readable explanation of why amnesty was granted. Example: I =item $short_string = $amnesty->{tag} =item $short_string = $amnesty->tag() Short string (usually 10 characters or less, not enforced, but may be truncated by renderers) categorizing the amnesty. =item $bool = $amnesty->{inherited} =item $bool = $amnesty->inherited() This will be true if the amnesty was granted to a parent event and inherited by this event, which is a child, such as an assertion within a subtest that is marked todo. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!¦a¢ µ#µ#perl5/Test2/Tools/Tiny.pmnuÏÃ6Ç$package Test2::Tools::Tiny; use strict; use warnings; BEGIN { if ($] lt "5.008") { require Test::Builder::IO::Scalar; } } use Scalar::Util qw/blessed/; use Test2::Util qw/try/; use Test2::API qw/context run_subtest test2_stack/; use Test2::Hub::Interceptor(); use Test2::Hub::Interceptor::Terminator(); our $VERSION = '1.302183'; BEGIN { require Exporter; our @ISA = qw(Exporter) } our @EXPORT = qw{ ok is isnt like unlike is_deeply diag note skip_all todo plan done_testing warnings exception tests capture }; sub ok($;$@) { my ($bool, $name, @diag) = @_; my $ctx = context(); return $ctx->pass_and_release($name) if $bool; return $ctx->fail_and_release($name, @diag); } sub is($$;$@) { my ($got, $want, $name, @diag) = @_; my $ctx = context(); my $bool; if (defined($got) && defined($want)) { $bool = "$got" eq "$want"; } elsif (defined($got) xor defined($want)) { $bool = 0; } else { # Both are undef $bool = 1; } return $ctx->pass_and_release($name) if $bool; $got = '*NOT DEFINED*' unless defined $got; $want = '*NOT DEFINED*' unless defined $want; unshift @diag => ( "GOT: $got", "EXPECTED: $want", ); return $ctx->fail_and_release($name, @diag); } sub isnt($$;$@) { my ($got, $want, $name, @diag) = @_; my $ctx = context(); my $bool; if (defined($got) && defined($want)) { $bool = "$got" ne "$want"; } elsif (defined($got) xor defined($want)) { $bool = 1; } else { # Both are undef $bool = 0; } return $ctx->pass_and_release($name) if $bool; unshift @diag => "Strings are the same (they should not be)" unless $bool; return $ctx->fail_and_release($name, @diag); } sub like($$;$@) { my ($thing, $pattern, $name, @diag) = @_; my $ctx = context(); my $bool; if (defined($thing)) { $bool = "$thing" =~ $pattern; unshift @diag => ( "Value: $thing", "Does not match: $pattern" ) unless $bool; } else { $bool = 0; unshift @diag => "Got an undefined value."; } return $ctx->pass_and_release($name) if $bool; return $ctx->fail_and_release($name, @diag); } sub unlike($$;$@) { my ($thing, $pattern, $name, @diag) = @_; my $ctx = context(); my $bool; if (defined($thing)) { $bool = "$thing" !~ $pattern; unshift @diag => ( "Unexpected pattern match (it should not match)", "Value: $thing", "Matches: $pattern" ) unless $bool; } else { $bool = 0; unshift @diag => "Got an undefined value."; } return $ctx->pass_and_release($name) if $bool; return $ctx->fail_and_release($name, @diag); } sub is_deeply($$;$@) { my ($got, $want, $name, @diag) = @_; my $ctx = context(); no warnings 'once'; require Data::Dumper; # Otherwise numbers might be unquoted local $Data::Dumper::Useperl = 1; local $Data::Dumper::Sortkeys = 1; local $Data::Dumper::Deparse = 1; local $Data::Dumper::Freezer = 'XXX'; local *UNIVERSAL::XXX = sub { my ($thing) = @_; if (ref($thing)) { $thing = {%$thing} if "$thing" =~ m/=HASH/; $thing = [@$thing] if "$thing" =~ m/=ARRAY/; $thing = \"$$thing" if "$thing" =~ m/=SCALAR/; } $_[0] = $thing; }; my $g = Data::Dumper::Dumper($got); my $w = Data::Dumper::Dumper($want); my $bool = $g eq $w; return $ctx->pass_and_release($name) if $bool; return $ctx->fail_and_release($name, $g, $w, @diag); } sub diag { my $ctx = context(); $ctx->diag(join '', @_); $ctx->release; } sub note { my $ctx = context(); $ctx->note(join '', @_); $ctx->release; } sub skip_all { my ($reason) = @_; my $ctx = context(); $ctx->plan(0, SKIP => $reason); $ctx->release if $ctx; } sub todo { my ($reason, $sub) = @_; my $ctx = context(); # This code is mostly copied from Test2::Todo in the Test2-Suite # distribution. my $hub = test2_stack->top; my $filter = $hub->pre_filter( sub { my ($active_hub, $event) = @_; if ($active_hub == $hub) { $event->set_todo($reason) if $event->can('set_todo'); $event->add_amnesty({tag => 'TODO', details => $reason}); } else { $event->add_amnesty({tag => 'TODO', details => $reason, inherited => 1}); } return $event; }, inherit => 1, todo => $reason, ); $sub->(); $hub->pre_unfilter($filter); $ctx->release if $ctx; } sub plan { my ($max) = @_; my $ctx = context(); $ctx->plan($max); $ctx->release; } sub done_testing { my $ctx = context(); $ctx->done_testing; $ctx->release; } sub warnings(&) { my $code = shift; my @warnings; local $SIG{__WARN__} = sub { push @warnings => @_ }; $code->(); return \@warnings; } sub exception(&) { my $code = shift; local ($@, $!, $SIG{__DIE__}); my $ok = eval { $code->(); 1 }; my $error = $@ || 'SQUASHED ERROR'; return $ok ? undef : $error; } sub tests { my ($name, $code) = @_; my $ctx = context(); my $be = caller->can('before_each'); $be->($name) if $be; my $bool = run_subtest($name, $code, 1); $ctx->release; return $bool; } sub capture(&) { my $code = shift; my ($err, $out) = ("", ""); my $handles = test2_stack->top->format->handles; my ($ok, $e); { my ($out_fh, $err_fh); ($ok, $e) = try { # Scalar refs as filehandles were added in 5.8. if ($] ge "5.008") { open($out_fh, '>', \$out) or die "Failed to open a temporary STDOUT: $!"; open($err_fh, '>', \$err) or die "Failed to open a temporary STDERR: $!"; } # Emulate scalar ref filehandles with a tie. else { $out_fh = Test::Builder::IO::Scalar->new(\$out) or die "Failed to open a temporary STDOUT"; $err_fh = Test::Builder::IO::Scalar->new(\$err) or die "Failed to open a temporary STDERR"; } test2_stack->top->format->set_handles([$out_fh, $err_fh, $out_fh]); $code->(); }; } test2_stack->top->format->set_handles($handles); die $e unless $ok; $err =~ s/ $/_/mg; $out =~ s/ $/_/mg; return { STDOUT => $out, STDERR => $err, }; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Tools::Tiny - Tiny set of tools for unfortunate souls who cannot use L. =head1 DESCRIPTION You should really look at L. This package is some very basic essential tools implemented using L. This exists only so that L and other tools required by L can be tested. This is the package L uses to test itself. =head1 USE Test2::Suite INSTEAD Use L if at all possible. =head1 EXPORTS =over 4 =item ok($bool, $name) =item ok($bool, $name, @diag) Run a simple assertion. =item is($got, $want, $name) =item is($got, $want, $name, @diag) Assert that 2 strings are the same. =item isnt($got, $do_not_want, $name) =item isnt($got, $do_not_want, $name, @diag) Assert that 2 strings are not the same. =item like($got, $regex, $name) =item like($got, $regex, $name, @diag) Check that the input string matches the regex. =item unlike($got, $regex, $name) =item unlike($got, $regex, $name, @diag) Check that the input string does not match the regex. =item is_deeply($got, $want, $name) =item is_deeply($got, $want, $name, @diag) Check 2 data structures. Please note that this is a I implementation that compares the output of L against both structures. =item diag($msg) Issue a diagnostics message to STDERR. =item note($msg) Issue a diagnostics message to STDOUT. =item skip_all($reason) Skip all tests. =item todo $reason => sub { ... } Run a block in TODO mode. =item plan($count) Set the plan. =item done_testing() Set the plan to the current test count. =item $warnings = warnings { ... } Capture an arrayref of warnings from the block. =item $exception = exception { ... } Capture an exception. =item tests $name => sub { ... } Run a subtest. =item $output = capture { ... } Capture STDOUT and STDERR output. Result looks like this: { STDOUT => "...", STDERR => "...", } =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!gè‡ssperl5/Test2/Util/Trace.pmnuÏÃ6Ç$package Test2::Util::Trace; require Test2::EventFacet::Trace; use warnings; use strict; our @ISA = ('Test2::EventFacet::Trace'); our $VERSION = '1.302183'; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Util::Trace - Legacy wrapper fro L. =head1 DESCRIPTION All the functionality for this class has been moved to L. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ÿz5±Ãà perl5/Test2/Util/ExternalMeta.pmnuÏÃ6Ç$package Test2::Util::ExternalMeta; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/croak/; sub META_KEY() { '_meta' } our @EXPORT = qw/meta set_meta get_meta delete_meta/; BEGIN { require Exporter; our @ISA = qw(Exporter) } sub set_meta { my $self = shift; my ($key, $value) = @_; validate_key($key); $self->{+META_KEY} ||= {}; $self->{+META_KEY}->{$key} = $value; } sub get_meta { my $self = shift; my ($key) = @_; validate_key($key); my $meta = $self->{+META_KEY} or return undef; return $meta->{$key}; } sub delete_meta { my $self = shift; my ($key) = @_; validate_key($key); my $meta = $self->{+META_KEY} or return undef; delete $meta->{$key}; } sub meta { my $self = shift; my ($key, $default) = @_; validate_key($key); my $meta = $self->{+META_KEY}; return undef unless $meta || defined($default); unless($meta) { $meta = {}; $self->{+META_KEY} = $meta; } $meta->{$key} = $default if defined($default) && !defined($meta->{$key}); return $meta->{$key}; } sub validate_key { my $key = shift; return if $key && !ref($key); my $render_key = defined($key) ? "'$key'" : 'undef'; croak "Invalid META key: $render_key, keys must be true, and may not be references"; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Util::ExternalMeta - Allow third party tools to safely attach meta-data to your instances. =head1 DESCRIPTION This package lets you define a clear, and consistent way to allow third party tools to attach meta-data to your instances. If your object consumes this package, and imports its methods, then third party meta-data has a safe place to live. =head1 SYNOPSIS package My::Object; use strict; use warnings; use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/; ... Now to use it: my $inst = My::Object->new; $inst->set_meta(foo => 'bar'); my $val = $inst->get_meta('foo'); =head1 WHERE IS THE DATA STORED? This package assumes your instances are blessed hashrefs, it will not work if that is not true. It will store all meta-data in the C<_meta> key on your objects hash. If your object makes use of the C<_meta> key in its underlying hash, then there is a conflict and you cannot use this package. =head1 EXPORTS =over 4 =item $val = $obj->meta($key) =item $val = $obj->meta($key, $default) This will get the value for a specified meta C<$key>. Normally this will return C when there is no value for the C<$key>, however you can specify a C<$default> value to set when no value is already set. =item $val = $obj->get_meta($key) This will get the value for a specified meta C<$key>. This does not have the C<$default> overhead that C does. =item $val = $obj->delete_meta($key) This will remove the value of a specified meta C<$key>. The old C<$val> will be returned. =item $obj->set_meta($key, $val) Set the value of a specified meta C<$key>. =back =head1 META-KEY RESTRICTIONS Meta keys must be defined, and must be true when used as a boolean. Keys may not be references. You are free to stringify a reference C<"$ref"> for use as a key, but this package will not stringify it for you. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!þ%éd¥3¥3perl5/Test2/Util/HashBase.pmnuÏÃ6Ç$package Test2::Util::HashBase; use strict; use warnings; our $VERSION = '1.302183'; ################################################################# # # # This is a generated file! Do not modify this file directly! # # Use hashbase_inc.pl script to regenerate this file. # # The script is part of the Object::HashBase distribution. # # Note: You can modify the version number above this comment # # if needed, that is fine. # # # ################################################################# { no warnings 'once'; $Test2::Util::HashBase::HB_VERSION = '0.009'; *Test2::Util::HashBase::ATTR_SUBS = \%Object::HashBase::ATTR_SUBS; *Test2::Util::HashBase::ATTR_LIST = \%Object::HashBase::ATTR_LIST; *Test2::Util::HashBase::VERSION = \%Object::HashBase::VERSION; *Test2::Util::HashBase::CAN_CACHE = \%Object::HashBase::CAN_CACHE; } require Carp; { no warnings 'once'; $Carp::Internal{+__PACKAGE__} = 1; } BEGIN { # these are not strictly equivalent, but for out use we don't care # about order *_isa = ($] >= 5.010 && require mro) ? \&mro::get_linear_isa : sub { no strict 'refs'; my @packages = ($_[0]); my %seen; for my $package (@packages) { push @packages, grep !$seen{$_}++, @{"$package\::ISA"}; } return \@packages; } } my %SPEC = ( '^' => {reader => 1, writer => 0, dep_writer => 1, read_only => 0, strip => 1}, '-' => {reader => 1, writer => 0, dep_writer => 0, read_only => 1, strip => 1}, '>' => {reader => 0, writer => 1, dep_writer => 0, read_only => 0, strip => 1}, '<' => {reader => 1, writer => 0, dep_writer => 0, read_only => 0, strip => 1}, '+' => {reader => 0, writer => 0, dep_writer => 0, read_only => 0, strip => 1}, ); sub import { my $class = shift; my $into = caller; # Make sure we list the OLDEST version used to create this class. my $ver = $Test2::Util::HashBase::HB_VERSION || $Test2::Util::HashBase::VERSION; $Test2::Util::HashBase::VERSION{$into} = $ver if !$Test2::Util::HashBase::VERSION{$into} || $Test2::Util::HashBase::VERSION{$into} > $ver; my $isa = _isa($into); my $attr_list = $Test2::Util::HashBase::ATTR_LIST{$into} ||= []; my $attr_subs = $Test2::Util::HashBase::ATTR_SUBS{$into} ||= {}; my %subs = ( ($into->can('new') ? () : (new => \&_new)), (map %{$Test2::Util::HashBase::ATTR_SUBS{$_} || {}}, @{$isa}[1 .. $#$isa]), ( map { my $p = substr($_, 0, 1); my $x = $_; my $spec = $SPEC{$p} || {reader => 1, writer => 1}; substr($x, 0, 1) = '' if $spec->{strip}; push @$attr_list => $x; my ($sub, $attr) = (uc $x, $x); $attr_subs->{$sub} = sub() { $attr }; my %out = ($sub => $attr_subs->{$sub}); $out{$attr} = sub { $_[0]->{$attr} } if $spec->{reader}; $out{"set_$attr"} = sub { $_[0]->{$attr} = $_[1] } if $spec->{writer}; $out{"set_$attr"} = sub { Carp::croak("'$attr' is read-only") } if $spec->{read_only}; $out{"set_$attr"} = sub { Carp::carp("set_$attr() is deprecated"); $_[0]->{$attr} = $_[1] } if $spec->{dep_writer}; %out; } @_ ), ); no strict 'refs'; *{"$into\::$_"} = $subs{$_} for keys %subs; } sub attr_list { my $class = shift; my $isa = _isa($class); my %seen; my @list = grep { !$seen{$_}++ } map { my @out; if (0.004 > ($Test2::Util::HashBase::VERSION{$_} || 0)) { Carp::carp("$_ uses an inlined version of Test2::Util::HashBase too old to support attr_list()"); } else { my $list = $Test2::Util::HashBase::ATTR_LIST{$_}; @out = $list ? @$list : () } @out; } reverse @$isa; return @list; } sub _new { my $class = shift; my $self; if (@_ == 1) { my $arg = shift; my $type = ref($arg); if ($type eq 'HASH') { $self = bless({%$arg}, $class) } else { Carp::croak("Not sure what to do with '$type' in $class constructor") unless $type eq 'ARRAY'; my %proto; my @attributes = attr_list($class); while (@$arg) { my $val = shift @$arg; my $key = shift @attributes or Carp::croak("Too many arguments for $class constructor"); $proto{$key} = $val; } $self = bless(\%proto, $class); } } else { $self = bless({@_}, $class); } $Test2::Util::HashBase::CAN_CACHE{$class} = $self->can('init') unless exists $Test2::Util::HashBase::CAN_CACHE{$class}; $self->init if $Test2::Util::HashBase::CAN_CACHE{$class}; $self; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Util::HashBase - Build hash based classes. =head1 SYNOPSIS A class: package My::Class; use strict; use warnings; # Generate 3 accessors use Test2::Util::HashBase qw/foo -bar ^baz ban +boo/; # Chance to initialize defaults sub init { my $self = shift; # No other args $self->{+FOO} ||= "foo"; $self->{+BAR} ||= "bar"; $self->{+BAZ} ||= "baz"; $self->{+BAT} ||= "bat"; $self->{+BAN} ||= "ban"; $self->{+BOO} ||= "boo"; } sub print { print join ", " => map { $self->{$_} } FOO, BAR, BAZ, BAT, BAN, BOO; } Subclass it package My::Subclass; use strict; use warnings; # Note, you should subclass before loading HashBase. use base 'My::Class'; use Test2::Util::HashBase qw/bub/; sub init { my $self = shift; # We get the constants from the base class for free. $self->{+FOO} ||= 'SubFoo'; $self->{+BUB} ||= 'bub'; $self->SUPER::init(); } use it: package main; use strict; use warnings; use My::Class; # These are all functionally identical my $one = My::Class->new(foo => 'MyFoo', bar => 'MyBar'); my $two = My::Class->new({foo => 'MyFoo', bar => 'MyBar'}); my $three = My::Class->new(['MyFoo', 'MyBar']); # Readers! my $foo = $one->foo; # 'MyFoo' my $bar = $one->bar; # 'MyBar' my $baz = $one->baz; # Defaulted to: 'baz' my $bat = $one->bat; # Defaulted to: 'bat' # '>ban' means setter only, no reader # '+boo' means no setter or reader, just the BOO constant # Setters! $one->set_foo('A Foo'); #'-bar' means read-only, so the setter will throw an exception (but is defined). $one->set_bar('A bar'); # '^baz' means deprecated setter, this will warn about the setter being # deprecated. $one->set_baz('A Baz'); # '{+FOO} = 'xxx'; =head1 DESCRIPTION This package is used to generate classes based on hashrefs. Using this class will give you a C method, as well as generating accessors you request. Generated accessors will be getters, C setters will also be generated for you. You also get constants for each accessor (all caps) which return the key into the hash for that accessor. Single inheritance is also supported. =head1 THIS IS A BUNDLED COPY OF HASHBASE This is a bundled copy of L. This file was generated using the C script. =head1 METHODS =head2 PROVIDED BY HASH BASE =over 4 =item $it = $class->new(%PAIRS) =item $it = $class->new(\%PAIRS) =item $it = $class->new(\@ORDERED_VALUES) Create a new instance. HashBase will not export C if there is already a C method in your packages inheritance chain. B you just have to declare it before loading L. package My::Package; # predeclare new() so that HashBase does not give us one. sub new; use Test2::Util::HashBase qw/foo bar baz/; # Now we define our own new method. sub new { ... } This makes it so that HashBase sees that you have your own C method. Alternatively you can define the method before loading HashBase instead of just declaring it, but that scatters your use statements. The most common way to create an object is to pass in key/value pairs where each key is an attribute and each value is what you want assigned to that attribute. No checking is done to verify the attributes or values are valid, you may do that in C if desired. If you would like, you can pass in a hashref instead of pairs. When you do so the hashref will be copied, and the copy will be returned blessed as an object. There is no way to ask HashBase to bless a specific hashref. In some cases an object may only have 1 or 2 attributes, in which case a hashref may be too verbose for your liking. In these cases you can pass in an arrayref with only values. The values will be assigned to attributes in the order the attributes were listed. When there is inheritance involved the attributes from parent classes will come before subclasses. =back =head2 HOOKS =over 4 =item $self->init() This gives you the chance to set some default values to your fields. The only argument is C<$self> with its indexes already set from the constructor. B Test2::Util::HashBase checks for an init using C<< $class->can('init') >> during construction. It DOES NOT call C on the created object. Also note that the result of the check is cached, it is only ever checked once, the first time an instance of your class is created. This means that adding an C method AFTER the first construction will result in it being ignored. =back =head1 ACCESSORS =head2 READ/WRITE To generate accessors you list them when using the module: use Test2::Util::HashBase qw/foo/; This will generate the following subs in your namespace: =over 4 =item foo() Getter, used to get the value of the C field. =item set_foo() Setter, used to set the value of the C field. =item FOO() Constant, returns the field C's key into the class hashref. Subclasses will also get this function as a constant, not simply a method, that means it is copied into the subclass namespace. The main reason for using these constants is to help avoid spelling mistakes and similar typos. It will not help you if you forget to prefix the '+' though. =back =head2 READ ONLY use Test2::Util::HashBase qw/-foo/; =over 4 =item set_foo() Throws an exception telling you the attribute is read-only. This is exported to override any active setters for the attribute in a parent class. =back =head2 DEPRECATED SETTER use Test2::Util::HashBase qw/^foo/; =over 4 =item set_foo() This will set the value, but it will also warn you that the method is deprecated. =back =head2 NO SETTER use Test2::Util::HashBase qw/ method is defined at all. =head2 NO READER use Test2::Util::HashBase qw/>foo/; Only gives you a write (C), no C method is defined at all. =head2 CONSTANT ONLY use Test2::Util::HashBase qw/+foo/; This does not create any methods for you, it just adds the C constant. =head1 SUBCLASSING You can subclass an existing HashBase class. use base 'Another::HashBase::Class'; use Test2::Util::HashBase qw/foo bar baz/; The base class is added to C<@ISA> for you, and all constants from base classes are added to subclasses automatically. =head1 GETTING A LIST OF ATTRIBUTES FOR A CLASS Test2::Util::HashBase provides a function for retrieving a list of attributes for an Test2::Util::HashBase class. =over 4 =item @list = Test2::Util::HashBase::attr_list($class) =item @list = $class->Test2::Util::HashBase::attr_list() Either form above will work. This will return a list of attributes defined on the object. This list is returned in the attribute definition order, parent class attributes are listed before subclass attributes. Duplicate attributes will be removed before the list is returned. B This list is used in the C<< $class->new(\@ARRAY) >> constructor to determine the attribute to which each value will be paired. =back =head1 SOURCE The source code repository for HashBase can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2017 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!}í–ûû!perl5/Test2/Util/Facets2Legacy.pmnuÏÃ6Ç$package Test2::Util::Facets2Legacy; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/croak confess/; use Scalar::Util qw/blessed/; use base 'Exporter'; our @EXPORT_OK = qw{ causes_fail diagnostics global increments_count no_display sets_plan subtest_id summary terminate uuid }; our %EXPORT_TAGS = ( ALL => \@EXPORT_OK ); our $CYCLE_DETECT = 0; sub _get_facet_data { my $in = shift; if (blessed($in) && $in->isa('Test2::Event')) { confess "Cycle between Facets2Legacy and $in\->facet_data() (Did you forget to override the facet_data() method?)" if $CYCLE_DETECT; local $CYCLE_DETECT = 1; return $in->facet_data; } return $in if ref($in) eq 'HASH'; croak "'$in' Does not appear to be either a Test::Event or an EventFacet hashref"; } sub causes_fail { my $facet_data = _get_facet_data(shift @_); return 1 if $facet_data->{errors} && grep { $_->{fail} } @{$facet_data->{errors}}; if (my $control = $facet_data->{control}) { return 1 if $control->{halt}; return 1 if $control->{terminate}; } return 0 if $facet_data->{amnesty} && @{$facet_data->{amnesty}}; return 1 if $facet_data->{assert} && !$facet_data->{assert}->{pass}; return 0; } sub diagnostics { my $facet_data = _get_facet_data(shift @_); return 1 if $facet_data->{errors} && @{$facet_data->{errors}}; return 0 unless $facet_data->{info} && @{$facet_data->{info}}; return (grep { $_->{debug} } @{$facet_data->{info}}) ? 1 : 0; } sub global { my $facet_data = _get_facet_data(shift @_); return 0 unless $facet_data->{control}; return $facet_data->{control}->{global}; } sub increments_count { my $facet_data = _get_facet_data(shift @_); return $facet_data->{assert} ? 1 : 0; } sub no_display { my $facet_data = _get_facet_data(shift @_); return 0 unless $facet_data->{about}; return $facet_data->{about}->{no_display}; } sub sets_plan { my $facet_data = _get_facet_data(shift @_); my $plan = $facet_data->{plan} or return; my @out = ($plan->{count} || 0); if ($plan->{skip}) { push @out => 'SKIP'; push @out => $plan->{details} if defined $plan->{details}; } elsif ($plan->{none}) { push @out => 'NO PLAN' } return @out; } sub subtest_id { my $facet_data = _get_facet_data(shift @_); return undef unless $facet_data->{parent}; return $facet_data->{parent}->{hid}; } sub summary { my $facet_data = _get_facet_data(shift @_); return '' unless $facet_data->{about} && $facet_data->{about}->{details}; return $facet_data->{about}->{details}; } sub terminate { my $facet_data = _get_facet_data(shift @_); return undef unless $facet_data->{control}; return $facet_data->{control}->{terminate}; } sub uuid { my $in = shift; if ($CYCLE_DETECT) { if (blessed($in) && $in->isa('Test2::Event')) { my $meth = $in->can('uuid'); $meth = $in->can('SUPER::uuid') if $meth == \&uuid; my $uuid = $in->$meth if $meth && $meth != \&uuid; return $uuid if $uuid; } return undef; } my $facet_data = _get_facet_data($in); return $facet_data->{about}->{uuid} if $facet_data->{about} && $facet_data->{about}->{uuid}; return undef; } 1; =pod =encoding UTF-8 =head1 NAME Test2::Util::Facets2Legacy - Convert facet data to the legacy event API. =head1 DESCRIPTION This module exports several subroutines from the older event API (see L). These subroutines can be used as methods on any object that provides a custom C method. These subroutines can also be used as functions that take a facet data hashref as arguments. =head1 SYNOPSIS =head2 AS METHODS package My::Event; use Test2::Util::Facets2Legacy ':ALL'; sub facet_data { return { ... } } Then to use it: my $e = My::Event->new(...); my $causes_fail = $e->causes_fail; my $summary = $e->summary; .... =head2 AS FUNCTIONS use Test2::Util::Facets2Legacy ':ALL'; my $f = { assert => { ... }, info => [{...}, ...], control => {...}, ... }; my $causes_fail = causes_fail($f); my $summary = summary($f); =head1 NOTE ON CYCLES When used as methods, all these subroutines call C<< $e->facet_data() >>. The default C method in L relies on the legacy methods this module emulates in order to work. As a result of this it is very easy to create infinite recursion bugs. These methods have cycle detection and will throw an exception early if a cycle is detected. C is currently the only subroutine in this library that has a fallback behavior when cycles are detected. =head1 EXPORTS Nothing is exported by default. You must specify which methods to import, or use the ':ALL' tag. =over 4 =item $bool = $e->causes_fail() =item $bool = causes_fail($f) Check if the event or facets result in a failing state. =item $bool = $e->diagnostics() =item $bool = diagnostics($f) Check if the event or facets contain any diagnostics information. =item $bool = $e->global() =item $bool = global($f) Check if the event or facets need to be globally processed. =item $bool = $e->increments_count() =item $bool = increments_count($f) Check if the event or facets make an assertion. =item $bool = $e->no_display() =item $bool = no_display($f) Check if the event or facets should be rendered or hidden. =item ($max, $directive, $reason) = $e->sets_plan() =item ($max, $directive, $reason) = sets_plan($f) Check if the event or facets set a plan, and return the plan details. =item $id = $e->subtest_id() =item $id = subtest_id($f) Get the subtest id, if any. =item $string = $e->summary() =item $string = summary($f) Get the summary of the event or facets hash, if any. =item $undef_or_int = $e->terminate() =item $undef_or_int = terminate($f) Check if the event or facets should result in process termination, if so the exit code is returned (which could be 0). undef is returned if no termination is requested. =item $uuid = $e->uuid() =item $uuid = uuid($f) Get the UUID of the facets or event. B This will fall back to C<< $e->SUPER::uuid() >> if a cycle is detected and an event is used as the argument. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!^>¯ ·4·4perl5/Test2/Transition.podnuÏÃ6Ç$=pod =head1 NAME Test2::Transition - Transition notes when upgrading to Test2 =head1 DESCRIPTION This is where gotchas and breakages related to the Test2 upgrade are documented. The upgrade causes Test::Builder to defer to Test2 under the hood. This transition is mostly transparent, but there are a few cases that can trip you up. =head1 THINGS THAT BREAK This is the list of scenarios that break with the new internals. =head2 Test::Builder1.5/2 conditionals =head3 The Problem a few years back there were two attempts to upgrade/replace Test::Builder. Confusingly these were called Test::Builder2 and Test::Builder1.5, in that order. Many people put conditionals in their code to check the Test::Builder version number and adapt their code accordingly. The Test::Builder2/1.5 projects both died out. Now the conditional code people added has become a mine field. A vast majority of modules broken by Test2 fall into this category. =head3 The Fix The fix is to remove all Test::Builder1.5/2 related code. Either use the legacy Test::Builder API, or use Test2 directly. =head2 Replacing the Test::Builder singleton =head3 The Problem Some test modules would replace the Test::Builder singleton instance with their own instance or subclass. This was usually done to intercept or modify results as they happened. The Test::Builder singleton is now a simple compatibility wrapper around Test2. The Test::Builder singleton is no longer the central place for results. Many results bypass the Test::Builder singleton completely, which breaks and behavior intended when replacing the singleton. =head3 The Fix If you simply want to intercept all results instead of letting them go to TAP, you should look at the L docs and read about pushing a new hub onto the hub stack. Replacing the hub temporarily is now the correct way to intercept results. If your goal is purely monitoring of events use the C<< Test2::Hub->listen() >> method exported by Test::More to watch events as they are fired. If you wish to modify results before they go to TAP look at the C<< Test2::Hub->filter() >> method. =head2 Directly Accessing Hash Elements =head3 The Problem Some modules look directly at hash keys on the Test::Builder singleton. The problem here is that the Test::Builder singleton no longer holds anything important. =head3 The Fix The fix is to use the API specified in L to look at or modify state as needed. =head2 Subtest indentation =head3 The Problem An early change, in fact the change that made Test2 an idea, was a change to the indentation of the subtest note. It was decided it would be more readable to outdent the subtest note instead of having it inline with the subtest: # subtest foo ok 1 - blah 1..1 ok 1 - subtest foo The old style indented the note: # subtest foo ok 1 - blah 1..1 ok 1 - subtest foo This breaks tests that do string comparison of TAP output. =head3 The Fix my $indent = $INC{'Test2/API.pm'} ? '' : ' '; is( $subtest_output, "${indent}# subtest foo", "Got subtest note" ); Check if C<$INC{'Test2/API.pm'}> is set, if it is then no indentation should be expected. If it is not set, then the old Test::Builder is in use, indentation should be expected. =head1 DISTRIBUTIONS THAT BREAK OR NEED TO BE UPGRADED This is a list of cpan modules that have been known to have been broken by the upgrade at one point. =head2 WORKS BUT TESTS WILL FAIL These modules still function correctly, but their test suites will not pass. If you already have these modules installed then you can continue to use them. If you are trying to install them after upgrading Test::Builder you will need to force installation, or bypass the broken tests. =over 4 =item Test::DBIx::Class::Schema This module has a test that appears to work around a Test::Builder bug. The bug appears to have been fixed by Test2, which means the workaround causes a failure. This can be easily updated, but nobody has done so yet. Known broken in versions: 1.0.9 and older =item Device::Chip Tests break due to subtest indentation. Known broken in version 0.07. Apparently works fine in 0.06 though. Patch has been submitted to fix the issue. =back =head2 UPGRADE SUGGESTED These are modules that did not break, but had broken test suites that have since been fixed. =over 4 =item Test::Exception Old versions work fine, but have a minor test name behavior that breaks with Test2. Old versions will no longer install because of this. The latest version on CPAN will install just fine. Upgrading is not required, but is recommended. Fixed in version: 0.43 =item Data::Peek Some tests depended on C<$!> and C<$?> being modified in subtle ways. A patch was applied to correct things that changed. The module itself works fine, there is no need to upgrade. Fixed in version: 0.45 =item circular::require Some tests were fragile and required base.pm to be loaded at a late stage. Test2 was loading base.pm too early. The tests were updated to fix this. The module itself never broke, you do not need to upgrade. Fixed in version: 0.12 =item Test::Module::Used A test worked around a now-fixed planning bug. There is no need to upgrade if you have an old version installed. New versions install fine if you want them. Fixed in version: 0.2.5 =item Test::Moose::More Some tests were fragile, but have been fixed. The actual breakage was from the subtest comment indentation change. No need to upgrade, old versions work fine. Only new versions will install. Fixed in version: 0.025 =item Test::FITesque This was broken by a bugfix to how planning is done. The test was updated after the bugfix. Fixed in version: 0.04 =item Test::Kit Old versions work fine, but would not install because L was in the dependency chain. An upgrade should not be needed. Fixed in version: 2.15 =item autouse A test broke because it depended on Scalar::Util not being loaded. Test2 loads Scalar::Util. The test was updated to load Test2 after checking Scalar::Util's load status. There is no need to upgrade if you already have it installed. Fixed in version: 1.11 =back =head2 NEED TO UPGRADE =over 4 =item Test::SharedFork Old versions need to directly access Test::Builder singleton hash elements. The latest version on CPAN will still do this on old Test::Builder, but will defer to L on Test2. Fixed in version: 0.35 =item Test::Builder::Clutch This works by doing overriding methods on the singleton, and directly accessing hash values on the singleton. A new version has been released that uses the Test2 API to accomplish the same result in a saner way. Fixed in version: 0.07 =item Test::Dist::VersionSync This had Test::Builder2 conditionals. This was fixed by removing the conditionals. Fixed in version: 1.1.4 =item Test::Modern This relied on C<< Test::Builder->_try() >> which was a private method, documented as something nobody should use. This was fixed by using a different tool. Fixed in version: 0.012 =item Test::UseAllModules Version 0.14 relied on C<< Test::Builder->history >> which was available in Test::Builder 1.5. Versions 0.12 and 0.13 relied on other Test::Builder internals. Fixed in version: 0.15 =item Test::More::Prefix Worked by applying a role that wrapped C<< Test::Builder->_print_comment >>. Fixed by adding an event filter that modifies the message instead when running under Test2. Fixed in version: 0.007 =back =head2 STILL BROKEN =over 4 =item Test::Aggregate This distribution directly accesses the hash keys in the L singleton. It also approaches the problem from the wrong angle, please consider using L for similar functionality and L which allows module preloading at the harness level. Still broken as of version: 0.373 =item Test::Wrapper This module directly uses hash keys in the L singleton. This module is also obsolete thanks to the benefits of L. Use C from L to achieve a similar result. Still broken as of version: 0.3.0 =item Test::ParallelSubtest This module overrides C and C. It also directly accesses hash elements of the singleton. It has not yet been fixed. Alternatives: L and L (not stable). Still broken as of version: 0.05 =item Test::Pretty See https://github.com/tokuhirom/Test-Pretty/issues/25 The author admits the module is crazy, and he is awaiting a stable release of something new (Test2) to completely rewrite it in a sane way. Still broken as of version: 0.32 =item Net::BitTorrent The tests for this module directly access L hash keys. Most, if not all of these hash keys have public API methods that could be used instead to avoid the problem. Still broken in version: 0.052 =item Test::Group It monkeypatches Test::Builder, and calls it "black magic" in the code. Still broken as of version: 0.20 =item Test::Flatten This modifies the Test::Builder internals in many ways. A better was to accomplish the goal of this module is to write your own subtest function. Still broken as of version: 0.11 =item Log::Dispatch::Config::TestLog Modifies Test::Builder internals. Still broken as of version: 0.02 =item Test::Able Modifies Test::Builder internals. Still broken as of version: 0.11 =back =head1 MAKE ASSERTIONS -> SEND EVENTS =head2 LEGACY use Test::Builder; # A majority of tools out there do this: # my $TB = Test::Builder->new; # This works, but has always been wrong, forcing Test::Builder to implement # subtests as a horrific hack. It also causes problems for tools that try # to replace the singleton (also discouraged). sub my_ok($;$) { my ($bool, $name) = @_; my $TB = Test::Builder->new; $TB->ok($bool, $name); } sub my_diag($) { my ($msg) = @_; my $TB = Test::Builder->new; $TB->diag($msg); } =head2 TEST2 use Test2::API qw/context/; sub my_ok($;$) { my ($bool, $name) = @_; my $ctx = context(); $ctx->ok($bool, $name); $ctx->release; } sub my_diag($) { my ($msg) = @_; my $ctx = context(); $ctx->diag($msg); $ctx->release; } The context object has API compatible implementations of the following methods: =over 4 =item ok($bool, $name) =item diag(@messages) =item note(@messages) =item subtest($name, $code) =back If you are looking for helpers with C, C, and others, see L. =head1 WRAP EXISTING TOOLS =head2 LEGACY use Test::More; sub exclusive_ok { my ($bool1, $bool2, $name) = @_; # Ensure errors are reported 1 level higher local $Test::Builder::Level = $Test::Builder::Level + 1; $ok = $bool1 || $bool2; $ok &&= !($bool1 && $bool2); ok($ok, $name); return $bool; } Every single tool in the chain from this, to C, to anything C calls needs to increment the C<$Level> variable. When an error occurs Test::Builder will do a trace to the stack frame determined by C<$Level>, and report that file+line as the one where the error occurred. If you or any other tool you use forgets to set C<$Level> then errors will be reported to the wrong place. =head2 TEST2 use Test::More; sub exclusive_ok { my ($bool1, $bool2, $name) = @_; # Grab and store the context, even if you do not need to use it # directly. my $ctx = context(); $ok = $bool1 || $bool2; $ok &&= !($bool1 && $bool2); ok($ok, $name); $ctx->release; return $bool; } Instead of using C<$Level> to perform a backtrace, Test2 uses a context object. In this sample you create a context object and store it. This locks the context (errors report 1 level up from here) for all wrapped tools to find. You do not need to use the context object, but you do need to store it in a variable. Once the sub ends the C<$ctx> variable is destroyed which lets future tools find their own. =head1 USING UTF8 =head2 LEGACY # Set the mode BEFORE anything loads Test::Builder use open ':std', ':encoding(utf8)'; use Test::More; Or # Modify the filehandles my $builder = Test::More->builder; binmode $builder->output, ":encoding(utf8)"; binmode $builder->failure_output, ":encoding(utf8)"; binmode $builder->todo_output, ":encoding(utf8)"; =head2 TEST2 use Test2::API qw/test2_stack/; test2_stack->top->format->encoding('utf8'); Though a much better way is to use the L plugin, which is part of L. =head1 AUTHORS, CONTRIBUTORS AND REVIEWERS The following people have all contributed to this document in some way, even if only for review. =over 4 =item Chad Granum (EXODIST) Eexodist@cpan.orgE =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINER =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ag«o½½perl5/Test2/API.pmnuÏÃ6Ç$package Test2::API; use strict; use warnings; use Test2::Util qw/USE_THREADS/; BEGIN { $ENV{TEST_ACTIVE} ||= 1; $ENV{TEST2_ACTIVE} = 1; } our $VERSION = '1.302183'; my $INST; my $ENDING = 0; sub test2_unset_is_end { $ENDING = 0 } sub test2_get_is_end { $ENDING } sub test2_set_is_end { my $before = $ENDING; ($ENDING) = @_ ? @_ : (1); # Only send the event in a transition from false to true return if $before; return unless $ENDING; return unless $INST; my $stack = $INST->stack or return; my $root = $stack->root or return; return unless $root->count; return unless $$ == $INST->pid; return unless get_tid() == $INST->tid; my $trace = Test2::EventFacet::Trace->new( frame => [__PACKAGE__, __FILE__, __LINE__, __PACKAGE__ . '::test2_set_is_end'], ); my $ctx = Test2::API::Context->new( trace => $trace, hub => $root, ); $ctx->send_ev2(control => { phase => 'END', details => 'Transition to END phase' }); 1; } use Test2::API::Instance(\$INST); # Set the exit status END { test2_set_is_end(); # See gh #16 $INST->set_exit(); } sub CLONE { my $init = test2_init_done(); my $load = test2_load_done(); return if $init && $load; require Carp; Carp::croak "Test2 must be fully loaded before you start a new thread!\n"; } # See gh #16 { no warnings; INIT { eval 'END { test2_set_is_end() }; 1' or die $@ } } BEGIN { no warnings 'once'; if($] ge '5.014' || $ENV{T2_CHECK_DEPTH} || $Test2::API::DO_DEPTH_CHECK) { *DO_DEPTH_CHECK = sub() { 1 }; } else { *DO_DEPTH_CHECK = sub() { 0 }; } } use Test2::EventFacet::Trace(); use Test2::Util::Trace(); # Legacy use Test2::Hub::Subtest(); use Test2::Hub::Interceptor(); use Test2::Hub::Interceptor::Terminator(); use Test2::Event::Ok(); use Test2::Event::Diag(); use Test2::Event::Note(); use Test2::Event::Plan(); use Test2::Event::Bail(); use Test2::Event::Exception(); use Test2::Event::Waiting(); use Test2::Event::Skip(); use Test2::Event::Subtest(); use Carp qw/carp croak confess/; use Scalar::Util qw/blessed weaken/; use Test2::Util qw/get_tid clone_io pkg_to_file gen_uid/; our @EXPORT_OK = qw{ context release context_do no_context intercept intercept_deep run_subtest test2_init_done test2_load_done test2_load test2_start_preload test2_stop_preload test2_in_preload test2_is_testing_done test2_set_is_end test2_unset_is_end test2_get_is_end test2_pid test2_tid test2_stack test2_no_wait test2_ipc_wait_enable test2_ipc_wait_disable test2_ipc_wait_enabled test2_add_uuid_via test2_add_callback_testing_done test2_add_callback_context_aquire test2_add_callback_context_acquire test2_add_callback_context_init test2_add_callback_context_release test2_add_callback_exit test2_add_callback_post_load test2_add_callback_pre_subtest test2_list_context_aquire_callbacks test2_list_context_acquire_callbacks test2_list_context_init_callbacks test2_list_context_release_callbacks test2_list_exit_callbacks test2_list_post_load_callbacks test2_list_pre_subtest_callbacks test2_ipc test2_has_ipc test2_ipc_disable test2_ipc_disabled test2_ipc_drivers test2_ipc_add_driver test2_ipc_polling test2_ipc_disable_polling test2_ipc_enable_polling test2_ipc_get_pending test2_ipc_set_pending test2_ipc_get_timeout test2_ipc_set_timeout test2_formatter test2_formatters test2_formatter_add test2_formatter_set test2_stdout test2_stderr test2_reset_io }; BEGIN { require Exporter; our @ISA = qw(Exporter) } my $STACK = $INST->stack; my $CONTEXTS = $INST->contexts; my $INIT_CBS = $INST->context_init_callbacks; my $ACQUIRE_CBS = $INST->context_acquire_callbacks; my $STDOUT = clone_io(\*STDOUT); my $STDERR = clone_io(\*STDERR); sub test2_stdout { $STDOUT ||= clone_io(\*STDOUT) } sub test2_stderr { $STDERR ||= clone_io(\*STDERR) } sub test2_post_preload_reset { test2_reset_io(); $INST->post_preload_reset; } sub test2_reset_io { $STDOUT = clone_io(\*STDOUT); $STDERR = clone_io(\*STDERR); } sub test2_init_done { $INST->finalized } sub test2_load_done { $INST->loaded } sub test2_load { $INST->load } sub test2_start_preload { $ENV{T2_IN_PRELOAD} = 1; $INST->start_preload } sub test2_stop_preload { $ENV{T2_IN_PRELOAD} = 0; $INST->stop_preload } sub test2_in_preload { $INST->preload } sub test2_pid { $INST->pid } sub test2_tid { $INST->tid } sub test2_stack { $INST->stack } sub test2_ipc_wait_enable { $INST->set_no_wait(0) } sub test2_ipc_wait_disable { $INST->set_no_wait(1) } sub test2_ipc_wait_enabled { !$INST->no_wait } sub test2_is_testing_done { # No instance? VERY DONE! return 1 unless $INST; # No stack? tests must be done, it is created pretty early my $stack = $INST->stack or return 1; # Nothing on the stack, no root hub yet, likely have not started testing return 0 unless @$stack; # Stack has a slot for the root hub (see above) but it is undefined, likely # garbage collected, test is done my $root_hub = $stack->[0] or return 1; # If the root hub is ended than testing is done. return 1 if $root_hub->ended; # Looks like we are still testing! return 0; } sub test2_no_wait { $INST->set_no_wait(@_) if @_; $INST->no_wait; } sub test2_add_callback_testing_done { my $cb = shift; test2_add_callback_post_load(sub { my $stack = test2_stack(); $stack->top; # Insure we have a hub my ($hub) = Test2::API::test2_stack->all; $hub->set_active(1); $hub->follow_up($cb); }); return; } sub test2_add_callback_context_acquire { $INST->add_context_acquire_callback(@_) } sub test2_add_callback_context_aquire { $INST->add_context_acquire_callback(@_) } sub test2_add_callback_context_init { $INST->add_context_init_callback(@_) } sub test2_add_callback_context_release { $INST->add_context_release_callback(@_) } sub test2_add_callback_exit { $INST->add_exit_callback(@_) } sub test2_add_callback_post_load { $INST->add_post_load_callback(@_) } sub test2_add_callback_pre_subtest { $INST->add_pre_subtest_callback(@_) } sub test2_list_context_aquire_callbacks { @{$INST->context_acquire_callbacks} } sub test2_list_context_acquire_callbacks { @{$INST->context_acquire_callbacks} } sub test2_list_context_init_callbacks { @{$INST->context_init_callbacks} } sub test2_list_context_release_callbacks { @{$INST->context_release_callbacks} } sub test2_list_exit_callbacks { @{$INST->exit_callbacks} } sub test2_list_post_load_callbacks { @{$INST->post_load_callbacks} } sub test2_list_pre_subtest_callbacks { @{$INST->pre_subtest_callbacks} } sub test2_add_uuid_via { $INST->set_add_uuid_via(@_) if @_; $INST->add_uuid_via(); } sub test2_ipc { $INST->ipc } sub test2_has_ipc { $INST->has_ipc } sub test2_ipc_disable { $INST->ipc_disable } sub test2_ipc_disabled { $INST->ipc_disabled } sub test2_ipc_add_driver { $INST->add_ipc_driver(@_) } sub test2_ipc_drivers { @{$INST->ipc_drivers} } sub test2_ipc_polling { $INST->ipc_polling } sub test2_ipc_enable_polling { $INST->enable_ipc_polling } sub test2_ipc_disable_polling { $INST->disable_ipc_polling } sub test2_ipc_get_pending { $INST->get_ipc_pending } sub test2_ipc_set_pending { $INST->set_ipc_pending(@_) } sub test2_ipc_set_timeout { $INST->set_ipc_timeout(@_) } sub test2_ipc_get_timeout { $INST->ipc_timeout() } sub test2_ipc_enable_shm { 0 } sub test2_formatter { if ($ENV{T2_FORMATTER} && $ENV{T2_FORMATTER} =~ m/^(\+)?(.*)$/) { my $formatter = $1 ? $2 : "Test2::Formatter::$2"; my $file = pkg_to_file($formatter); require $file; return $formatter; } return $INST->formatter; } sub test2_formatters { @{$INST->formatters} } sub test2_formatter_add { $INST->add_formatter(@_) } sub test2_formatter_set { my ($formatter) = @_; croak "No formatter specified" unless $formatter; croak "Global Formatter already set" if $INST->formatter_set; $INST->set_formatter($formatter); } # Private, for use in Test2::API::Context sub _contexts_ref { $INST->contexts } sub _context_acquire_callbacks_ref { $INST->context_acquire_callbacks } sub _context_init_callbacks_ref { $INST->context_init_callbacks } sub _context_release_callbacks_ref { $INST->context_release_callbacks } sub _add_uuid_via_ref { \($INST->{Test2::API::Instance::ADD_UUID_VIA()}) } # Private, for use in Test2::IPC sub _set_ipc { $INST->set_ipc(@_) } sub context_do(&;@) { my $code = shift; my @args = @_; my $ctx = context(level => 1); my $want = wantarray; my @out; my $ok = eval { $want ? @out = $code->($ctx, @args) : defined($want) ? $out[0] = $code->($ctx, @args) : $code->($ctx, @args) ; 1; }; my $err = $@; $ctx->release; die $err unless $ok; return @out if $want; return $out[0] if defined $want; return; } sub no_context(&;$) { my ($code, $hid) = @_; $hid ||= $STACK->top->hid; my $ctx = $CONTEXTS->{$hid}; delete $CONTEXTS->{$hid}; my $ok = eval { $code->(); 1 }; my $err = $@; $CONTEXTS->{$hid} = $ctx; weaken($CONTEXTS->{$hid}); die $err unless $ok; return; }; my $UUID_VIA = _add_uuid_via_ref(); sub context { # We need to grab these before anything else to ensure they are not # changed. my ($errno, $eval_error, $child_error, $extended_error) = (0 + $!, $@, $?, $^E); my %params = (level => 0, wrapped => 0, @_); # If something is getting a context then the sync system needs to be # considered loaded... $INST->load unless $INST->{loaded}; croak "context() called, but return value is ignored" unless defined wantarray; my $stack = $params{stack} || $STACK; my $hub = $params{hub} || (@$stack ? $stack->[-1] : $stack->top); # Catch an edge case where we try to get context after the root hub has # been garbage collected resulting in a stack that has a single undef # hub if (!$hub && !exists($params{hub}) && @$stack) { my $msg = Carp::longmess("Attempt to get Test2 context after testing has completed (did you attempt a testing event after done_testing?)"); # The error message is usually masked by the global destruction, so we have to print to STDER print STDERR $msg; # Make sure this is a failure, we are probably already in END, so set $? to change the exit code $? = 1; # Now we actually die to interrupt the program flow and avoid undefined his warnings die $msg; } my $hid = $hub->{hid}; my $current = $CONTEXTS->{$hid}; $_->(\%params) for @$ACQUIRE_CBS; map $_->(\%params), @{$hub->{_context_acquire}} if $hub->{_context_acquire}; # This is for https://github.com/Test-More/test-more/issues/16 # and https://rt.perl.org/Public/Bug/Display.html?id=127774 my $phase = ${^GLOBAL_PHASE} || 'NA'; my $end_phase = $ENDING || $phase eq 'END' || $phase eq 'DESTRUCT'; my $level = 1 + $params{level}; my ($pkg, $file, $line, $sub, @other) = $end_phase ? caller(0) : caller($level); unless ($pkg || $end_phase) { confess "Could not find context at depth $level" unless $params{fudge}; ($pkg, $file, $line, $sub, @other) = caller(--$level) while ($level >= 0 && !$pkg); } my $depth = $level; $depth++ while DO_DEPTH_CHECK && !$end_phase && (!$current || $depth <= $current->{_depth} + $params{wrapped}) && caller($depth + 1); $depth -= $params{wrapped}; my $depth_ok = !DO_DEPTH_CHECK || $end_phase || !$current || $current->{_depth} < $depth; if ($current && $params{on_release} && $depth_ok) { $current->{_on_release} ||= []; push @{$current->{_on_release}} => $params{on_release}; } # I know this is ugly.... ($!, $@, $?, $^E) = ($errno, $eval_error, $child_error, $extended_error) and return bless( { %$current, _is_canon => undef, errno => $errno, eval_error => $eval_error, child_error => $child_error, _is_spawn => [$pkg, $file, $line, $sub], }, 'Test2::API::Context' ) if $current && $depth_ok; # Handle error condition of bad level if ($current) { unless (${$current->{_aborted}}) { _canon_error($current, [$pkg, $file, $line, $sub, $depth]) unless $current->{_is_canon}; _depth_error($current, [$pkg, $file, $line, $sub, $depth]) unless $depth_ok; } $current->release if $current->{_is_canon}; delete $CONTEXTS->{$hid}; } # Directly bless the object here, calling new is a noticeable performance # hit with how often this needs to be called. my $trace = bless( { frame => [$pkg, $file, $line, $sub], pid => $$, tid => get_tid(), cid => gen_uid(), hid => $hid, nested => $hub->{nested}, buffered => $hub->{buffered}, full_caller => [$pkg, $file, $line, $sub, @other], $$UUID_VIA ? ( huuid => $hub->{uuid}, uuid => ${$UUID_VIA}->('context'), ) : (), }, 'Test2::EventFacet::Trace' ); # Directly bless the object here, calling new is a noticeable performance # hit with how often this needs to be called. my $aborted = 0; $current = bless( { _aborted => \$aborted, stack => $stack, hub => $hub, trace => $trace, _is_canon => 1, _depth => $depth, errno => $errno, eval_error => $eval_error, child_error => $child_error, $params{on_release} ? (_on_release => [$params{on_release}]) : (), }, 'Test2::API::Context' ); $CONTEXTS->{$hid} = $current; weaken($CONTEXTS->{$hid}); $_->($current) for @$INIT_CBS; map $_->($current), @{$hub->{_context_init}} if $hub->{_context_init}; $params{on_init}->($current) if $params{on_init}; ($!, $@, $?, $^E) = ($errno, $eval_error, $child_error, $extended_error); return $current; } sub _depth_error { _existing_error(@_, <<" EOT"); context() was called to retrieve an existing context, however the existing context was created in a stack frame at the same, or deeper level. This usually means that a tool failed to release the context when it was finished. EOT } sub _canon_error { _existing_error(@_, <<" EOT"); context() was called to retrieve an existing context, however the existing context has an invalid internal state (!_canon_count). This should not normally happen unless something is mucking about with internals... EOT } sub _existing_error { my ($ctx, $details, $msg) = @_; my ($pkg, $file, $line, $sub, $depth) = @$details; my $oldframe = $ctx->{trace}->frame; my $olddepth = $ctx->{_depth}; # Older versions of Carp do not export longmess() function, so it needs to be called with package name my $mess = Carp::longmess(); warn <<" EOT"; $msg Old context details: File: $oldframe->[1] Line: $oldframe->[2] Tool: $oldframe->[3] Depth: $olddepth New context details: File: $file Line: $line Tool: $sub Depth: $depth Trace: $mess Removing the old context and creating a new one... EOT } sub release($;$) { $_[0]->release; return $_[1]; } sub intercept(&) { my $code = shift; my $ctx = context(); my $events = _intercept($code, deep => 0); $ctx->release; return $events; } sub intercept_deep(&) { my $code = shift; my $ctx = context(); my $events = _intercept($code, deep => 1); $ctx->release; return $events; } sub _intercept { my $code = shift; my %params = @_; my $ctx = context(); my $ipc; if (my $global_ipc = test2_ipc()) { my $driver = blessed($global_ipc); $ipc = $driver->new; } my $hub = Test2::Hub::Interceptor->new( ipc => $ipc, no_ending => 1, ); my @events; $hub->listen(sub { push @events => $_[1] }, inherit => $params{deep}); $ctx->stack->top; # Make sure there is a top hub before we begin. $ctx->stack->push($hub); my $trace = $ctx->trace; my $state = {}; $hub->clean_inherited(trace => $trace, state => $state); my ($ok, $err) = (1, undef); T2_SUBTEST_WRAPPER: { # Do not use 'try' cause it localizes __DIE__ $ok = eval { $code->(hub => $hub, context => $ctx->snapshot); 1 }; $err = $@; # They might have done 'BEGIN { skip_all => "whatever" }' if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && $err->isa('Test2::Hub::Interceptor::Terminator'))) { $ok = 1; $err = undef; } } $hub->cull; $ctx->stack->pop($hub); $hub->restore_inherited(trace => $trace, state => $state); $ctx->release; die $err unless $ok; $hub->finalize($trace, 1) if $ok && !$hub->no_ending && !$hub->ended; require Test2::API::InterceptResult; return Test2::API::InterceptResult->new_from_ref(\@events); } sub run_subtest { my ($name, $code, $params, @args) = @_; $_->($name,$code,@args) for Test2::API::test2_list_pre_subtest_callbacks(); $params = {buffered => $params} unless ref $params; my $inherit_trace = delete $params->{inherit_trace}; my $ctx = context(); my $parent = $ctx->hub; # If a parent is buffered then the child must be as well. my $buffered = $params->{buffered} || $parent->{buffered}; $ctx->note($name) unless $buffered; my $stack = $ctx->stack || $STACK; my $hub = $stack->new_hub( class => 'Test2::Hub::Subtest', %$params, buffered => $buffered, ); my @events; $hub->listen(sub { push @events => $_[1] }); if ($buffered) { if (my $format = $hub->format) { my $hide = $format->can('hide_buffered') ? $format->hide_buffered : 1; $hub->format(undef) if $hide; } } if ($inherit_trace) { my $orig = $code; $code = sub { my $base_trace = $ctx->trace; my $trace = $base_trace->snapshot(nested => 1 + $base_trace->nested); my $st_ctx = Test2::API::Context->new( trace => $trace, hub => $hub, ); $st_ctx->do_in_context($orig, @args); }; } my ($ok, $err, $finished); T2_SUBTEST_WRAPPER: { # Do not use 'try' cause it localizes __DIE__ $ok = eval { $code->(@args); 1 }; $err = $@; # They might have done 'BEGIN { skip_all => "whatever" }' if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) { $ok = undef; $err = undef; } else { $finished = 1; } } if ($params->{no_fork}) { if ($$ != $ctx->trace->pid) { warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err; exit 255; } if (get_tid() != $ctx->trace->tid) { warn $ok ? "Started new thread inside subtest, but thread never finished!\n" : $err; exit 255; } } elsif (!$parent->is_local && !$parent->ipc) { warn $ok ? "A new process or thread was started inside subtest, but IPC is not enabled!\n" : $err; exit 255; } $stack->pop($hub); my $trace = $ctx->trace; my $bailed = $hub->bailed_out; if (!$finished) { if ($bailed && !$buffered) { $ctx->bail($bailed->reason); } elsif ($bailed && $buffered) { $ok = 1; } else { my $code = $hub->exit_code; $ok = !$code; $err = "Subtest ended with exit code $code" if $code; } } $hub->finalize($trace->snapshot(huuid => $hub->uuid, hid => $hub->hid, nested => $hub->nested, buffered => $buffered), 1) if $ok && !$hub->no_ending && !$hub->ended; my $pass = $ok && $hub->is_passing; my $e = $ctx->build_event( 'Subtest', pass => $pass, name => $name, subtest_id => $hub->id, subtest_uuid => $hub->uuid, buffered => $buffered, subevents => \@events, ); my $plan_ok = $hub->check_plan; $ctx->hub->send($e); $ctx->failure_diag($e) unless $e->pass; $ctx->diag("Caught exception in subtest: $err") unless $ok; $ctx->diag("Bad subtest plan, expected " . $hub->plan . " but ran " . $hub->count) if defined($plan_ok) && !$plan_ok; $ctx->bail($bailed->reason) if $bailed && $buffered; $ctx->release; return $pass; } # There is a use-cycle between API and API/Context. Context needs to use some # API functions as the package is compiling. Test2::API::context() needs # Test2::API::Context to be loaded, but we cannot 'require' the module there as # it causes a very noticeable performance impact with how often context() is # called. require Test2::API::Context; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API - Primary interface for writing Test2 based testing tools. =head1 ***INTERNALS NOTE*** B The public methods provided will not change in backwards-incompatible ways (once there is a stable release), but the underlying implementation details might. B Currently the implementation is to create a single instance of the L Object. All class methods defer to the single instance. There is no public access to the singleton, and that is intentional. The class methods provided by this package provide the only functionality publicly exposed. This is done primarily to avoid the problems Test::Builder had by exposing its singleton. We do not want anyone to replace this singleton, rebless it, or directly muck with its internals. If you need to do something and cannot because of the restrictions placed here, then please report it as an issue. If possible, we will create a way for you to implement your functionality without exposing things that should not be exposed. =head1 DESCRIPTION This package exports all the functions necessary to write and/or verify testing tools. Using these building blocks you can begin writing test tools very quickly. You are also provided with tools that help you to test the tools you write. =head1 SYNOPSIS =head2 WRITING A TOOL The C method is your primary interface into the Test2 framework. package My::Ok; use Test2::API qw/context/; our @EXPORT = qw/my_ok/; use base 'Exporter'; # Just like ok() from Test::More sub my_ok($;$) { my ($bool, $name) = @_; my $ctx = context(); # Get a context $ctx->ok($bool, $name); $ctx->release; # Release the context return $bool; } See L for a list of methods available on the context object. =head2 TESTING YOUR TOOLS The C tool lets you temporarily intercept all events generated by the test system: use Test2::API qw/intercept/; use My::Ok qw/my_ok/; my $events = intercept { # These events are not displayed my_ok(1, "pass"); my_ok(0, "fail"); }; As of version 1.302178 this now returns an arrayref that is also an instance of L. See the L documentation for details on how to best use it. =head2 OTHER API FUNCTIONS use Test2::API qw{ test2_init_done test2_stack test2_set_is_end test2_get_is_end test2_ipc test2_formatter_set test2_formatter test2_is_testing_done }; my $init = test2_init_done(); my $stack = test2_stack(); my $ipc = test2_ipc(); test2_formatter_set($FORMATTER) my $formatter = test2_formatter(); ... And others ... =head1 MAIN API EXPORTS All exports are optional. You must specify subs to import. use Test2::API qw/context intercept run_subtest/; This is the list of exports that are most commonly needed. If you are simply writing a tool, then this is probably all you need. If you need something and you cannot find it here, then you can also look at L. These exports lack the 'test2_' prefix because of how important/common they are. Exports in the L section have the 'test2_' prefix to ensure they stand out. =head2 context(...) Usage: =over 4 =item $ctx = context() =item $ctx = context(%params) =back The C function will always return the current context. If there is already a context active, it will be returned. If there is not an active context, one will be generated. When a context is generated it will default to using the file and line number where the currently running sub was called from. Please see L for important rules about what you can and cannot do with a context once it is obtained. B This function will throw an exception if you ignore the context object it returns. B On perls 5.14+ a depth check is used to insure there are no context leaks. This cannot be safely done on older perls due to L You can forcefully enable it either by setting C<$ENV{T2_CHECK_DEPTH} = 1> or C<$Test2::API::DO_DEPTH_CHECK = 1> B loading L. =head3 OPTIONAL PARAMETERS All parameters to C are optional. =over 4 =item level => $int If you must obtain a context in a sub deeper than your entry point you can use this to tell it how many EXTRA stack frames to look back. If this option is not provided the default of C<0> is used. sub third_party_tool { my $sub = shift; ... # Does not obtain a context $sub->(); ... } third_party_tool(sub { my $ctx = context(level => 1); ... $ctx->release; }); =item wrapped => $int Use this if you need to write your own tool that wraps a call to C with the intent that it should return a context object. sub my_context { my %params = ( wrapped => 0, @_ ); $params{wrapped}++; my $ctx = context(%params); ... return $ctx; } sub my_tool { my $ctx = my_context(); ... $ctx->release; } If you do not do this, then tools you call that also check for a context will notice that the context they grabbed was created at the same stack depth, which will trigger protective measures that warn you and destroy the existing context. =item stack => $stack Normally C looks at the global hub stack. If you are maintaining your own L instance you may pass it in to be used instead of the global one. =item hub => $hub Use this parameter if you want to obtain the context for a specific hub instead of whatever one happens to be at the top of the stack. =item on_init => sub { ... } This lets you provide a callback sub that will be called B if your call to C generated a new context. The callback B be called if C is returning an existing context. The only argument passed into the callback will be the context object itself. sub foo { my $ctx = context(on_init => sub { 'will run' }); my $inner = sub { # This callback is not run since we are getting the existing # context from our parent sub. my $ctx = context(on_init => sub { 'will NOT run' }); $ctx->release; } $inner->(); $ctx->release; } =item on_release => sub { ... } This lets you provide a callback sub that will be called when the context instance is released. This callback will be added to the returned context even if an existing context is returned. If multiple calls to context add callbacks, then all will be called in reverse order when the context is finally released. sub foo { my $ctx = context(on_release => sub { 'will run second' }); my $inner = sub { my $ctx = context(on_release => sub { 'will run first' }); # Neither callback runs on this release $ctx->release; } $inner->(); # Both callbacks run here. $ctx->release; } =back =head2 release($;$) Usage: =over 4 =item release $ctx; =item release $ctx, ...; =back This is intended as a shortcut that lets you release your context and return a value in one statement. This function will get your context, and an optional return value. It will release your context, then return your value. Scalar context is always assumed. sub tool { my $ctx = context(); ... return release $ctx, 1; } This tool is most useful when you want to return the value you get from calling a function that needs to see the current context: my $ctx = context(); my $out = some_tool(...); $ctx->release; return $out; We can combine the last 3 lines of the above like so: my $ctx = context(); release $ctx, some_tool(...); =head2 context_do(&;@) Usage: sub my_tool { context_do { my $ctx = shift; my (@args) = @_; $ctx->ok(1, "pass"); ... # No need to call $ctx->release, done for you on scope exit. } @_; } Using this inside your test tool takes care of a lot of boilerplate for you. It will ensure a context is acquired. It will capture and rethrow any exception. It will insure the context is released when you are done. It preserves the subroutine call context (array, scalar, void). This is the safest way to write a test tool. The only two downsides to this are a slight performance decrease, and some extra indentation in your source. If the indentation is a problem for you then you can take a peek at the next section. =head2 no_context(&;$) Usage: =over 4 =item no_context { ... }; =item no_context { ... } $hid; sub my_tool(&) { my $code = shift; my $ctx = context(); ... no_context { # Things in here will not see our current context, they get a new # one. $code->(); }; ... $ctx->release; }; =back This tool will hide a context for the provided block of code. This means any tools run inside the block will get a completely new context if they acquire one. The new context will be inherited by tools nested below the one that acquired it. This will normally hide the current context for the top hub. If you need to hide the context for a different hub you can pass in the optional C<$hid> parameter. =head2 intercept(&) Usage: my $events = intercept { ok(1, "pass"); ok(0, "fail"); ... }; This function takes a codeblock as its only argument, and it has a prototype. It will execute the codeblock, intercepting any generated events in the process. It will return an array reference with all the generated event objects. All events should be subclasses of L. As of version 1.302178 the events array that is returned is blssed as an L instance. L Provides a helpful interface for filtering and/or inspecting the events list overall, or individual events within the list. This is intended to help you test your test code. This is not intended for people simply writing tests. =head2 run_subtest(...) Usage: run_subtest($NAME, \&CODE, $BUFFERED, @ARGS) # or run_subtest($NAME, \&CODE, \%PARAMS, @ARGS) This will run the provided codeblock with the args in C<@args>. This codeblock will be run as a subtest. A subtest is an isolated test state that is condensed into a single L event, which contains all events generated inside the subtest. =head3 ARGUMENTS: =over 4 =item $NAME The name of the subtest. =item \&CODE The code to run inside the subtest. =item $BUFFERED or \%PARAMS If this is a simple scalar then it will be treated as a boolean for the 'buffered' setting. If this is a hash reference then it will be used as a parameters hash. The param hash will be used for hub construction (with the specified keys removed). Keys that are removed and used by run_subtest: =over 4 =item 'buffered' => $bool Toggle buffered status. =item 'inherit_trace' => $bool Normally the subtest hub is pushed and the sub is allowed to generate its own root context for the hub. When this setting is turned on a root context will be created for the hub that shares the same trace as the current context. Set this to true if your tool is producing subtests without user-specified subs. =item 'no_fork' => $bool Defaults to off. Normally forking inside a subtest will actually fork the subtest, resulting in 2 final subtest events. This parameter will turn off that behavior, only the original process/thread will return a final subtest event. =back =item @ARGS Any extra arguments you want passed into the subtest code. =back =head3 BUFFERED VS UNBUFFERED (OR STREAMED) Normally all events inside and outside a subtest are sent to the formatter immediately by the hub. Sometimes it is desirable to hold off sending events within a subtest until the subtest is complete. This usually depends on the formatter being used. =over 4 =item Things not effected by this flag In both cases events are generated and stored in an array. This array is eventually used to populate the C attribute on the L event that is generated at the end of the subtest. This flag has no effect on this part, it always happens. At the end of the subtest, the final L event is sent to the formatter. =item Things that are effected by this flag The C attribute of the L event will be set to the value of this flag. This means any formatter, listener, etc which looks at the event will know if it was buffered. =item Things that are formatter dependant Events within a buffered subtest may or may not be sent to the formatter as they happen. If a formatter fails to specify then the default is to B the events as they are generated, instead the formatter can pull them from the C attribute. A formatter can specify by implementing the C method. If this method returns true then events generated inside a buffered subtest will not be sent independently of the final subtest event. =back An example of how this is used is the L formatter. For unbuffered subtests the events are rendered as they are generated. At the end of the subtest, the final subtest event is rendered, but the C attribute is ignored. For buffered subtests the opposite occurs, the events are NOT rendered as they are generated, instead the C attribute is used to render them all at once. This is useful when running subtests tests in parallel, since without it the output from subtests would be interleaved together. =head1 OTHER API EXPORTS Exports in this section are not commonly needed. These all have the 'test2_' prefix to help ensure they stand out. You should look at the L section before looking here. This section is one where "Great power comes with great responsibility". It is possible to break things badly if you are not careful with these. All exports are optional. You need to list which ones you want at import time: use Test2::API qw/test2_init_done .../; =head2 STATUS AND INITIALIZATION STATE These provide access to internal state and object instances. =over 4 =item $bool = test2_init_done() This will return true if the stack and IPC instances have already been initialized. It will return false if they have not. Init happens as late as possible. It happens as soon as a tool requests the IPC instance, the formatter, or the stack. =item $bool = test2_load_done() This will simply return the boolean value of the loaded flag. If Test2 has finished loading this will be true, otherwise false. Loading is considered complete the first time a tool requests a context. =item test2_set_is_end() =item test2_set_is_end($bool) This is used to toggle Test2's belief that the END phase has already started. With no arguments this will set it to true. With arguments it will set it to the first argument's value. This is used to prevent the use of C in END blocks which can cause segfaults. This is only necessary in some persistent environments that may have multiple END phases. =item $bool = test2_get_is_end() Check if Test2 believes it is the END phase. =item $stack = test2_stack() This will return the global L instance. If this has not yet been initialized it will be initialized now. =item $bool = test2_is_testing_done() This will return true if testing is complete and no other events should be sent. This is useful in things like warning handlers where you might want to turn warnings into events, but need them to start acting like normal warnings when testing is done. $SIG{__WARN__} = sub { my ($warning) = @_; if (test2_is_testing_done()) { warn @_; } else { my $ctx = context(); ... $ctx->release } } =item test2_ipc_disable Disable IPC. =item $bool = test2_ipc_diabled Check if IPC is disabled. =item test2_ipc_wait_enable() =item test2_ipc_wait_disable() =item $bool = test2_ipc_wait_enabled() These can be used to turn IPC waiting on and off, or check the current value of the flag. Waiting is turned on by default. Waiting will cause the parent process/thread to wait until all child processes and threads are finished before exiting. You will almost never want to turn this off. =item $bool = test2_no_wait() =item test2_no_wait($bool) B: This is a confusing interface, it is better to use C, C and C. This can be used to get/set the no_wait status. Waiting is turned on by default. Waiting will cause the parent process/thread to wait until all child processes and threads are finished before exiting. You will almost never want to turn this off. =item $fh = test2_stdout() =item $fh = test2_stderr() These functions return the filehandles that test output should be written to. They are primarily useful when writing a custom formatter and code that turns events into actual output (TAP, etc.). They will return a dupe of the original filehandles that formatted output can be sent to regardless of whatever state the currently running test may have left STDOUT and STDERR in. =item test2_reset_io() Re-dupe the internal filehandles returned by C and C from the current STDOUT and STDERR. You shouldn't need to do this except in very peculiar situations (for example, you're testing a new formatter and you need control over where the formatter is sending its output.) =back =head2 BEHAVIOR HOOKS These are hooks that allow you to add custom behavior to actions taken by Test2 and tools built on top of it. =over 4 =item test2_add_callback_exit(sub { ... }) This can be used to add a callback that is called after all testing is done. This is too late to add additional results, the main use of this callback is to set the exit code. test2_add_callback_exit( sub { my ($context, $exit, \$new_exit) = @_; ... } ); The C<$context> passed in will be an instance of L. The C<$exit> argument will be the original exit code before anything modified it. C<$$new_exit> is a reference to the new exit code. You may modify this to change the exit code. Please note that C<$$new_exit> may already be different from C<$exit> =item test2_add_callback_post_load(sub { ... }) Add a callback that will be called when Test2 is finished loading. This means the callback will be run once, the first time a context is obtained. If Test2 has already finished loading then the callback will be run immediately. =item test2_add_callback_testing_done(sub { ... }) This adds your coderef as a follow-up to the root hub after Test2 is finished loading. This is essentially a helper to do the following: test2_add_callback_post_load(sub { my $stack = test2_stack(); $stack->top; # Insure we have a hub my ($hub) = Test2::API::test2_stack->all; $hub->set_active(1); $hub->follow_up(sub { ... }); # <-- Your coderef here }); =item test2_add_callback_context_acquire(sub { ... }) Add a callback that will be called every time someone tries to acquire a context. This will be called on EVERY call to C. It gets a single argument, a reference to the hash of parameters being used the construct the context. This is your chance to change the parameters by directly altering the hash. test2_add_callback_context_acquire(sub { my $params = shift; $params->{level}++; }); This is a very scary API function. Please do not use this unless you need to. This is here for L and backwards compatibility. This has you directly manipulate the hash instead of returning a new one for performance reasons. =item test2_add_callback_context_init(sub { ... }) Add a callback that will be called every time a new context is created. The callback will receive the newly created context as its only argument. =item test2_add_callback_context_release(sub { ... }) Add a callback that will be called every time a context is released. The callback will receive the released context as its only argument. =item test2_add_callback_pre_subtest(sub { ... }) Add a callback that will be called every time a subtest is going to be run. The callback will receive the subtest name, coderef, and any arguments. =item @list = test2_list_context_acquire_callbacks() Return all the context acquire callback references. =item @list = test2_list_context_init_callbacks() Returns all the context init callback references. =item @list = test2_list_context_release_callbacks() Returns all the context release callback references. =item @list = test2_list_exit_callbacks() Returns all the exit callback references. =item @list = test2_list_post_load_callbacks() Returns all the post load callback references. =item @list = test2_list_pre_subtest_callbacks() Returns all the pre-subtest callback references. =item test2_add_uuid_via(sub { ... }) =item $sub = test2_add_uuid_via() This allows you to provide a UUID generator. If provided UUIDs will be attached to all events, hubs, and contexts. This is useful for storing, tracking, and linking these objects. The sub you provide should always return a unique identifier. Most things will expect a proper UUID string, however nothing in Test2::API enforces this. The sub will receive exactly 1 argument, the type of thing being tagged 'context', 'hub', or 'event'. In the future additional things may be tagged, in which case new strings will be passed in. These are purely informative, you can (and usually should) ignore them. =back =head2 IPC AND CONCURRENCY These let you access, or specify, the IPC system internals. =over 4 =item $bool = test2_has_ipc() Check if IPC is enabled. =item $ipc = test2_ipc() This will return the global L instance. If this has not yet been initialized it will be initialized now. =item test2_ipc_add_driver($DRIVER) Add an IPC driver to the list. This will add the driver to the start of the list. =item @drivers = test2_ipc_drivers() Get the list of IPC drivers. =item $bool = test2_ipc_polling() Check if polling is enabled. =item test2_ipc_enable_polling() Turn on polling. This will cull events from other processes and threads every time a context is created. =item test2_ipc_disable_polling() Turn off IPC polling. =item test2_ipc_enable_shm() Legacy, this is currently a no-op that returns 0; =item test2_ipc_set_pending($uniq_val) Tell other processes and events that an event is pending. C<$uniq_val> should be a unique value no other thread/process will generate. B After calling this C will return 1. This is intentional, and not avoidable. =item $pending = test2_ipc_get_pending() This returns -1 if there is no way to check (assume yes) This returns 0 if there are (most likely) no pending events. This returns 1 if there are (likely) pending events. Upon return it will reset, nothing else will be able to see that there were pending events. =item $timeout = test2_ipc_get_timeout() =item test2_ipc_set_timeout($timeout) Get/Set the timeout value for the IPC system. This timeout is how long the IPC system will wait for child processes and threads to finish before aborting. The default value is C<30> seconds. =back =head2 MANAGING FORMATTERS These let you access, or specify, the formatters that can/should be used. =over 4 =item $formatter = test2_formatter This will return the global formatter class. This is not an instance. By default the formatter is set to L. You can override this default using the C environment variable. Normally 'Test2::Formatter::' is prefixed to the value in the environment variable: $ T2_FORMATTER='TAP' perl test.t # Use the Test2::Formatter::TAP formatter $ T2_FORMATTER='Foo' perl test.t # Use the Test2::Formatter::Foo formatter If you want to specify a full module name you use the '+' prefix: $ T2_FORMATTER='+Foo::Bar' perl test.t # Use the Foo::Bar formatter =item test2_formatter_set($class_or_instance) Set the global formatter class. This can only be set once. B This will override anything specified in the 'T2_FORMATTER' environment variable. =item @formatters = test2_formatters() Get a list of all loaded formatters. =item test2_formatter_add($class_or_instance) Add a formatter to the list. Last formatter added is used at initialization. If this is called after initialization a warning will be issued. =back =head1 OTHER EXAMPLES See the C directory included in this distribution. =head1 SEE ALSO L - Detailed documentation of the context object. L - The IPC system used for threading/fork support. L - Formatters such as TAP live here. L - Events live in this namespace. L - All events eventually funnel through a hub. Custom hubs are how C and C are implemented. =head1 MAGIC This package has an END block. This END block is responsible for setting the exit code based on the test results. This end block also calls the callbacks that can be added to this package. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ÜÓÏqqperl5/Test2/Formatter.pmnuÏÃ6Ç$package Test2::Formatter; use strict; use warnings; our $VERSION = '1.302183'; my %ADDED; sub import { my $class = shift; return if $class eq __PACKAGE__; return if $ADDED{$class}++; require Test2::API; Test2::API::test2_formatter_add($class); } sub new_root { my $class = shift; return $class->new(@_); } sub supports_tables { 0 } sub hide_buffered { 1 } sub terminate { } sub finalize { } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Formatter - Namespace for formatters. =head1 DESCRIPTION This is the namespace for formatters. This is an empty package. =head1 CREATING FORMATTERS A formatter is any package or object with a C method. package Test2::Formatter::Foo; use strict; use warnings; sub write { my $self_or_class = shift; my ($event, $assert_num) = @_; ... } sub hide_buffered { 1 } sub terminate { } sub finalize { } sub supports_tables { return $BOOL } sub new_root { my $class = shift; ... $class->new(@_); } 1; The C method is a method, so it either gets a class or instance. The two arguments are the C<$event> object it should record, and the C<$assert_num> which is the number of the current assertion (ok), or the last assertion if this event is not itself an assertion. The assertion number may be any integer 0 or greater, and may be undefined in some cases. The C method must return a boolean. This is used to tell buffered subtests whether or not to send it events as they are being buffered. See L for more information. The C and C methods are optional methods called that you can implement if the format you're generating needs to handle these cases, for example if you are generating XML and need close open tags. The C method is called when an event's C method returns true, for example when a L has a C<'skip_all'> plan, or when a L event is sent. The C method is passed a single argument, the L object which triggered the terminate. The C method is always the last thing called on the formatter, I<< except when C is called for a Bail event >>. It is passed the following arguments: The C method should be true if the formatter supports directly rendering table data from the C facets. This is a newer feature and many older formatters may not support it. When not supported the formatter falls back to rendering C instead of the C
data. The C method is used when constructing a root formatter. The default is to just delegate to the regular C method, most formatters can ignore this. =over 4 =item * The number of tests that were planned =item * The number of tests actually seen =item * The number of tests which failed =item * A boolean indicating whether or not the test suite passed =item * A boolean indicating whether or not this call is for a subtest =back The C method is called when C Initializes the root hub for the first time. Most formatters will simply have this call C<< $class->new >>, which is the default behavior. Some formatters however may want to take extra action during construction of the root formatter, this is where they can do that. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!äÞTݦ ¦ perl5/Test2/Hub/Interceptor.pmnuÏÃ6Ç$package Test2::Hub::Interceptor; use strict; use warnings; our $VERSION = '1.302183'; use Test2::Hub::Interceptor::Terminator(); BEGIN { require Test2::Hub; our @ISA = qw(Test2::Hub) } use Test2::Util::HashBase; sub init { my $self = shift; $self->SUPER::init(); $self->{+NESTED} = 0; } sub inherit { my $self = shift; my ($from, %params) = @_; $self->{+NESTED} = 0; if ($from->{+IPC} && !$self->{+IPC} && !exists($params{ipc})) { my $ipc = $from->{+IPC}; $self->{+IPC} = $ipc; $ipc->add_hub($self->{+HID}); } if (my $ls = $from->{+_LISTENERS}) { push @{$self->{+_LISTENERS}} => grep { $_->{intercept_inherit} } @$ls; } if (my $pfs = $from->{+_PRE_FILTERS}) { push @{$self->{+_PRE_FILTERS}} => grep { $_->{intercept_inherit} } @$pfs; } if (my $fs = $from->{+_FILTERS}) { push @{$self->{+_FILTERS}} => grep { $_->{intercept_inherit} } @$fs; } } sub clean_inherited { my $self = shift; my %params = @_; my @sets = ( $self->{+_LISTENERS}, $self->{+_PRE_FILTERS}, $self->{+_FILTERS}, ); for my $set (@sets) { next unless $set; for my $i (@$set) { my $cbs = $i->{intercept_inherit} or next; next unless ref($cbs) eq 'HASH'; my $cb = $cbs->{clean} or next; $cb->(%params); } } } sub restore_inherited { my $self = shift; my %params = @_; my @sets = ( $self->{+_FILTERS}, $self->{+_PRE_FILTERS}, $self->{+_LISTENERS}, ); for my $set (@sets) { next unless $set; for my $i (@$set) { my $cbs = $i->{intercept_inherit} or next; next unless ref($cbs) eq 'HASH'; my $cb = $cbs->{restore} or next; $cb->(%params); } } } sub terminate { my $self = shift; my ($code) = @_; eval { no warnings 'exiting'; last T2_SUBTEST_WRAPPER; }; my $err = $@; # Fallback die bless(\$err, 'Test2::Hub::Interceptor::Terminator'); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Hub::Interceptor - Hub used by interceptor to grab results. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!.4ß=P P perl5/Test2/Hub/Subtest.pmnuÏÃ6Ç$package Test2::Hub::Subtest; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Hub; our @ISA = qw(Test2::Hub) } use Test2::Util::HashBase qw/nested exit_code manual_skip_all/; use Test2::Util qw/get_tid/; sub is_subtest { 1 } sub inherit { my $self = shift; my ($from) = @_; $self->SUPER::inherit($from); $self->{+NESTED} = $from->nested + 1; } { # Legacy no warnings 'once'; *ID = \&Test2::Hub::HID; *id = \&Test2::Hub::hid; *set_id = \&Test2::Hub::set_hid; } sub send { my $self = shift; my ($e) = @_; my $out = $self->SUPER::send($e); return $out if $self->{+MANUAL_SKIP_ALL}; my $f = $e->facet_data; my $plan = $f->{plan} or return $out; return $out unless $plan->{skip}; my $trace = $f->{trace} or die "Missing Trace!"; return $out unless $trace->{pid} != $self->pid || $trace->{tid} != $self->tid; no warnings 'exiting'; last T2_SUBTEST_WRAPPER; } sub terminate { my $self = shift; my ($code, $e, $f) = @_; $self->set_exit_code($code); return if $self->{+MANUAL_SKIP_ALL}; $f ||= $e->facet_data; if(my $plan = $f->{plan}) { my $trace = $f->{trace} or die "Missing Trace!"; return if $plan->{skip} && ($trace->{pid} != $$ || $trace->{tid} != get_tid); } no warnings 'exiting'; last T2_SUBTEST_WRAPPER; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Hub::Subtest - Hub used by subtests =head1 DESCRIPTION Subtests make use of this hub to route events. =head1 TOGGLES =over 4 =item $bool = $hub->manual_skip_all =item $hub->set_manual_skip_all($bool) The default is false. Normally a skip-all plan event will cause a subtest to stop executing. This is accomplished via C to a label inside the subtest code. Most of the time this is perfectly fine. There are times however where this flow control causes bad things to happen. This toggle lets you turn off the abort logic for the hub. When this is toggled to true B are responsible for ensuring no additional events are generated. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!CdöIàà)perl5/Test2/Hub/Interceptor/Terminator.pmnuÏÃ6Ç$package Test2::Hub::Interceptor::Terminator; use strict; use warnings; our $VERSION = '1.302183'; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Hub::Interceptor::Terminator - Exception class used by Test2::Hub::Interceptor =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!¨Xv ,Y,Yperl5/Test2/Hub.pmnuÏÃ6Ç$package Test2::Hub; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/carp croak confess/; use Test2::Util qw/get_tid gen_uid/; use Scalar::Util qw/weaken/; use List::Util qw/first/; use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/; use Test2::Util::HashBase qw{ pid tid hid ipc nested buffered no_ending _filters _pre_filters _listeners _follow_ups _formatter _context_acquire _context_init _context_release uuid active count failed ended bailed_out _passing _plan skip_reason }; my $UUID_VIA; sub init { my $self = shift; $self->{+PID} = $$; $self->{+TID} = get_tid(); $self->{+HID} = gen_uid(); $UUID_VIA ||= Test2::API::_add_uuid_via_ref(); $self->{+UUID} = ${$UUID_VIA}->('hub') if $$UUID_VIA; $self->{+NESTED} = 0 unless defined $self->{+NESTED}; $self->{+BUFFERED} = 0 unless defined $self->{+BUFFERED}; $self->{+COUNT} = 0; $self->{+FAILED} = 0; $self->{+_PASSING} = 1; if (my $formatter = delete $self->{formatter}) { $self->format($formatter); } if (my $ipc = $self->{+IPC}) { $ipc->add_hub($self->{+HID}); } } sub is_subtest { 0 } sub _tb_reset { my $self = shift; # Nothing to do return if $self->{+PID} == $$ && $self->{+TID} == get_tid(); $self->{+PID} = $$; $self->{+TID} = get_tid(); $self->{+HID} = gen_uid(); if (my $ipc = $self->{+IPC}) { $ipc->add_hub($self->{+HID}); } } sub reset_state { my $self = shift; $self->{+COUNT} = 0; $self->{+FAILED} = 0; $self->{+_PASSING} = 1; delete $self->{+_PLAN}; delete $self->{+ENDED}; delete $self->{+BAILED_OUT}; delete $self->{+SKIP_REASON}; } sub inherit { my $self = shift; my ($from, %params) = @_; $self->{+NESTED} ||= 0; $self->{+_FORMATTER} = $from->{+_FORMATTER} unless $self->{+_FORMATTER} || exists($params{formatter}); if ($from->{+IPC} && !$self->{+IPC} && !exists($params{ipc})) { my $ipc = $from->{+IPC}; $self->{+IPC} = $ipc; $ipc->add_hub($self->{+HID}); } if (my $ls = $from->{+_LISTENERS}) { push @{$self->{+_LISTENERS}} => grep { $_->{inherit} } @$ls; } if (my $pfs = $from->{+_PRE_FILTERS}) { push @{$self->{+_PRE_FILTERS}} => grep { $_->{inherit} } @$pfs; } if (my $fs = $from->{+_FILTERS}) { push @{$self->{+_FILTERS}} => grep { $_->{inherit} } @$fs; } } sub format { my $self = shift; my $old = $self->{+_FORMATTER}; ($self->{+_FORMATTER}) = @_ if @_; return $old; } sub is_local { my $self = shift; return $$ == $self->{+PID} && get_tid() == $self->{+TID}; } sub listen { my $self = shift; my ($sub, %params) = @_; carp "Useless addition of a listener in a child process or thread!" if $$ != $self->{+PID} || get_tid() != $self->{+TID}; croak "listen only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_LISTENERS}} => { %params, code => $sub }; $sub; # Intentional return. } sub unlisten { my $self = shift; carp "Useless removal of a listener in a child process or thread!" if $$ != $self->{+PID} || get_tid() != $self->{+TID}; my %subs = map {$_ => $_} @_; @{$self->{+_LISTENERS}} = grep { !$subs{$_->{code}} } @{$self->{+_LISTENERS}}; } sub filter { my $self = shift; my ($sub, %params) = @_; carp "Useless addition of a filter in a child process or thread!" if $$ != $self->{+PID} || get_tid() != $self->{+TID}; croak "filter only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_FILTERS}} => { %params, code => $sub }; $sub; # Intentional Return } sub unfilter { my $self = shift; carp "Useless removal of a filter in a child process or thread!" if $$ != $self->{+PID} || get_tid() != $self->{+TID}; my %subs = map {$_ => $_} @_; @{$self->{+_FILTERS}} = grep { !$subs{$_->{code}} } @{$self->{+_FILTERS}}; } sub pre_filter { my $self = shift; my ($sub, %params) = @_; croak "pre_filter only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_PRE_FILTERS}} => { %params, code => $sub }; $sub; # Intentional Return } sub pre_unfilter { my $self = shift; my %subs = map {$_ => $_} @_; @{$self->{+_PRE_FILTERS}} = grep { !$subs{$_->{code}} } @{$self->{+_PRE_FILTERS}}; } sub follow_up { my $self = shift; my ($sub) = @_; carp "Useless addition of a follow-up in a child process or thread!" if $$ != $self->{+PID} || get_tid() != $self->{+TID}; croak "follow_up only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_FOLLOW_UPS}} => $sub; } *add_context_aquire = \&add_context_acquire; sub add_context_acquire { my $self = shift; my ($sub) = @_; croak "add_context_acquire only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_CONTEXT_ACQUIRE}} => $sub; $sub; # Intentional return. } *remove_context_aquire = \&remove_context_acquire; sub remove_context_acquire { my $self = shift; my %subs = map {$_ => $_} @_; @{$self->{+_CONTEXT_ACQUIRE}} = grep { !$subs{$_} == $_ } @{$self->{+_CONTEXT_ACQUIRE}}; } sub add_context_init { my $self = shift; my ($sub) = @_; croak "add_context_init only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_CONTEXT_INIT}} => $sub; $sub; # Intentional return. } sub remove_context_init { my $self = shift; my %subs = map {$_ => $_} @_; @{$self->{+_CONTEXT_INIT}} = grep { !$subs{$_} == $_ } @{$self->{+_CONTEXT_INIT}}; } sub add_context_release { my $self = shift; my ($sub) = @_; croak "add_context_release only takes coderefs for arguments, got '$sub'" unless ref $sub && ref $sub eq 'CODE'; push @{$self->{+_CONTEXT_RELEASE}} => $sub; $sub; # Intentional return. } sub remove_context_release { my $self = shift; my %subs = map {$_ => $_} @_; @{$self->{+_CONTEXT_RELEASE}} = grep { !$subs{$_} == $_ } @{$self->{+_CONTEXT_RELEASE}}; } sub send { my $self = shift; my ($e) = @_; $e->eid; $e->add_hub( { details => ref($self), buffered => $self->{+BUFFERED}, hid => $self->{+HID}, nested => $self->{+NESTED}, pid => $self->{+PID}, tid => $self->{+TID}, uuid => $self->{+UUID}, ipc => $self->{+IPC} ? 1 : 0, } ); $e->set_uuid(${$UUID_VIA}->('event')) if $$UUID_VIA; if ($self->{+_PRE_FILTERS}) { for (@{$self->{+_PRE_FILTERS}}) { $e = $_->{code}->($self, $e); return unless $e; } } my $ipc = $self->{+IPC} || return $self->process($e); if($e->global) { $ipc->send($self->{+HID}, $e, 'GLOBAL'); return $self->process($e); } return $ipc->send($self->{+HID}, $e) if $$ != $self->{+PID} || get_tid() != $self->{+TID}; $self->process($e); } sub process { my $self = shift; my ($e) = @_; if ($self->{+_FILTERS}) { for (@{$self->{+_FILTERS}}) { $e = $_->{code}->($self, $e); return unless $e; } } # Optimize the most common case my $type = ref($e); if ($type eq 'Test2::Event::Pass' || ($type eq 'Test2::Event::Ok' && $e->{pass})) { my $count = ++($self->{+COUNT}); $self->{+_FORMATTER}->write($e, $count) if $self->{+_FORMATTER}; if ($self->{+_LISTENERS}) { $_->{code}->($self, $e, $count) for @{$self->{+_LISTENERS}}; } return $e; } my $f = $e->facet_data; my $fail = 0; $fail = 1 if $f->{assert} && !$f->{assert}->{pass}; $fail = 1 if $f->{errors} && grep { $_->{fail} } @{$f->{errors}}; $fail = 0 if $f->{amnesty}; $self->{+COUNT}++ if $f->{assert}; $self->{+FAILED}++ if $fail && $f->{assert}; $self->{+_PASSING} = 0 if $fail; my $code = $f->{control} ? $f->{control}->{terminate} : undef; my $count = $self->{+COUNT}; if (my $plan = $f->{plan}) { if ($plan->{skip}) { $self->plan('SKIP'); $self->set_skip_reason($plan->{details} || 1); $code ||= 0; } elsif ($plan->{none}) { $self->plan('NO PLAN'); } else { $self->plan($plan->{count}); } } $e->callback($self) if $f->{control} && $f->{control}->{has_callback}; $self->{+_FORMATTER}->write($e, $count, $f) if $self->{+_FORMATTER}; if ($self->{+_LISTENERS}) { $_->{code}->($self, $e, $count, $f) for @{$self->{+_LISTENERS}}; } if ($f->{control} && $f->{control}->{halt}) { $code ||= 255; $self->set_bailed_out($e); } if (defined $code) { $self->{+_FORMATTER}->terminate($e, $f) if $self->{+_FORMATTER}; $self->terminate($code, $e, $f); } return $e; } sub terminate { my $self = shift; my ($code) = @_; exit($code); } sub cull { my $self = shift; my $ipc = $self->{+IPC} || return; return if $self->{+PID} != $$ || $self->{+TID} != get_tid(); # No need to do IPC checks on culled events $self->process($_) for $ipc->cull($self->{+HID}); } sub finalize { my $self = shift; my ($trace, $do_plan) = @_; $self->cull(); my $plan = $self->{+_PLAN}; my $count = $self->{+COUNT}; my $failed = $self->{+FAILED}; my $active = $self->{+ACTIVE}; # return if NOTHING was done. unless ($active || $do_plan || defined($plan) || $count || $failed) { $self->{+_FORMATTER}->finalize($plan, $count, $failed, 0, $self->is_subtest) if $self->{+_FORMATTER}; return; } unless ($self->{+ENDED}) { if ($self->{+_FOLLOW_UPS}) { $_->($trace, $self) for reverse @{$self->{+_FOLLOW_UPS}}; } # These need to be refreshed now $plan = $self->{+_PLAN}; $count = $self->{+COUNT}; $failed = $self->{+FAILED}; if (($plan && $plan eq 'NO PLAN') || ($do_plan && !$plan)) { $self->send( Test2::Event::Plan->new( trace => $trace, max => $count, ) ); } $plan = $self->{+_PLAN}; } my $frame = $trace->frame; if($self->{+ENDED}) { my (undef, $ffile, $fline) = @{$self->{+ENDED}}; my (undef, $sfile, $sline) = @$frame; die <<" EOT" Test already ended! First End: $ffile line $fline Second End: $sfile line $sline EOT } $self->{+ENDED} = $frame; my $pass = $self->is_passing(); # Generate the final boolean. $self->{+_FORMATTER}->finalize($plan, $count, $failed, $pass, $self->is_subtest) if $self->{+_FORMATTER}; return $pass; } sub is_passing { my $self = shift; ($self->{+_PASSING}) = @_ if @_; # If we already failed just return 0. my $pass = $self->{+_PASSING} or return 0; return $self->{+_PASSING} = 0 if $self->{+FAILED}; my $count = $self->{+COUNT}; my $ended = $self->{+ENDED}; my $plan = $self->{+_PLAN}; return $pass if !$count && $plan && $plan =~ m/^SKIP$/; return $self->{+_PASSING} = 0 if $ended && (!$count || !$plan); return $pass unless $plan && $plan =~ m/^\d+$/; if ($ended) { return $self->{+_PASSING} = 0 if $count != $plan; } else { return $self->{+_PASSING} = 0 if $count > $plan; } return $pass; } sub plan { my $self = shift; return $self->{+_PLAN} unless @_; my ($plan) = @_; confess "You cannot unset the plan" unless defined $plan; confess "You cannot change the plan" if $self->{+_PLAN} && $self->{+_PLAN} !~ m/^NO PLAN$/; confess "'$plan' is not a valid plan! Plan must be an integer greater than 0, 'NO PLAN', or 'SKIP'" unless $plan =~ m/^(\d+|NO PLAN|SKIP)$/; $self->{+_PLAN} = $plan; } sub check_plan { my $self = shift; return undef unless $self->{+ENDED}; my $plan = $self->{+_PLAN} || return undef; return 1 if $plan !~ m/^\d+$/; return 1 if $plan == $self->{+COUNT}; return 0; } sub DESTROY { my $self = shift; my $ipc = $self->{+IPC} || return; return unless $$ == $self->{+PID}; return unless get_tid() == $self->{+TID}; $ipc->drop_hub($self->{+HID}); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Hub - The conduit through which all events flow. =head1 SYNOPSIS use Test2::Hub; my $hub = Test2::Hub->new(); $hub->send(...); =head1 DESCRIPTION The hub is the place where all events get processed and handed off to the formatter. The hub also tracks test state, and provides several hooks into the event pipeline. =head1 COMMON TASKS =head2 SENDING EVENTS $hub->send($event) The C method is used to issue an event to the hub. This method will handle thread/fork sync, filters, listeners, TAP output, etc. =head2 ALTERING OR REMOVING EVENTS You can use either C or C, depending on your needs. Both have identical syntax, so only C is shown here. $hub->filter(sub { my ($hub, $event) = @_; my $action = get_action($event); # No action should be taken return $event if $action eq 'none'; # You want your filter to remove the event return undef if $action eq 'delete'; if ($action eq 'do_it') { my $new_event = copy_event($event); ... Change your copy of the event ... return $new_event; } die "Should not happen"; }); By default, filters are not inherited by child hubs. That means if you start a subtest, the subtest will not inherit the filter. You can change this behavior with the C parameter: $hub->filter(sub { ... }, inherit => 1); =head2 LISTENING FOR EVENTS $hub->listen(sub { my ($hub, $event, $number) = @_; ... do whatever you want with the event ... # return is ignored }); By default listeners are not inherited by child hubs. That means if you start a subtest, the subtest will not inherit the listener. You can change this behavior with the C parameter: $hub->listen(sub { ... }, inherit => 1); =head2 POST-TEST BEHAVIORS $hub->follow_up(sub { my ($trace, $hub) = @_; ... do whatever you need to ... # Return is ignored }); follow_up subs are called only once, either when done_testing is called, or in an END block. =head2 SETTING THE FORMATTER By default an instance of L is created and used. my $old = $hub->format(My::Formatter->new); Setting the formatter will REPLACE any existing formatter. You may set the formatter to undef to prevent output. The old formatter will be returned if one was already set. Only one formatter is allowed at a time. =head1 METHODS =over 4 =item $hub->send($event) This is where all events enter the hub for processing. =item $hub->process($event) This is called by send after it does any IPC handling. You can use this to bypass the IPC process, but in general you should avoid using this. =item $old = $hub->format($formatter) Replace the existing formatter instance with a new one. Formatters must be objects that implement a C<< $formatter->write($event) >> method. =item $sub = $hub->listen(sub { ... }, %optional_params) You can use this to record all events AFTER they have been sent to the formatter. No changes made here will be meaningful, except possibly to other listeners. $hub->listen(sub { my ($hub, $event, $number) = @_; ... do whatever you want with the event ... # return is ignored }); Normally listeners are not inherited by child hubs such as subtests. You can add the C<< inherit => 1 >> parameter to allow a listener to be inherited. =item $hub->unlisten($sub) You can use this to remove a listen callback. You must pass in the coderef returned by the C method. =item $sub = $hub->filter(sub { ... }, %optional_params) =item $sub = $hub->pre_filter(sub { ... }, %optional_params) These can be used to add filters. Filters can modify, replace, or remove events before anything else can see them. $hub->filter( sub { my ($hub, $event) = @_; return $event; # No Changes return; # Remove the event # Or you can modify an event before returning it. $event->modify; return $event; } ); If you are not using threads, forking, or IPC then the only difference between a C and a C is that C subs run first. When you are using threads, forking, or IPC, pre_filters happen to events before they are sent to their destination proc/thread, ordinary filters happen only in the destination hub/thread. You cannot add a regular filter to a hub if the hub was created in another process or thread. You can always add a pre_filter. =item $hub->unfilter($sub) =item $hub->pre_unfilter($sub) These can be used to remove filters and pre_filters. The C<$sub> argument is the reference returned by C or C. =item $hub->follow_op(sub { ... }) Use this to add behaviors that are called just before the hub is finalized. The only argument to your codeblock will be a L instance. $hub->follow_up(sub { my ($trace, $hub) = @_; ... do whatever you need to ... # Return is ignored }); follow_up subs are called only once, ether when done_testing is called, or in an END block. =item $sub = $hub->add_context_acquire(sub { ... }); Add a callback that will be called every time someone tries to acquire a context. It gets a single argument, a reference of the hash of parameters being used the construct the context. This is your chance to change the parameters by directly altering the hash. test2_add_callback_context_acquire(sub { my $params = shift; $params->{level}++; }); This is a very scary API function. Please do not use this unless you need to. This is here for L and backwards compatibility. This has you directly manipulate the hash instead of returning a new one for performance reasons. B Using this hook could have a huge performance impact. The coderef you provide is returned and can be used to remove the hook later. =item $hub->remove_context_acquire($sub); This can be used to remove a context acquire hook. =item $sub = $hub->add_context_init(sub { ... }); This allows you to add callbacks that will trigger every time a new context is created for the hub. The only argument to the sub will be the L instance that was created. B Using this hook could have a huge performance impact. The coderef you provide is returned and can be used to remove the hook later. =item $hub->remove_context_init($sub); This can be used to remove a context init hook. =item $sub = $hub->add_context_release(sub { ... }); This allows you to add callbacks that will trigger every time a context for this hub is released. The only argument to the sub will be the L instance that was released. These will run in reverse order. B Using this hook could have a huge performance impact. The coderef you provide is returned and can be used to remove the hook later. =item $hub->remove_context_release($sub); This can be used to remove a context release hook. =item $hub->cull() Cull any IPC events (and process them). =item $pid = $hub->pid() Get the process id under which the hub was created. =item $tid = $hub->tid() Get the thread id under which the hub was created. =item $hud = $hub->hid() Get the identifier string of the hub. =item $uuid = $hub->uuid() If UUID tagging is enabled (see L) then the hub will have a UUID. =item $ipc = $hub->ipc() Get the IPC object used by the hub. =item $hub->set_no_ending($bool) =item $bool = $hub->no_ending This can be used to disable auto-ending behavior for a hub. The auto-ending behavior is triggered by an end block and is used to cull IPC events, and output the final plan if the plan was 'NO PLAN'. =item $bool = $hub->active =item $hub->set_active($bool) These are used to get/set the 'active' attribute. When true this attribute will force C<< hub->finalize() >> to take action even if there is no plan, and no tests have been run. This flag is useful for plugins that add follow-up behaviors that need to run even if no events are seen. =back =head2 STATE METHODS =over 4 =item $hub->reset_state() Reset all state to the start. This sets the test count to 0, clears the plan, removes the failures, etc. =item $num = $hub->count Get the number of tests that have been run. =item $num = $hub->failed Get the number of failures (Not all failures come from a test fail, so this number can be larger than the count). =item $bool = $hub->ended True if the testing has ended. This MAY return the stack frame of the tool that ended the test, but that is not guaranteed. =item $bool = $hub->is_passing =item $hub->is_passing($bool) Check if the overall test run is a failure. Can also be used to set the pass/fail status. =item $hub->plan($plan) =item $plan = $hub->plan Get or set the plan. The plan must be an integer larger than 0, the string 'NO PLAN', or the string 'SKIP'. =item $bool = $hub->check_plan Check if the plan and counts match, but only if the tests have ended. If tests have not ended this will return undef, otherwise it will be a true/false. =back =head1 THIRD PARTY META-DATA This object consumes L which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!cõ.íoXoXperl5/Test2/Event.pmnuÏÃ6Ç$package Test2::Event; use strict; use warnings; our $VERSION = '1.302183'; use Scalar::Util qw/blessed reftype/; use Carp qw/croak/; use Test2::Util::HashBase qw/trace -amnesty uuid -_eid -hubs/; use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/; use Test2::Util qw/pkg_to_file gen_uid/; use Test2::EventFacet::About(); use Test2::EventFacet::Amnesty(); use Test2::EventFacet::Assert(); use Test2::EventFacet::Control(); use Test2::EventFacet::Error(); use Test2::EventFacet::Info(); use Test2::EventFacet::Meta(); use Test2::EventFacet::Parent(); use Test2::EventFacet::Plan(); use Test2::EventFacet::Trace(); use Test2::EventFacet::Hub(); # Legacy tools will expect this to be loaded now require Test2::Util::Trace; my %LOADED_FACETS = ( 'about' => 'Test2::EventFacet::About', 'amnesty' => 'Test2::EventFacet::Amnesty', 'assert' => 'Test2::EventFacet::Assert', 'control' => 'Test2::EventFacet::Control', 'errors' => 'Test2::EventFacet::Error', 'info' => 'Test2::EventFacet::Info', 'meta' => 'Test2::EventFacet::Meta', 'parent' => 'Test2::EventFacet::Parent', 'plan' => 'Test2::EventFacet::Plan', 'trace' => 'Test2::EventFacet::Trace', 'hubs' => 'Test2::EventFacet::Hub', ); sub FACET_TYPES { sort values %LOADED_FACETS } sub load_facet { my $class = shift; my ($facet) = @_; return $LOADED_FACETS{$facet} if exists $LOADED_FACETS{$facet}; my @check = ($facet); if ('s' eq substr($facet, -1, 1)) { push @check => substr($facet, 0, -1); } else { push @check => $facet . 's'; } my $found; for my $check (@check) { my $mod = "Test2::EventFacet::" . ucfirst($facet); my $file = pkg_to_file($mod); next unless eval { require $file; 1 }; $found = $mod; last; } return undef unless $found; $LOADED_FACETS{$facet} = $found; } sub causes_fail { 0 } sub increments_count { 0 } sub diagnostics { 0 } sub no_display { 0 } sub subtest_id { undef } sub callback { } sub terminate { () } sub global { () } sub sets_plan { () } sub summary { ref($_[0]) } sub related { my $self = shift; my ($event) = @_; my $tracea = $self->trace or return undef; my $traceb = $event->trace or return undef; my $uuida = $tracea->uuid; my $uuidb = $traceb->uuid; if ($uuida && $uuidb) { return 1 if $uuida eq $uuidb; return 0; } my $siga = $tracea->signature or return undef; my $sigb = $traceb->signature or return undef; return 1 if $siga eq $sigb; return 0; } sub add_hub { my $self = shift; unshift @{$self->{+HUBS}} => @_; } sub add_amnesty { my $self = shift; for my $am (@_) { $am = {%$am} if ref($am) ne 'ARRAY'; $am = Test2::EventFacet::Amnesty->new($am); push @{$self->{+AMNESTY}} => $am; } } sub eid { $_[0]->{+_EID} ||= gen_uid() } sub common_facet_data { my $self = shift; my %out; $out{about} = {package => ref($self) || undef}; if (my $uuid = $self->uuid) { $out{about}->{uuid} = $uuid; } $out{about}->{eid} = $self->{+_EID} || $self->eid; if (my $trace = $self->trace) { $out{trace} = { %$trace }; } if (my $hubs = $self->hubs) { $out{hubs} = $hubs; } $out{amnesty} = [map {{ %{$_} }} @{$self->{+AMNESTY}}] if $self->{+AMNESTY}; if (my $meta = $self->meta_facet_data) { $out{meta} = $meta; } return \%out; } sub meta_facet_data { my $self = shift; my $key = Test2::Util::ExternalMeta::META_KEY(); my $hash = $self->{$key} or return undef; return {%$hash}; } sub facet_data { my $self = shift; my $out = $self->common_facet_data; $out->{about}->{details} = $self->summary || undef; $out->{about}->{no_display} = $self->no_display || undef; # Might be undef, we want to preserve that my $terminate = $self->terminate; $out->{control} = { global => $self->global || 0, terminate => $terminate, has_callback => $self->can('callback') == \&callback ? 0 : 1, }; $out->{assert} = { no_debug => 1, # Legacy behavior pass => $self->causes_fail ? 0 : 1, details => $self->summary, } if $self->increments_count; $out->{parent} = {hid => $self->subtest_id} if $self->subtest_id; if (my @plan = $self->sets_plan) { $out->{plan} = {}; $out->{plan}->{count} = $plan[0] if defined $plan[0]; $out->{plan}->{details} = $plan[2] if defined $plan[2]; if ($plan[1]) { $out->{plan}->{skip} = 1 if $plan[1] eq 'SKIP'; $out->{plan}->{none} = 1 if $plan[1] eq 'NO PLAN'; } $out->{control}->{terminate} ||= 0 if $out->{plan}->{skip}; } if ($self->causes_fail && !$out->{assert}) { $out->{errors} = [ { tag => 'FAIL', fail => 1, details => $self->summary, } ]; } my %IGNORE = (trace => 1, about => 1, control => 1); my $do_info = !grep { !$IGNORE{$_} } keys %$out; if ($do_info && !$self->no_display && $self->diagnostics) { $out->{info} = [ { tag => 'DIAG', debug => 1, details => $self->summary, } ]; } return $out; } sub facets { my $self = shift; my %out; my $data = $self->facet_data; my @errors = $self->validate_facet_data($data); die join "\n" => @errors if @errors; for my $facet (keys %$data) { my $class = $self->load_facet($facet); my $val = $data->{$facet}; unless($class) { $out{$facet} = $val; next; } my $is_list = reftype($val) eq 'ARRAY' ? 1 : 0; if ($is_list) { $out{$facet} = [map { $class->new($_) } @$val]; } else { $out{$facet} = $class->new($val); } } return \%out; } sub validate_facet_data { my $class_or_self = shift; my ($f, %params); $f = shift if @_ && (reftype($_[0]) || '') eq 'HASH'; %params = @_; $f ||= $class_or_self->facet_data if blessed($class_or_self); croak "No facet data" unless $f; my @errors; for my $k (sort keys %$f) { my $fclass = $class_or_self->load_facet($k); push @errors => "Could not find a facet class for facet '$k'" if $params{require_facet_class} && !$fclass; next unless $fclass; my $v = $f->{$k}; next unless defined($v); # undef is always fine my $is_list = $fclass->is_list(); my $got_list = reftype($v) eq 'ARRAY' ? 1 : 0; push @errors => "Facet '$k' should be a list, but got a single item ($v)" if $is_list && !$got_list; push @errors => "Facet '$k' should not be a list, but got a a list ($v)" if $got_list && !$is_list; } return @errors; } sub nested { my $self = shift; Carp::cluck("Use of Test2::Event->nested() is deprecated, use Test2::Event->trace->nested instead") if $ENV{AUTHOR_TESTING}; if (my $hubs = $self->{+HUBS}) { return $hubs->[0]->{nested} if @$hubs; } my $trace = $self->{+TRACE} or return undef; return $trace->{nested}; } sub in_subtest { my $self = shift; Carp::cluck("Use of Test2::Event->in_subtest() is deprecated, use Test2::Event->trace->hid instead") if $ENV{AUTHOR_TESTING}; my $hubs = $self->{+HUBS}; if ($hubs && @$hubs) { return undef unless $hubs->[0]->{nested}; return $hubs->[0]->{hid} } my $trace = $self->{+TRACE} or return undef; return undef unless $trace->{nested}; return $trace->{hid}; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Event - Base class for events =head1 DESCRIPTION Base class for all event objects that get passed through L. =head1 SYNOPSIS package Test2::Event::MyEvent; use strict; use warnings; # This will make our class an event subclass (required) use base 'Test2::Event'; # Add some accessors (optional) # You are not obligated to use HashBase, you can use any object tool you # want, or roll your own accessors. use Test2::Util::HashBase qw/foo bar baz/; # Use this if you want the legacy API to be written for you, for this to # work you will need to implement a facet_data() method. use Test2::Util::Facets2Legacy; # Chance to initialize some defaults sub init { my $self = shift; # no other args in @_ $self->set_foo('xxx') unless defined $self->foo; ... } # This is the new way for events to convey data to the Test2 system sub facet_data { my $self = shift; # Get common facets such as 'about', 'trace' 'amnesty', and 'meta' my $facet_data = $self->common_facet_data(); # Are you making an assertion? $facet_data->{assert} = {pass => 1, details => 'my assertion'}; ... return $facet_data; } 1; =head1 METHODS =head2 GENERAL =over 4 =item $trace = $e->trace Get a snapshot of the L as it was when this event was generated =item $bool_or_undef = $e->related($e2) Check if 2 events are related. In this case related means their traces share a signature meaning they were created with the same context (or at the very least by contexts which share an id, which is the same thing unless someone is doing something very bad). This can be used to reliably link multiple events created by the same tool. For instance a failing test like C will generate 2 events, one being a L, the other being a L, both of these events are related having been created under the same context and by the same initial tool (though multiple tools may have been nested under the initial one). This will return C if the relationship cannot be checked, which happens if either event has an incomplete or missing trace. This will return C<0> if the traces are complete, but do not match. C<1> will be returned if there is a match. =item $e->add_amnesty({tag => $TAG, details => $DETAILS}); This can be used to add amnesty to this event. Amnesty only effects failing assertions in most cases, but some formatters may display them for passing assertions, or even non-assertions as well. Amnesty will prevent a failed assertion from causing the overall test to fail. In other words it marks a failure as expected and allowed. B This is how 'TODO' is implemented under the hood. TODO is essentially amnesty with the 'TODO' tag. The details are the reason for the TODO. =item $uuid = $e->uuid If UUID tagging is enabled (See L) then any event that has made its way through a hub will be tagged with a UUID. A newly created event will not yet be tagged in most cases. =item $class = $e->load_facet($name) This method is used to load a facet by name (or key). It will attempt to load the facet class, if it succeeds it will return the class it loaded. If it fails it will return C. This caches the result at the class level so that future calls will be faster. The C<$name> variable should be the key used to access the facet in a facets hashref. For instance the assertion facet has the key 'assert', the information facet has the 'info' key, and the error facet has the key 'errors'. You may include or omit the 's' at the end of the name, the method is smart enough to try both the 's' and no-'s' forms, it will check what you provided first, and if that is not found it will add or strip the 's and try again. =item @classes = $e->FACET_TYPES() =item @classes = Test2::Event->FACET_TYPES() This returns a list of all facets that have been loaded using the C method. This will not return any classes that have not been loaded, or have been loaded directly without a call to C. B The core facet types are automatically loaded and populated in this list. =back =head2 NEW API =over 4 =item $hashref = $e->common_facet_data(); This can be used by subclasses to generate a starting facet data hashref. This will populate the hashref with the trace, meta, amnesty, and about facets. These facets are nearly always produced the same way for all events. =item $hashref = $e->facet_data() If you do not override this then the default implementation will attempt to generate facets from the legacy API. This generation is limited only to what the legacy API can provide. It is recommended that you override this method and write out explicit facet data. =item $hashref = $e->facets() This takes the hashref from C and blesses each facet into the proper C subclass. If no class can be found for any given facet it will be passed along unchanged. =item @errors = $e->validate_facet_data(); =item @errors = $e->validate_facet_data(%params); =item @errors = $e->validate_facet_data(\%facets, %params); =item @errors = Test2::Event->validate_facet_data(%params); =item @errors = Test2::Event->validate_facet_data(\%facets, %params); This method will validate facet data and return a list of errors. If no errors are found this will return an empty list. This can be called as an object method with no arguments, in which case the C method will be called to get the facet data to be validated. When used as an object method the C<\%facet_data> argument may be omitted. When used as a class method the C<\%facet_data> argument is required. Remaining arguments will be slurped into a C<%params> hash. Currently only 1 parameter is defined: =over 4 =item require_facet_class => $BOOL When set to true (default is false) this will reject any facets where a facet class cannot be found. Normally facets without classes are assumed to be custom and are ignored. =back =back =head3 WHAT ARE FACETS? Facets are how events convey their purpose to the Test2 internals and formatters. An event without facets will have no intentional effect on the overall test state, and will not be displayed at all by most formatters, except perhaps to say that an event of an unknown type was seen. Facets are produced by the C subroutine, which you should nearly-always override. C is expected to return a hashref where each key is the facet type, and the value is either a hashref with the data for that facet, or an array of hashrefs. Some facets must be defined as single hashrefs, some must be defined as an array of hashrefs, No facets allow both. C B bless the data it returns, the main hashref, and nested facet hashrefs B be bare, though items contained within each facet may be blessed. The data returned by this method B also be copies of the internal data in order to prevent accidental state modification. C takes the data from C and blesses it into the C packages. This is rarely used however, the EventFacet packages are primarily for convenience and documentation. The EventFacet classes are not used at all internally, instead the raw data is used. Here is a list of facet types by package. The packages are not used internally, but are where the documentation for each type is kept. B Every single facet type has the C<'details'> field. This field is always intended for human consumption, and when provided, should explain the 'why' for the facet. All other fields are facet specific. =over 4 =item about => {...} L This contains information about the event itself such as the event package name. The C
field for this facet is an overall summary of the event. =item assert => {...} L This facet is used if an assertion was made. The C
field of this facet is the description of the assertion. =item control => {...} L This facet is used to tell the L about special actions the event causes. Things like halting all testing, terminating the current test, etc. In this facet the C
field explains why any special action was taken. B This is how bail-out is implemented. =item meta => {...} L The meta facet contains all the meta-data attached to the event. In this case the C
field has no special meaning, but may be present if something sets the 'details' meta-key on the event. =item parent => {...} L This facet contains nested events and similar details for subtests. In this facet the C
field will typically be the name of the subtest. =item plan => {...} L This facet tells the system that a plan has been set. The C
field of this is usually left empty, but when present explains why the plan is what it is, this is most useful if the plan is to skip-all. =item trace => {...} L This facet contains information related to when and where the event was generated. This is how the test file and line number of a failure is known. This facet can also help you to tell if tests are related. In this facet the C
field overrides the "failed at test_file.t line 42." message provided on assertion failure. =item amnesty => [{...}, ...] L The amnesty facet is a list instead of a single item, this is important as amnesty can come from multiple places at once. For each instance of amnesty the C
field explains why amnesty was granted. B Outside of formatters amnesty only acts to forgive a failing assertion. =item errors => [{...}, ...] L The errors facet is a list instead of a single item, any number of errors can be listed. In this facet C
describes the error, or may contain the raw error message itself (such as an exception). In perl exception may be blessed objects, as such the raw data for this facet may contain nested items which are blessed. Not all errors are considered fatal, there is a C field that must be set for an error to cause the test to fail. B This facet is unique in that the field name is 'errors' while the package is 'Error'. This is because this is the only facet type that is both a list, and has a name where the plural is not the same as the singular. This may cause some confusion, but I feel it will be less confusing than the alternative. =item info => [{...}, ...] L The 'info' facet is a list instead of a single item, any quantity of extra information can be attached to an event. Some information may be critical diagnostics, others may be simply commentary in nature, this is determined by the C flag. For this facet the C
flag is the info itself. This info may be a string, or it may be a data structure to display. This is one of the few facet types that may contain blessed items. =back =head2 LEGACY API =over 4 =item $bool = $e->causes_fail Returns true if this event should result in a test failure. In general this should be false. =item $bool = $e->increments_count Should be true if this event should result in a test count increment. =item $e->callback($hub) If your event needs to have extra effects on the L you can override this method. This is called B your event is passed to the formatter. =item $num = $e->nested If this event is nested inside of other events, this should be the depth of nesting. (This is mainly for subtests) =item $bool = $e->global Set this to true if your event is global, that is ALL threads and processes should see it no matter when or where it is generated. This is not a common thing to want, it is used by bail-out and skip_all to end testing. =item $code = $e->terminate This is called B your event has been passed to the formatter. This should normally return undef, only change this if your event should cause the test to exit immediately. If you want this event to cause the test to exit you should return the exit code here. Exit code of 0 means exit success, any other integer means exit with failure. This is used by L to exit 0 when the plan is 'skip_all'. This is also used by L to force the test to exit with a failure. This is called after the event has been sent to the formatter in order to ensure the event is seen and understood. =item $msg = $e->summary This is intended to be a human readable summary of the event. This should ideally only be one line long, but you can use multiple lines if necessary. This is intended for human consumption. You do not need to make it easy for machines to understand. The default is to simply return the event package name. =item ($count, $directive, $reason) = $e->sets_plan() Check if this event sets the testing plan. It will return an empty list if it does not. If it does set the plan it will return a list of 1 to 3 items in order: Expected Test Count, Test Directive, Reason for directive. =item $bool = $e->diagnostics True if the event contains diagnostics info. This is useful because a non-verbose harness may choose to hide events that are not in this category. Some formatters may choose to send these to STDERR instead of STDOUT to ensure they are seen. =item $bool = $e->no_display False by default. This will return true on events that should not be displayed by formatters. =item $id = $e->in_subtest If the event is inside a subtest this should have the subtest ID. =item $id = $e->subtest_id If the event is a final subtest event, this should contain the subtest ID. =back =head1 THIRD PARTY META-DATA This object consumes L which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!RÛSH�k�kperl5/Test2/API/Context.pmnuÏÃ6Ç$package Test2::API::Context; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/confess croak/; use Scalar::Util qw/weaken blessed/; use Test2::Util qw/get_tid try pkg_to_file get_tid/; use Test2::EventFacet::Trace(); use Test2::API(); # Preload some key event types my %LOADED = ( map { my $pkg = "Test2::Event::$_"; my $file = "Test2/Event/$_.pm"; require $file unless $INC{$file}; ( $pkg => $pkg, $_ => $pkg ) } qw/Ok Diag Note Plan Bail Exception Waiting Skip Subtest Pass Fail V2/ ); use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/; use Test2::Util::HashBase qw{ stack hub trace _on_release _depth _is_canon _is_spawn _aborted errno eval_error child_error thrown }; # Private, not package vars # It is safe to cache these. my $ON_RELEASE = Test2::API::_context_release_callbacks_ref(); my $CONTEXTS = Test2::API::_contexts_ref(); sub init { my $self = shift; confess "The 'trace' attribute is required" unless $self->{+TRACE}; confess "The 'hub' attribute is required" unless $self->{+HUB}; $self->{+_DEPTH} = 0 unless defined $self->{+_DEPTH}; $self->{+ERRNO} = $! unless exists $self->{+ERRNO}; $self->{+EVAL_ERROR} = $@ unless exists $self->{+EVAL_ERROR}; $self->{+CHILD_ERROR} = $? unless exists $self->{+CHILD_ERROR}; } sub snapshot { bless {%{$_[0]}, _is_canon => undef, _is_spawn => undef, _aborted => undef}, __PACKAGE__ } sub restore_error_vars { my $self = shift; ($!, $@, $?) = @$self{+ERRNO, +EVAL_ERROR, +CHILD_ERROR}; } sub DESTROY { return unless $_[0]->{+_IS_CANON} || $_[0]->{+_IS_SPAWN}; return if $_[0]->{+_ABORTED} && ${$_[0]->{+_ABORTED}}; my ($self) = @_; my $hub = $self->{+HUB}; my $hid = $hub->{hid}; # Do not show the warning if it looks like an exception has been thrown, or # if the context is not local to this process or thread. { # Sometimes $@ is uninitialized, not a problem in this case so do not # show the warning about using eq. no warnings 'uninitialized'; if($self->{+EVAL_ERROR} eq $@ && $hub->is_local) { require Carp; my $mess = Carp::longmess("Context destroyed"); my $frame = $self->{+_IS_SPAWN} || $self->{+TRACE}->frame; warn <<" EOT"; A context appears to have been destroyed without first calling release(). Based on \$@ it does not look like an exception was thrown (this is not always a reliable test) This is a problem because the global error variables (\$!, \$@, and \$?) will not be restored. In addition some release callbacks will not work properly from inside a DESTROY method. Here are the context creation details, just in case a tool forgot to call release(): File: $frame->[1] Line: $frame->[2] Tool: $frame->[3] Here is a trace to the code that caused the context to be destroyed, this could be an exit(), a goto, or simply the end of a scope: $mess Cleaning up the CONTEXT stack... EOT } } return if $self->{+_IS_SPAWN}; # Remove the key itself to avoid a slow memory leak delete $CONTEXTS->{$hid}; $self->{+_IS_CANON} = undef; if (my $cbk = $self->{+_ON_RELEASE}) { $_->($self) for reverse @$cbk; } if (my $hcbk = $hub->{_context_release}) { $_->($self) for reverse @$hcbk; } $_->($self) for reverse @$ON_RELEASE; } # release exists to implement behaviors like die-on-fail. In die-on-fail you # want to die after a failure, but only after diagnostics have been reported. # The ideal time for the die to happen is when the context is released. # Unfortunately die does not work in a DESTROY block. sub release { my ($self) = @_; ($!, $@, $?) = @$self{+ERRNO, +EVAL_ERROR, +CHILD_ERROR} and return if $self->{+THROWN}; ($!, $@, $?) = @$self{+ERRNO, +EVAL_ERROR, +CHILD_ERROR} and return $self->{+_IS_SPAWN} = undef if $self->{+_IS_SPAWN}; croak "release() should not be called on context that is neither canon nor a child" unless $self->{+_IS_CANON}; my $hub = $self->{+HUB}; my $hid = $hub->{hid}; croak "context thinks it is canon, but it is not" unless $CONTEXTS->{$hid} && $CONTEXTS->{$hid} == $self; # Remove the key itself to avoid a slow memory leak $self->{+_IS_CANON} = undef; delete $CONTEXTS->{$hid}; if (my $cbk = $self->{+_ON_RELEASE}) { $_->($self) for reverse @$cbk; } if (my $hcbk = $hub->{_context_release}) { $_->($self) for reverse @$hcbk; } $_->($self) for reverse @$ON_RELEASE; # Do this last so that nothing else changes them. # If one of the hooks dies then these do not get restored, this is # intentional ($!, $@, $?) = @$self{+ERRNO, +EVAL_ERROR, +CHILD_ERROR}; return; } sub do_in_context { my $self = shift; my ($sub, @args) = @_; # We need to update the pid/tid and error vars. my $clone = $self->snapshot; @$clone{+ERRNO, +EVAL_ERROR, +CHILD_ERROR} = ($!, $@, $?); $clone->{+TRACE} = $clone->{+TRACE}->snapshot(pid => $$, tid => get_tid()); my $hub = $clone->{+HUB}; my $hid = $hub->hid; my $old = $CONTEXTS->{$hid}; $clone->{+_IS_CANON} = 1; $CONTEXTS->{$hid} = $clone; weaken($CONTEXTS->{$hid}); my ($ok, $err) = &try($sub, @args); my ($rok, $rerr) = try { $clone->release }; delete $clone->{+_IS_CANON}; if ($old) { $CONTEXTS->{$hid} = $old; weaken($CONTEXTS->{$hid}); } else { delete $CONTEXTS->{$hid}; } die $err unless $ok; die $rerr unless $rok; } sub done_testing { my $self = shift; $self->hub->finalize($self->trace, 1); return; } sub throw { my ($self, $msg) = @_; $self->{+THROWN} = 1; ${$self->{+_ABORTED}}++ if $self->{+_ABORTED}; $self->release if $self->{+_IS_CANON} || $self->{+_IS_SPAWN}; $self->trace->throw($msg); } sub alert { my ($self, $msg) = @_; $self->trace->alert($msg); } sub send_ev2_and_release { my $self = shift; my $out = $self->send_ev2(@_); $self->release; return $out; } sub send_ev2 { my $self = shift; my $e; { local $Carp::CarpLevel = $Carp::CarpLevel + 1; $e = Test2::Event::V2->new( trace => $self->{+TRACE}->snapshot, @_, ); } if ($self->{+_ABORTED}) { my $f = $e->facet_data; ${$self->{+_ABORTED}}++ if $f->{control}->{halt} || defined($f->{control}->{terminate}) || defined($e->terminate); } $self->{+HUB}->send($e); } sub build_ev2 { my $self = shift; local $Carp::CarpLevel = $Carp::CarpLevel + 1; Test2::Event::V2->new( trace => $self->{+TRACE}->snapshot, @_, ); } sub send_event_and_release { my $self = shift; my $out = $self->send_event(@_); $self->release; return $out; } sub send_event { my $self = shift; my $event = shift; my %args = @_; my $pkg = $LOADED{$event} || $self->_parse_event($event); my $e; { local $Carp::CarpLevel = $Carp::CarpLevel + 1; $e = $pkg->new( trace => $self->{+TRACE}->snapshot, %args, ); } if ($self->{+_ABORTED}) { my $f = $e->facet_data; ${$self->{+_ABORTED}}++ if $f->{control}->{halt} || defined($f->{control}->{terminate}) || defined($e->terminate); } $self->{+HUB}->send($e); } sub build_event { my $self = shift; my $event = shift; my %args = @_; my $pkg = $LOADED{$event} || $self->_parse_event($event); local $Carp::CarpLevel = $Carp::CarpLevel + 1; $pkg->new( trace => $self->{+TRACE}->snapshot, %args, ); } sub pass { my $self = shift; my ($name) = @_; my $e = bless( { trace => bless({%{$self->{+TRACE}}}, 'Test2::EventFacet::Trace'), name => $name, }, "Test2::Event::Pass" ); $self->{+HUB}->send($e); return $e; } sub pass_and_release { my $self = shift; my ($name) = @_; my $e = bless( { trace => bless({%{$self->{+TRACE}}}, 'Test2::EventFacet::Trace'), name => $name, }, "Test2::Event::Pass" ); $self->{+HUB}->send($e); $self->release; return 1; } sub fail { my $self = shift; my ($name, @diag) = @_; my $e = bless( { trace => bless({%{$self->{+TRACE}}}, 'Test2::EventFacet::Trace'), name => $name, }, "Test2::Event::Fail" ); for my $msg (@diag) { if (ref($msg) eq 'Test2::EventFacet::Info::Table') { $e->add_info({tag => 'DIAG', debug => 1, $msg->info_args}); } else { $e->add_info({tag => 'DIAG', debug => 1, details => $msg}); } } $self->{+HUB}->send($e); return $e; } sub fail_and_release { my $self = shift; my ($name, @diag) = @_; my $e = bless( { trace => bless({%{$self->{+TRACE}}}, 'Test2::EventFacet::Trace'), name => $name, }, "Test2::Event::Fail" ); for my $msg (@diag) { if (ref($msg) eq 'Test2::EventFacet::Info::Table') { $e->add_info({tag => 'DIAG', debug => 1, $msg->info_args}); } else { $e->add_info({tag => 'DIAG', debug => 1, details => $msg}); } } $self->{+HUB}->send($e); $self->release; return 0; } sub ok { my $self = shift; my ($pass, $name, $on_fail) = @_; my $hub = $self->{+HUB}; my $e = bless { trace => bless( {%{$self->{+TRACE}}}, 'Test2::EventFacet::Trace'), pass => $pass, name => $name, }, 'Test2::Event::Ok'; $e->init; $hub->send($e); return $e if $pass; $self->failure_diag($e); if ($on_fail && @$on_fail) { $self->diag($_) for @$on_fail; } return $e; } sub failure_diag { my $self = shift; my ($e) = @_; # Figure out the debug info, this is typically the file name and line # number, but can also be a custom message. If no trace object is provided # then we have nothing useful to display. my $name = $e->name; my $trace = $e->trace; my $debug = $trace ? $trace->debug : "[No trace info available]"; # Create the initial diagnostics. If the test has a name we put the debug # info on a second line, this behavior is inherited from Test::Builder. my $msg = defined($name) ? qq[Failed test '$name'\n$debug.\n] : qq[Failed test $debug.\n]; $self->diag($msg); } sub skip { my $self = shift; my ($name, $reason, @extra) = @_; $self->send_event( 'Skip', name => $name, reason => $reason, pass => 1, @extra, ); } sub note { my $self = shift; my ($message) = @_; $self->send_event('Note', message => $message); } sub diag { my $self = shift; my ($message) = @_; my $hub = $self->{+HUB}; $self->send_event( 'Diag', message => $message, ); } sub plan { my ($self, $max, $directive, $reason) = @_; $self->send_event('Plan', max => $max, directive => $directive, reason => $reason); } sub bail { my ($self, $reason) = @_; $self->send_event('Bail', reason => $reason); } sub _parse_event { my $self = shift; my $event = shift; my $pkg; if ($event =~ m/^\+(.*)/) { $pkg = $1; } else { $pkg = "Test2::Event::$event"; } unless ($LOADED{$pkg}) { my $file = pkg_to_file($pkg); my ($ok, $err) = try { require $file }; $self->throw("Could not load event module '$pkg': $err") unless $ok; $LOADED{$pkg} = $pkg; } confess "'$pkg' is not a subclass of 'Test2::Event'" unless $pkg->isa('Test2::Event'); $LOADED{$event} = $pkg; return $pkg; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::Context - Object to represent a testing context. =head1 DESCRIPTION The context object is the primary interface for authors of testing tools written with L. The context object represents the context in which a test takes place (File and Line Number), and provides a quick way to generate events from that context. The context object also takes care of sending events to the correct L instance. =head1 SYNOPSIS In general you will not be creating contexts directly. To obtain a context you should always use C which is exported by the L module. use Test2::API qw/context/; sub my_ok { my ($bool, $name) = @_; my $ctx = context(); if ($bool) { $ctx->pass($name); } else { $ctx->fail($name); } $ctx->release; # You MUST do this! return $bool; } Context objects make it easy to wrap other tools that also use context. Once you grab a context, any tool you call before releasing your context will inherit it: sub wrapper { my ($bool, $name) = @_; my $ctx = context(); $ctx->diag("wrapping my_ok"); my $out = my_ok($bool, $name); $ctx->release; # You MUST do this! return $out; } =head1 CRITICAL DETAILS =over 4 =item you MUST always use the context() sub from Test2::API Creating your own context via C<< Test2::API::Context->new() >> will almost never produce a desirable result. Use C which is exported by L. There are a handful of cases where a tool author may want to create a new context by hand, which is why the C method exists. Unless you really know what you are doing you should avoid this. =item You MUST always release the context when done with it Releasing the context tells the system you are done with it. This gives it a chance to run any necessary callbacks or cleanup tasks. If you forget to release the context it will try to detect the problem and warn you about it. =item You MUST NOT pass context objects around When you obtain a context object it is made specifically for your tool and any tools nested within. If you pass a context around you run the risk of polluting other tools with incorrect context information. If you are certain that you want a different tool to use the same context you may pass it a snapshot. C<< $ctx->snapshot >> will give you a shallow clone of the context that is safe to pass around or store. =item You MUST NOT store or cache a context for later As long as a context exists for a given hub, all tools that try to get a context will get the existing instance. If you try to store the context you will pollute other tools with incorrect context information. If you are certain that you want to save the context for later, you can use a snapshot. C<< $ctx->snapshot >> will give you a shallow clone of the context that is safe to pass around or store. C has some mechanisms to protect you if you do cause a context to persist beyond the scope in which it was obtained. In practice you should not rely on these protections, and they are fairly noisy with warnings. =item You SHOULD obtain your context as soon as possible in a given tool You never know what tools you call from within your own tool will need a context. Obtaining the context early ensures that nested tools can find the context you want them to find. =back =head1 METHODS =over 4 =item $ctx->done_testing; Note that testing is finished. If no plan has been set this will generate a Plan event. =item $clone = $ctx->snapshot() This will return a shallow clone of the context. The shallow clone is safe to store for later. =item $ctx->release() This will release the context. This runs cleanup tasks, and several important hooks. It will also restore C<$!>, C<$?>, and C<$@> to what they were when the context was created. B If a context is acquired more than once an internal refcount is kept. C decrements the ref count, none of the other actions of C will occur unless the refcount hits 0. This means only the last call to C will reset C<$?>, C<$!>, C<$@>,and run the cleanup tasks. =item $ctx->throw($message) This will throw an exception reporting to the file and line number of the context. This will also release the context for you. =item $ctx->alert($message) This will issue a warning from the file and line number of the context. =item $stack = $ctx->stack() This will return the L instance the context used to find the current hub. =item $hub = $ctx->hub() This will return the L instance the context recognizes as the current one to which all events should be sent. =item $dbg = $ctx->trace() This will return the L instance used by the context. =item $ctx->do_in_context(\&code, @args); Sometimes you have a context that is not current, and you want things to use it as the current one. In these cases you can call C<< $ctx->do_in_context(sub { ... }) >>. The codeblock will be run, and anything inside of it that looks for a context will find the one on which the method was called. This B affect context on other hubs, only the hub used by the context will be affected. my $ctx = ...; $ctx->do_in_context(sub { my $ctx = context(); # returns the $ctx the sub is called on }); B The context will actually be cloned, the clone will be used instead of the original. This allows the thread id, process id, and error variables to be correct without modifying the original context. =item $ctx->restore_error_vars() This will set C<$!>, C<$?>, and C<$@> to what they were when the context was created. There is no localization or anything done here, calling this method will actually set these vars. =item $! = $ctx->errno() The (numeric) value of C<$!> when the context was created. =item $? = $ctx->child_error() The value of C<$?> when the context was created. =item $@ = $ctx->eval_error() The value of C<$@> when the context was created. =back =head2 EVENT PRODUCTION METHODS B The C and C are optimal if they meet your situation, using one of them will always be the most optimal. That said they are optimal by eliminating many features. Method such as C, and C are shortcuts for generating common 1-task events based on the old API, however they are forward compatible, and easy to use. If these meet your needs then go ahead and use them, but please check back often for alternatives that may be added. If you want to generate new style events, events that do many things at once, then you want the C<*ev2*> methods. These let you directly specify which facets you wish to use. =over 4 =item $event = $ctx->pass() =item $event = $ctx->pass($name) This will send and return an L event. You may optionally provide a C<$name> for the assertion. The L is a specially crafted and optimized event, using this will help the performance of passing tests. =item $true = $ctx->pass_and_release() =item $true = $ctx->pass_and_release($name) This is a combination of C and C. You can use this if you do not plan to do anything with the context after sending the event. This helps write more clear and compact code. sub shorthand { my ($bool, $name) = @_; my $ctx = context(); return $ctx->pass_and_release($name) if $bool; ... Handle a failure ... } sub longform { my ($bool, $name) = @_; my $ctx = context(); if ($bool) { $ctx->pass($name); $ctx->release; return 1; } ... Handle a failure ... } =item my $event = $ctx->fail() =item my $event = $ctx->fail($name) =item my $event = $ctx->fail($name, @diagnostics) This lets you send an L event. You may optionally provide a C<$name> and C<@diagnostics> messages. Diagnostics messages can be simple strings, data structures, or instances of L (which are converted inline into the L structure). =item my $false = $ctx->fail_and_release() =item my $false = $ctx->fail_and_release($name) =item my $false = $ctx->fail_and_release($name, @diagnostics) This is a combination of C and C. This can be used to write clearer and shorter code. sub shorthand { my ($bool, $name) = @_; my $ctx = context(); return $ctx->fail_and_release($name) unless $bool; ... Handle a success ... } sub longform { my ($bool, $name) = @_; my $ctx = context(); unless ($bool) { $ctx->pass($name); $ctx->release; return 1; } ... Handle a success ... } =item $event = $ctx->ok($bool, $name) =item $event = $ctx->ok($bool, $name, \@on_fail) B Use of this method is discouraged in favor of C and C which produce L and L events. These newer event types are faster and less crufty. This will create an L object for you. If C<$bool> is false then an L event will be sent as well with details about the failure. If you do not want automatic diagnostics you should use the C method directly. The third argument C<\@on_fail>) is an optional set of diagnostics to be sent in the event of a test failure. Unlike with C these diagnostics must be plain strings, data structures are not supported. =item $event = $ctx->note($message) Send an L. This event prints a message to STDOUT. =item $event = $ctx->diag($message) Send an L. This event prints a message to STDERR. =item $event = $ctx->plan($max) =item $event = $ctx->plan(0, 'SKIP', $reason) This can be used to send an L event. This event usually takes either a number of tests you expect to run. Optionally you can set the expected count to 0 and give the 'SKIP' directive with a reason to cause all tests to be skipped. =item $event = $ctx->skip($name, $reason); Send an L event. =item $event = $ctx->bail($reason) This sends an L event. This event will completely terminate all testing. =item $event = $ctx->send_ev2(%facets) This lets you build and send a V2 event directly from facets. The event is returned after it is sent. This example sends a single assertion, a note (comment for stdout in Test::Builder talk) and sets the plan to 1. my $event = $ctx->send_event( plan => {count => 1}, assert => {pass => 1, details => "A passing assert"}, info => [{tag => 'NOTE', details => "This is a note"}], ); =item $event = $ctx->build_e2(%facets) This is the same as C, except it builds and returns the event without sending it. =item $event = $ctx->send_ev2_and_release($Type, %parameters) This is a combination of C and C. sub shorthand { my $ctx = context(); return $ctx->send_ev2_and_release(assert => {pass => 1, details => 'foo'}); } sub longform { my $ctx = context(); my $event = $ctx->send_ev2(assert => {pass => 1, details => 'foo'}); $ctx->release; return $event; } =item $event = $ctx->send_event($Type, %parameters) B This lets you build and send an event of any type. The C<$Type> argument should be the event package name with C left off, or a fully qualified package name prefixed with a '+'. The event is returned after it is sent. my $event = $ctx->send_event('Ok', ...); or my $event = $ctx->send_event('+Test2::Event::Ok', ...); =item $event = $ctx->build_event($Type, %parameters) B This is the same as C, except it builds and returns the event without sending it. =item $event = $ctx->send_event_and_release($Type, %parameters) B This is a combination of C and C. sub shorthand { my $ctx = context(); return $ctx->send_event_and_release(Pass => { name => 'foo' }); } sub longform { my $ctx = context(); my $event = $ctx->send_event(Pass => { name => 'foo' }); $ctx->release; return $event; } =back =head1 HOOKS There are 2 types of hooks, init hooks, and release hooks. As the names suggest, these hooks are triggered when contexts are created or released. =head2 INIT HOOKS These are called whenever a context is initialized. That means when a new instance is created. These hooks are B called every time something requests a context, just when a new one is created. =head3 GLOBAL This is how you add a global init callback. Global callbacks happen for every context for any hub or stack. Test2::API::test2_add_callback_context_init(sub { my $ctx = shift; ... }); =head3 PER HUB This is how you add an init callback for all contexts created for a given hub. These callbacks will not run for other hubs. $hub->add_context_init(sub { my $ctx = shift; ... }); =head3 PER CONTEXT This is how you specify an init hook that will only run if your call to C generates a new context. The callback will be ignored if C is returning an existing context. my $ctx = context(on_init => sub { my $ctx = shift; ... }); =head2 RELEASE HOOKS These are called whenever a context is released. That means when the last reference to the instance is about to be destroyed. These hooks are B called every time C<< $ctx->release >> is called. =head3 GLOBAL This is how you add a global release callback. Global callbacks happen for every context for any hub or stack. Test2::API::test2_add_callback_context_release(sub { my $ctx = shift; ... }); =head3 PER HUB This is how you add a release callback for all contexts created for a given hub. These callbacks will not run for other hubs. $hub->add_context_release(sub { my $ctx = shift; ... }); =head3 PER CONTEXT This is how you add release callbacks directly to a context. The callback will B be added to the context that gets returned, it does not matter if a new one is generated, or if an existing one is returned. my $ctx = context(on_release => sub { my $ctx = shift; ... }); =head1 THIRD PARTY META-DATA This object consumes L which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =item Kent Fredric Ekentnl@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!u�ëSùSùSperl5/Test2/API/Instance.pmnuÏÃ6Ç$package Test2::API::Instance; use strict; use warnings; our $VERSION = '1.302183'; our @CARP_NOT = qw/Test2::API Test2::API::Instance Test2::IPC::Driver Test2::Formatter/; use Carp qw/confess carp/; use Scalar::Util qw/reftype/; use Test2::Util qw/get_tid USE_THREADS CAN_FORK pkg_to_file try CAN_SIGSYS/; use Test2::EventFacet::Trace(); use Test2::API::Stack(); use Test2::Util::HashBase qw{ _pid _tid no_wait finalized loaded ipc stack formatter contexts add_uuid_via -preload ipc_disabled ipc_polling ipc_drivers ipc_timeout formatters exit_callbacks post_load_callbacks context_acquire_callbacks context_init_callbacks context_release_callbacks pre_subtest_callbacks }; sub DEFAULT_IPC_TIMEOUT() { 30 } sub pid { $_[0]->{+_PID} } sub tid { $_[0]->{+_TID} } # Wrap around the getters that should call _finalize. BEGIN { for my $finalizer (IPC, FORMATTER) { my $orig = __PACKAGE__->can($finalizer); my $new = sub { my $self = shift; $self->_finalize unless $self->{+FINALIZED}; $self->$orig; }; no strict 'refs'; no warnings 'redefine'; *{$finalizer} = $new; } } sub has_ipc { !!$_[0]->{+IPC} } sub import { my $class = shift; return unless @_; my ($ref) = @_; $$ref = $class->new; } sub init { $_[0]->reset } sub start_preload { my $self = shift; confess "preload cannot be started, Test2::API has already been initialized" if $self->{+FINALIZED} || $self->{+LOADED}; return $self->{+PRELOAD} = 1; } sub stop_preload { my $self = shift; return 0 unless $self->{+PRELOAD}; $self->{+PRELOAD} = 0; $self->post_preload_reset(); return 1; } sub post_preload_reset { my $self = shift; delete $self->{+_PID}; delete $self->{+_TID}; $self->{+ADD_UUID_VIA} = undef unless exists $self->{+ADD_UUID_VIA}; $self->{+CONTEXTS} = {}; $self->{+FORMATTERS} = []; $self->{+FINALIZED} = undef; $self->{+IPC} = undef; $self->{+IPC_DISABLED} = $ENV{T2_NO_IPC} ? 1 : 0; $self->{+IPC_TIMEOUT} = DEFAULT_IPC_TIMEOUT() unless defined $self->{+IPC_TIMEOUT}; $self->{+LOADED} = 0; $self->{+STACK} ||= Test2::API::Stack->new; } sub reset { my $self = shift; delete $self->{+_PID}; delete $self->{+_TID}; $self->{+ADD_UUID_VIA} = undef; $self->{+CONTEXTS} = {}; $self->{+IPC_DRIVERS} = []; $self->{+IPC_POLLING} = undef; $self->{+FORMATTERS} = []; $self->{+FORMATTER} = undef; $self->{+FINALIZED} = undef; $self->{+IPC} = undef; $self->{+IPC_DISABLED} = $ENV{T2_NO_IPC} ? 1 : 0; $self->{+IPC_TIMEOUT} = DEFAULT_IPC_TIMEOUT() unless defined $self->{+IPC_TIMEOUT}; $self->{+NO_WAIT} = 0; $self->{+LOADED} = 0; $self->{+EXIT_CALLBACKS} = []; $self->{+POST_LOAD_CALLBACKS} = []; $self->{+CONTEXT_ACQUIRE_CALLBACKS} = []; $self->{+CONTEXT_INIT_CALLBACKS} = []; $self->{+CONTEXT_RELEASE_CALLBACKS} = []; $self->{+PRE_SUBTEST_CALLBACKS} = []; $self->{+STACK} = Test2::API::Stack->new; } sub _finalize { my $self = shift; my ($caller) = @_; $caller ||= [caller(1)]; confess "Attempt to initialize Test2::API during preload" if $self->{+PRELOAD}; $self->{+FINALIZED} = $caller; $self->{+_PID} = $$ unless defined $self->{+_PID}; $self->{+_TID} = get_tid() unless defined $self->{+_TID}; unless ($self->{+FORMATTER}) { my ($formatter, $source); if ($ENV{T2_FORMATTER}) { $source = "set by the 'T2_FORMATTER' environment variable"; if ($ENV{T2_FORMATTER} =~ m/^(\+)?(.*)$/) { $formatter = $1 ? $2 : "Test2::Formatter::$2" } else { $formatter = ''; } } elsif (@{$self->{+FORMATTERS}}) { ($formatter) = @{$self->{+FORMATTERS}}; $source = "Most recently added"; } else { $formatter = 'Test2::Formatter::TAP'; $source = 'default formatter'; } unless (ref($formatter) || $formatter->can('write')) { my $file = pkg_to_file($formatter); my ($ok, $err) = try { require $file }; unless ($ok) { my $line = "* COULD NOT LOAD FORMATTER '$formatter' ($source) *"; my $border = '*' x length($line); die "\n\n $border\n $line\n $border\n\n$err"; } } $self->{+FORMATTER} = $formatter; } # Turn on IPC if threads are on, drivers are registered, or the Test2::IPC # module is loaded. return if $self->{+IPC_DISABLED}; return unless USE_THREADS || $INC{'Test2/IPC.pm'} || @{$self->{+IPC_DRIVERS}}; # Turn on polling by default, people expect it. $self->enable_ipc_polling; unless (@{$self->{+IPC_DRIVERS}}) { my ($ok, $error) = try { require Test2::IPC::Driver::Files }; die $error unless $ok; push @{$self->{+IPC_DRIVERS}} => 'Test2::IPC::Driver::Files'; } for my $driver (@{$self->{+IPC_DRIVERS}}) { next unless $driver->can('is_viable') && $driver->is_viable; $self->{+IPC} = $driver->new or next; return; } die "IPC has been requested, but no viable drivers were found. Aborting...\n"; } sub formatter_set { $_[0]->{+FORMATTER} ? 1 : 0 } sub add_formatter { my $self = shift; my ($formatter) = @_; unshift @{$self->{+FORMATTERS}} => $formatter; return unless $self->{+FINALIZED}; # Why is the @CARP_NOT entry not enough? local %Carp::Internal = %Carp::Internal; $Carp::Internal{'Test2::Formatter'} = 1; carp "Formatter $formatter loaded too late to be used as the global formatter"; } sub add_context_acquire_callback { my $self = shift; my ($code) = @_; my $rtype = reftype($code) || ""; confess "Context-acquire callbacks must be coderefs" unless $code && $rtype eq 'CODE'; push @{$self->{+CONTEXT_ACQUIRE_CALLBACKS}} => $code; } sub add_context_init_callback { my $self = shift; my ($code) = @_; my $rtype = reftype($code) || ""; confess "Context-init callbacks must be coderefs" unless $code && $rtype eq 'CODE'; push @{$self->{+CONTEXT_INIT_CALLBACKS}} => $code; } sub add_context_release_callback { my $self = shift; my ($code) = @_; my $rtype = reftype($code) || ""; confess "Context-release callbacks must be coderefs" unless $code && $rtype eq 'CODE'; push @{$self->{+CONTEXT_RELEASE_CALLBACKS}} => $code; } sub add_post_load_callback { my $self = shift; my ($code) = @_; my $rtype = reftype($code) || ""; confess "Post-load callbacks must be coderefs" unless $code && $rtype eq 'CODE'; push @{$self->{+POST_LOAD_CALLBACKS}} => $code; $code->() if $self->{+LOADED}; } sub add_pre_subtest_callback { my $self = shift; my ($code) = @_; my $rtype = reftype($code) || ""; confess "Pre-subtest callbacks must be coderefs" unless $code && $rtype eq 'CODE'; push @{$self->{+PRE_SUBTEST_CALLBACKS}} => $code; } sub load { my $self = shift; unless ($self->{+LOADED}) { confess "Attempt to initialize Test2::API during preload" if $self->{+PRELOAD}; $self->{+_PID} = $$ unless defined $self->{+_PID}; $self->{+_TID} = get_tid() unless defined $self->{+_TID}; # This is for https://github.com/Test-More/test-more/issues/16 # and https://rt.perl.org/Public/Bug/Display.html?id=127774 # END blocks run in reverse order. This insures the END block is loaded # as late as possible. It will not solve all cases, but it helps. eval "END { Test2::API::test2_set_is_end() }; 1" or die $@; $self->{+LOADED} = 1; $_->() for @{$self->{+POST_LOAD_CALLBACKS}}; } return $self->{+LOADED}; } sub add_exit_callback { my $self = shift; my ($code) = @_; my $rtype = reftype($code) || ""; confess "End callbacks must be coderefs" unless $code && $rtype eq 'CODE'; push @{$self->{+EXIT_CALLBACKS}} => $code; } sub ipc_disable { my $self = shift; confess "Attempt to disable IPC after it has been initialized" if $self->{+IPC}; $self->{+IPC_DISABLED} = 1; } sub add_ipc_driver { my $self = shift; my ($driver) = @_; unshift @{$self->{+IPC_DRIVERS}} => $driver; return unless $self->{+FINALIZED}; # Why is the @CARP_NOT entry not enough? local %Carp::Internal = %Carp::Internal; $Carp::Internal{'Test2::IPC::Driver'} = 1; carp "IPC driver $driver loaded too late to be used as the global ipc driver"; } sub enable_ipc_polling { my $self = shift; $self->{+_PID} = $$ unless defined $self->{+_PID}; $self->{+_TID} = get_tid() unless defined $self->{+_TID}; $self->add_context_init_callback( # This is called every time a context is created, it needs to be fast. # $_[0] is a context object sub { return unless $self->{+IPC_POLLING}; return unless $self->{+IPC}; return unless $self->{+IPC}->pending(); return $_[0]->{hub}->cull; } ) unless defined $self->ipc_polling; $self->set_ipc_polling(1); } sub get_ipc_pending { my $self = shift; return -1 unless $self->{+IPC}; $self->{+IPC}->pending(); } sub _check_pid { my $self = shift; my ($pid) = @_; return kill(0, $pid); } sub set_ipc_pending { my $self = shift; return unless $self->{+IPC}; my ($val) = @_; confess "value is required for set_ipc_pending" unless $val; $self->{+IPC}->set_pending($val); } sub disable_ipc_polling { my $self = shift; return unless defined $self->{+IPC_POLLING}; $self->{+IPC_POLLING} = 0; } sub _ipc_wait { my ($timeout) = @_; my $fail = 0; $timeout = DEFAULT_IPC_TIMEOUT() unless defined $timeout; my $ok = eval { if (CAN_FORK) { local $SIG{ALRM} = sub { die "Timeout waiting on child processes" }; alarm $timeout; while (1) { my $pid = CORE::wait(); my $err = $?; last if $pid == -1; next unless $err; $fail++; my $sig = $err & 127; my $exit = $err >> 8; warn "Process $pid did not exit cleanly (wstat: $err, exit: $exit, sig: $sig)\n"; } alarm 0; } if (USE_THREADS) { my $start = time; while (1) { last unless threads->list(); die "Timeout waiting on child thread" if time - $start >= $timeout; sleep 1; for my $t (threads->list) { # threads older than 1.34 do not have this :-( next if $t->can('is_joinable') && !$t->is_joinable; $t->join; # In older threads we cannot check if a thread had an error unless # we control it and its return. my $err = $t->can('error') ? $t->error : undef; next unless $err; my $tid = $t->tid(); $fail++; chomp($err); warn "Thread $tid did not end cleanly: $err\n"; } } } 1; }; my $error = $@; return 0 if $ok && !$fail; warn $error unless $ok; return 255; } sub set_exit { my $self = shift; return if $self->{+PRELOAD}; my $exit = $?; my $new_exit = $exit; if ($INC{'Test/Builder.pm'} && $Test::Builder::VERSION ne $Test2::API::VERSION) { print STDERR <<" EOT"; ******************************************************************************** * * * Test::Builder -- Test2::API version mismatch detected * * * ******************************************************************************** Test2::API Version: $Test2::API::VERSION Test::Builder Version: $Test::Builder::VERSION This is not a supported configuration, you will have problems. EOT } for my $ctx (values %{$self->{+CONTEXTS}}) { next unless $ctx; next if $ctx->_aborted && ${$ctx->_aborted}; # Only worry about contexts in this PID my $trace = $ctx->trace || next; next unless $trace->pid && $trace->pid == $$; # Do not worry about contexts that have no hub my $hub = $ctx->hub || next; # Do not worry if the state came to a sudden end. next if $hub->bailed_out; next if defined $hub->skip_reason; # now we worry $trace->alert("context object was never released! This means a testing tool is behaving very badly"); $exit = 255; $new_exit = 255; } if (!defined($self->{+_PID}) or !defined($self->{+_TID}) or $self->{+_PID} != $$ or $self->{+_TID} != get_tid()) { $? = $exit; return; } my @hubs = $self->{+STACK} ? $self->{+STACK}->all : (); if (@hubs and $self->{+IPC} and !$self->{+NO_WAIT}) { local $?; my %seen; for my $hub (reverse @hubs) { my $ipc = $hub->ipc or next; next if $seen{$ipc}++; $ipc->waiting(); } my $ipc_exit = _ipc_wait($self->{+IPC_TIMEOUT}); $new_exit ||= $ipc_exit; } # None of this is necessary if we never got a root hub if(my $root = shift @hubs) { my $trace = Test2::EventFacet::Trace->new( frame => [__PACKAGE__, __FILE__, 0, __PACKAGE__ . '::END'], detail => __PACKAGE__ . ' END Block finalization', ); my $ctx = Test2::API::Context->new( trace => $trace, hub => $root, ); if (@hubs) { $ctx->diag("Test ended with extra hubs on the stack!"); $new_exit = 255; } unless ($root->no_ending) { local $?; $root->finalize($trace) unless $root->ended; $_->($ctx, $exit, \$new_exit) for @{$self->{+EXIT_CALLBACKS}}; $new_exit ||= $root->failed; $new_exit ||= 255 unless $root->is_passing; } } $new_exit = 255 if $new_exit > 255; if ($new_exit && eval { require Test2::API::Breakage; 1 }) { my @warn = Test2::API::Breakage->report(); if (@warn) { print STDERR "\nYou have loaded versions of test modules known to have problems with Test2.\nThis could explain some test failures.\n"; print STDERR "$_\n" for @warn; print STDERR "\n"; } } $? = $new_exit; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::Instance - Object used by Test2::API under the hood =head1 DESCRIPTION This object encapsulates the global shared state tracked by L. A single global instance of this package is stored (and obscured) by the L package. There is no reason to directly use this package. This package is documented for completeness. This package can change, or go away completely at any time. Directly using, or monkeypatching this package is not supported in any way shape or form. =head1 SYNOPSIS use Test2::API::Instance; my $obj = Test2::API::Instance->new; =over 4 =item $pid = $obj->pid PID of this instance. =item $obj->tid Thread ID of this instance. =item $obj->reset() Reset the object to defaults. =item $obj->load() Set the internal state to loaded, and run and stored post-load callbacks. =item $bool = $obj->loaded Check if the state is set to loaded. =item $arrayref = $obj->post_load_callbacks Get the post-load callbacks. =item $obj->add_post_load_callback(sub { ... }) Add a post-load callback. If C has already been called then the callback will be immediately executed. If C has not been called then the callback will be stored and executed later when C is called. =item $hashref = $obj->contexts() Get a hashref of all active contexts keyed by hub id. =item $arrayref = $obj->context_acquire_callbacks Get all context acquire callbacks. =item $arrayref = $obj->context_init_callbacks Get all context init callbacks. =item $arrayref = $obj->context_release_callbacks Get all context release callbacks. =item $arrayref = $obj->pre_subtest_callbacks Get all pre-subtest callbacks. =item $obj->add_context_init_callback(sub { ... }) Add a context init callback. Subs are called every time a context is created. Subs get the newly created context as their only argument. =item $obj->add_context_release_callback(sub { ... }) Add a context release callback. Subs are called every time a context is released. Subs get the released context as their only argument. These callbacks should not call release on the context. =item $obj->add_pre_subtest_callback(sub { ... }) Add a pre-subtest callback. Subs are called every time a subtest is going to be run. Subs get the subtest name, coderef, and any arguments. =item $obj->set_exit() This is intended to be called in an C block. This will look at test state and set $?. This will also call any end callbacks, and wait on child processes/threads. =item $obj->set_ipc_pending($val) Tell other processes and threads there is a pending event. C<$val> should be a unique value no other thread/process will generate. B This will also make the current process see a pending event. =item $pending = $obj->get_ipc_pending() This returns -1 if it is not possible to know. This returns 0 if there are no pending events. This returns 1 if there are pending events. =item $timeout = $obj->ipc_timeout; =item $obj->set_ipc_timeout($timeout); How long to wait for child processes and threads before aborting. =item $drivers = $obj->ipc_drivers Get the list of IPC drivers. =item $obj->add_ipc_driver($DRIVER_CLASS) Add an IPC driver to the list. The most recently added IPC driver will become the global one during initialization. If a driver is added after initialization has occurred a warning will be generated: "IPC driver $driver loaded too late to be used as the global ipc driver" =item $bool = $obj->ipc_polling Check if polling is enabled. =item $obj->enable_ipc_polling Turn on polling. This will cull events from other processes and threads every time a context is created. =item $obj->disable_ipc_polling Turn off IPC polling. =item $bool = $obj->no_wait =item $bool = $obj->set_no_wait($bool) Get/Set no_wait. This option is used to turn off process/thread waiting at exit. =item $arrayref = $obj->exit_callbacks Get the exit callbacks. =item $obj->add_exit_callback(sub { ... }) Add an exit callback. This callback will be called by C. =item $bool = $obj->finalized Check if the object is finalized. Finalization happens when either C, C, or C are called on the object. Once finalization happens these fields are considered unchangeable (not enforced here, enforced by L). =item $ipc = $obj->ipc Get the one true IPC instance. =item $obj->ipc_disable Turn IPC off =item $bool = $obj->ipc_disabled Check if IPC is disabled =item $stack = $obj->stack Get the one true hub stack. =item $formatter = $obj->formatter Get the global formatter. By default this is the C<'Test2::Formatter::TAP'> package. This could be any package that implements the C method. This can also be an instantiated object. =item $bool = $obj->formatter_set() Check if a formatter has been set. =item $obj->add_formatter($class) =item $obj->add_formatter($obj) Add a formatter. The most recently added formatter will become the global one during initialization. If a formatter is added after initialization has occurred a warning will be generated: "Formatter $formatter loaded too late to be used as the global formatter" =item $obj->set_add_uuid_via(sub { ... }) =item $sub = $obj->add_uuid_via() This allows you to provide a UUID generator. If provided UUIDs will be attached to all events, hubs, and contexts. This is useful for storing, tracking, and linking these objects. The sub you provide should always return a unique identifier. Most things will expect a proper UUID string, however nothing in Test2::API enforces this. The sub will receive exactly 1 argument, the type of thing being tagged 'context', 'hub', or 'event'. In the future additional things may be tagged, in which case new strings will be passed in. These are purely informative, you can (and usually should) ignore them. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!BV3ÚÚperl5/Test2/API/Breakage.pmnuÏÃ6Ç$package Test2::API::Breakage; use strict; use warnings; our $VERSION = '1.302183'; use Test2::Util qw/pkg_to_file/; our @EXPORT_OK = qw{ upgrade_suggested upgrade_required known_broken }; BEGIN { require Exporter; our @ISA = qw(Exporter) } sub upgrade_suggested { return ( 'Test::Exception' => '0.42', 'Test::FITesque' => '0.04', 'Test::Module::Used' => '0.2.5', 'Test::Moose::More' => '0.025', ); } sub upgrade_required { return ( 'Test::Builder::Clutch' => '0.07', 'Test::Dist::VersionSync' => '1.1.4', 'Test::Modern' => '0.012', 'Test::SharedFork' => '0.34', 'Test::Alien' => '0.04', 'Test::UseAllModules' => '0.14', 'Test::More::Prefix' => '0.005', 'Test2::Tools::EventDumper' => 0.000007, 'Test2::Harness' => 0.000013, 'Test::DBIx::Class::Schema' => '1.0.9', 'Test::Clustericious::Cluster' => '0.30', ); } sub known_broken { return ( 'Net::BitTorrent' => '0.052', 'Test::Able' => '0.11', 'Test::Aggregate' => '0.373', 'Test::Flatten' => '0.11', 'Test::Group' => '0.20', 'Test::ParallelSubtest' => '0.05', 'Test::Pretty' => '0.32', 'Test::Wrapper' => '0.3.0', 'Log::Dispatch::Config::TestLog' => '0.02', ); } # Not reportable: # Device::Chip => 0.07 - Tests will not pass, but not broken if already installed, also no fixed version we can upgrade to. sub report { my $class = shift; my ($require) = @_; my %suggest = __PACKAGE__->upgrade_suggested(); my %required = __PACKAGE__->upgrade_required(); my %broken = __PACKAGE__->known_broken(); my @warn; for my $mod (keys %suggest) { my $file = pkg_to_file($mod); next unless $INC{$file} || ($require && eval { require $file; 1 }); my $want = $suggest{$mod}; next if eval { $mod->VERSION($want); 1 }; my $error = $@; chomp $error; push @warn => " * Module '$mod' is outdated, we recommed updating above $want. error was: '$error'; INC is $INC{$file}"; } for my $mod (keys %required) { my $file = pkg_to_file($mod); next unless $INC{$file} || ($require && eval { require $file; 1 }); my $want = $required{$mod}; next if eval { $mod->VERSION($want); 1 }; push @warn => " * Module '$mod' is outdated and known to be broken, please update to $want or higher."; } for my $mod (keys %broken) { my $file = pkg_to_file($mod); next unless $INC{$file} || ($require && eval { require $file; 1 }); my $tested = $broken{$mod}; push @warn => " * Module '$mod' is known to be broken in version $tested and below, newer versions have not been tested. You have: " . $mod->VERSION; } return @warn; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::Breakage - What breaks at what version =head1 DESCRIPTION This module provides lists of modules that are broken, or have been broken in the past, when upgrading L to use L. =head1 FUNCTIONS These can be imported, or called as methods on the class. =over 4 =item %mod_ver = upgrade_suggested() =item %mod_ver = Test2::API::Breakage->upgrade_suggested() This returns key/value pairs. The key is the module name, the value is the version number. If the installed version of the module is at or below the specified one then an upgrade would be a good idea, but not strictly necessary. =item %mod_ver = upgrade_required() =item %mod_ver = Test2::API::Breakage->upgrade_required() This returns key/value pairs. The key is the module name, the value is the version number. If the installed version of the module is at or below the specified one then an upgrade is required for the module to work properly. =item %mod_ver = known_broken() =item %mod_ver = Test2::API::Breakage->known_broken() This returns key/value pairs. The key is the module name, the value is the version number. If the installed version of the module is at or below the specified one then the module will not work. A newer version may work, but is not tested or verified. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ûUþþperl5/Test2/API/Stack.pmnuÏÃ6Ç$package Test2::API::Stack; use strict; use warnings; our $VERSION = '1.302183'; use Test2::Hub(); use Carp qw/confess/; sub new { my $class = shift; return bless [], $class; } sub new_hub { my $self = shift; my %params = @_; my $class = delete $params{class} || 'Test2::Hub'; my $hub = $class->new(%params); if (@$self) { $hub->inherit($self->[-1], %params); } else { require Test2::API; $hub->format(Test2::API::test2_formatter()->new_root) unless $hub->format || exists($params{formatter}); my $ipc = Test2::API::test2_ipc(); if ($ipc && !$hub->ipc && !exists($params{ipc})) { $hub->set_ipc($ipc); $ipc->add_hub($hub->hid); } } push @$self => $hub; $hub; } sub top { my $self = shift; return $self->new_hub unless @$self; return $self->[-1]; } sub peek { my $self = shift; return @$self ? $self->[-1] : undef; } sub cull { my $self = shift; $_->cull for reverse @$self; } sub all { my $self = shift; return @$self; } sub root { my $self = shift; return unless @$self; return $self->[0]; } sub clear { my $self = shift; @$self = (); } # Do these last without keywords in order to prevent them from getting used # when we want the real push/pop. { no warnings 'once'; *push = sub { my $self = shift; my ($hub) = @_; $hub->inherit($self->[-1]) if @$self; push @$self => $hub; }; *pop = sub { my $self = shift; my ($hub) = @_; confess "No hubs on the stack" unless @$self; confess "You cannot pop the root hub" if 1 == @$self; confess "Hub stack mismatch, attempted to pop incorrect hub" unless $self->[-1] == $hub; pop @$self; }; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::Stack - Object to manage a stack of L instances. =head1 ***INTERNALS NOTE*** B The public methods provided will not change in backwards incompatible ways, but the underlying implementation details might. B =head1 DESCRIPTION This module is used to represent and manage a stack of L objects. Hubs are usually in a stack so that you can push a new hub into place that can intercept and handle events differently than the primary hub. =head1 SYNOPSIS my $stack = Test2::API::Stack->new; my $hub = $stack->top; =head1 METHODS =over 4 =item $stack = Test2::API::Stack->new() This will create a new empty stack instance. All arguments are ignored. =item $hub = $stack->new_hub() =item $hub = $stack->new_hub(%params) =item $hub = $stack->new_hub(%params, class => $class) This will generate a new hub and push it to the top of the stack. Optionally you can provide arguments that will be passed into the constructor for the L object. If you specify the C<< 'class' => $class >> argument, the new hub will be an instance of the specified class. Unless your parameters specify C<'formatter'> or C<'ipc'> arguments, the formatter and IPC instance will be inherited from the current top hub. You can set the parameters to C to avoid having a formatter or IPC instance. If there is no top hub, and you do not ask to leave IPC and formatter undef, then a new formatter will be created, and the IPC instance from L will be used. =item $hub = $stack->top() This will return the top hub from the stack. If there is no top hub yet this will create it. =item $hub = $stack->peek() This will return the top hub from the stack. If there is no top hub yet this will return undef. =item $stack->cull This will call C<< $hub->cull >> on all hubs in the stack. =item @hubs = $stack->all This will return all the hubs in the stack as a list. =item $stack->clear This will completely remove all hubs from the stack. Normally you do not want to do this, but there are a few valid reasons for it. =item $stack->push($hub) This will push the new hub onto the stack. =item $stack->pop($hub) This will pop a hub from the stack, if the hub at the top of the stack does not match the hub you expect (passed in as an argument) it will throw an exception. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!u³geèFèF"perl5/Test2/API/InterceptResult.pmnuÏÃ6Ç$package Test2::API::InterceptResult; use strict; use warnings; our $VERSION = '1.302183'; use Scalar::Util qw/blessed/; use Test2::Util qw/pkg_to_file/; use Storable qw/dclone/; use Carp qw/croak/; use Test2::API::InterceptResult::Squasher; use Test2::API::InterceptResult::Event; use Test2::API::InterceptResult::Hub; sub new { croak "Called a method that creates a new instance in void context" unless defined wantarray; my $class = shift; bless([@_], $class); } sub new_from_ref { croak "Called a method that creates a new instance in void context" unless defined wantarray; bless($_[1], $_[0]); } sub clone { blessed($_[0])->new(@{dclone($_[0])}) } sub event_list { @{$_[0]} } sub _upgrade { my $self = shift; my ($event, %params) = @_; my $blessed = blessed($event); my $upgrade_class = $params{upgrade_class} ||= 'Test2::API::InterceptResult::Event'; return $event if $blessed && $event->isa($upgrade_class) && !$params{_upgrade_clone}; my $fd = dclone($blessed ? $event->facet_data : $event); my $class = $params{result_class} ||= blessed($self); if (my $parent = $fd->{parent}) { $parent->{children} = $class->new_from_ref($parent->{children} || [])->upgrade(%params); } my $uc_file = pkg_to_file($upgrade_class); require($uc_file) unless $INC{$uc_file}; return $upgrade_class->new(facet_data => $fd, result_class => $class); } sub hub { my $self = shift; my $hub = Test2::API::InterceptResult::Hub->new(); $hub->process($_) for @$self; $hub->set_ended(1); return $hub; } sub state { my $self = shift; my %params = @_; my $hub = $self->hub; my $out = { map {($_ => scalar $hub->$_)} qw/count failed is_passing plan bailed_out skip_reason/ }; $out->{bailed_out} = $self->_upgrade($out->{bailed_out}, %params)->bailout_reason || 1 if $out->{bailed_out}; $out->{follows_plan} = $hub->check_plan; return $out; } sub upgrade { my $self = shift; my %params = @_; my @out = map { $self->_upgrade($_, %params, _upgrade_clone => 1) } @$self; return blessed($self)->new_from_ref(\@out) unless $params{in_place}; @$self = @out; return $self; } sub squash_info { my $self = shift; my %params = @_; my @out; { my $squasher = Test2::API::InterceptResult::Squasher->new(events => \@out); # Clone to make sure we do not indirectly modify an existing one if it # is already upgraded $squasher->process($self->_upgrade($_, %params)->clone) for @$self; $squasher->flush_down(); } return blessed($self)->new_from_ref(\@out) unless $params{in_place}; @$self = @out; return $self; } sub asserts { shift->grep(has_assert => @_) } sub subtests { shift->grep(has_subtest => @_) } sub diags { shift->grep(has_diags => @_) } sub notes { shift->grep(has_notes => @_) } sub errors { shift->grep(has_errors => @_) } sub plans { shift->grep(has_plan => @_) } sub causes_fail { shift->grep(causes_fail => @_) } sub causes_failure { shift->grep(causes_failure => @_) } sub flatten { shift->map(flatten => @_) } sub briefs { shift->map(brief => @_) } sub summaries { shift->map(summary => @_) } sub subtest_results { shift->map(subtest_result => @_) } sub diag_messages { shift->map(diag_messages => @_) } sub note_messages { shift->map(note_messages => @_) } sub error_messages { shift->map(error_messages => @_) } no warnings 'once'; *map = sub { my $self = shift; my ($call, %params) = @_; my $args = $params{args} ||= []; return [map { local $_ = $self->_upgrade($_, %params); $_->$call(@$args) } @$self]; }; *grep = sub { my $self = shift; my ($call, %params) = @_; my $args = $params{args} ||= []; my @out = grep { local $_ = $self->_upgrade($_, %params); $_->$call(@$args) } @$self; return blessed($self)->new_from_ref(\@out) unless $params{in_place}; @$self = @out; return $self; }; 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::InterceptResult - Representation of a list of events. =head1 DESCRIPTION This class represents a list of events, normally obtained using C from L. This class is intended for people who with to verify the results of test tools they write. This class provides methods to normalize, summarize, or map the list of events. The output of these operations makes verifying your testing tools and the events they generate significantly easier. In most cases this spares you from needing a deep understanding of the event/facet model. =head1 SYNOPSIS Usually you get an instance of this class when you use C from L. use Test2::V0; use Test2::API qw/intercept/; my $events = intercept { ok(1, "pass"); ok(0, "fail"); todo "broken" => sub { ok(0, "fixme") }; plan 3; }; # This is typically the most useful construct # squash_info() merges assertions and diagnostics that are associated # (and returns a new instance with the modifications) # flatten() condenses the facet data into the key details for each event # (and returns those structures in an arrayref) is( $events->squash_info->flatten(), [ { causes_failure => 0, name => 'pass', pass => 1, trace_file => 'xxx.t', trace_line => 5, }, { causes_failure => 1, name => 'fail', pass => 0, trace_file => 'xxx.t', trace_line => 6, # There can be more than one diagnostics message so this is # always an array when present. diag => ["Failed test 'fail'\nat xxx.t line 6."], }, { causes_failure => 0, name => 'fixme', pass => 0, trace_file => 'xxx.t', trace_line => 7, # There can be more than one diagnostics message or todo # reason, so these are always an array when present. todo => ['broken'], # Diag message was turned into a note since the assertion was # TODO note => ["Failed test 'fixme'\nat xxx.t line 7."], }, { causes_failure => 0, plan => 3, trace_file => 'xxx.t', trace_line => 8, }, ], "Flattened events look like we expect" ); See L for a full description of what C provides for each event. =head1 METHODS Please note that no methods modify the original instance unless asked to do so. =head2 CONSTRUCTION =over 4 =item $events = Test2::API::InterceptResult->new(@EVENTS) =item $events = Test2::API::InterceptResult->new_from_ref(\@EVENTS) These create a new instance of Test2::API::InterceptResult from the given events. In the first form a new blessed arrayref is returned. In the 'new_from_ref' form the reference you pass in is directly blessed. Both of these will throw an exception if called in void context. This is mainly important for the 'filtering' methods listed below which normally return a new instance, they throw an exception in such cases as it probably means someone meant to filter the original in place. =item $clone = $events->clone() Make a clone of the original events. Note that this is a deep copy, the entire structure is duplicated. This uses C from L to achieve the deep clone. =back =head2 NORMALIZATION =over 4 =item @events = $events->event_list This returns all the events in list-form. =item $hub = $events->hub This returns a new L instance that has processed all the events contained in the instance. This gives you a simple way to inspect the state changes your events cause. =item $state = $events->state This returns a summary of the state of a hub after processing all the events. { count => 2, # Number of assertions made failed => 1, # Number of test failures seen is_passing => 0, # Boolean, true if the test would be passing # after the events are processed. plan => 2, # Plan, either a number, undef, 'SKIP', or 'NO PLAN' follows_plan => 1, # True if there is a plan and it was followed. # False if the plan and assertions did not # match, undef if no plan was present in the # event list. bailed_out => undef, # undef unless there was a bail-out in the # events in which case this will be a string # explaining why there was a bailout, if no # reason was given this will simply be set to # true (1). skip_reason => undef, # If there was a skip_all this will give the # reason. } =item $new = $events->upgrade =item $events->upgrade(in_place => $BOOL) B This normally returns a new instance, leaving the original unchanged. If you call it in void context it will throw an exception. If you want to modify the original you must pass in the C<< in_place => 1 >> option. You may call this in void context when you ask to modify it in place. The in-place form returns the instance that was modified so you can chain methods. This will create a clone of the list where all events have been converted into L instances. This is extremely helpful as L provide a much better interface for working with events. This allows you to avoid thinking about legacy event types. This also means your tests against the list are not fragile if the tool you are testing randomly changes what type of events it generates (IE Changing from L to L, both make assertions and both will normalize to identical (or close enough) L instances. Really you almost always want this, the only reason it is not done automatically is to make sure the C tool is backwards compatible. =item $new = $events->squash_info =item $events->squash_info(in_place => $BOOL) B This normally returns a new instance, leaving the original unchanged. If you call it in void context it will throw an exception. If you want to modify the original you must pass in the C<< in_place => 1 >> option. You may call this in void context when you ask to modify it in place. The in-place form returns the instance that was modified so you can chain methods. B All events in the new or modified instance will be converted to L instances. There is no way to avoid this, the squash operation requires the upgraded event class. L and many other legacy tools would send notes, diags, and assertions as seperate events. A subtest in L would send a note with the subtest name, the subtest assertion, and finally a diagnostics event if the subtest failed. This method will normalize things by squashing the note and diag into the same event as the subtest (This is different from putting them into the subtest, which is not what happens). =back =head2 FILTERING B These normally return new instances, leaving the originals unchanged. If you call them in void context they will throw exceptions. If you want to modify the originals you must pass in the C<< in_place => 1 >> option. You may call these in void context when you ask to modify them in place. The in-place forms return the instance that was modified so you can chain methods. =head3 %PARAMS These all accept the same 2 optional parameters: =over 4 =item in_place => $BOOL When true the method will modify the instance in place instead of returning a new instance. =item args => \@ARGS If you wish to pass parameters into the event method being used for filtering, you may do so here. =back =head3 METHODS =over 4 =item $events->grep($CALL, %PARAMS) This is essentially: Test2::API::InterceptResult->new( grep { $_->$CALL( @{$PARAMS{args}} ) } $self->event_list, ); B that $CALL is called on an upgraded version of the event, though the events returned will be the original ones, not the upgraded ones. $CALL may be either the name of a method on L, or a coderef. =item $events->asserts(%PARAMS) This is essentially: $events->grep(has_assert => @{$PARAMS{args}}) It returns a new instance containing only the events that made assertions. =item $events->subtests(%PARAMS) This is essentially: $events->grep(has_subtest => @{$PARAMS{args}}) It returns a new instance containing only the events that have subtests. =item $events->diags(%PARAMS) This is essentially: $events->grep(has_diags => @{$PARAMS{args}}) It returns a new instance containing only the events that have diags. =item $events->notes(%PARAMS) This is essentially: $events->grep(has_notes => @{$PARAMS{args}}) It returns a new instance containing only the events that have notes. =item $events->errors(%PARAMS) B Errors are NOT failing assertions. Failing assertions are a different thing. This is essentially: $events->grep(has_errors => @{$PARAMS{args}}) It returns a new instance containing only the events that have errors. =item $events->plans(%PARAMS) This is essentially: $events->grep(has_plan => @{$PARAMS{args}}) It returns a new instance containing only the events that set the plan. =item $events->causes_fail(%PARAMS) =item $events->causes_failure(%PARAMS) These are essentially: $events->grep(causes_fail => @{$PARAMS{args}}) $events->grep(causes_failure => @{$PARAMS{args}}) B C and C are both aliases for eachother in events, so these methods are effectively aliases here as well. It returns a new instance containing only the events that cause failure. =back =head2 MAPPING These methods B return an arrayref. B No methods on L alter the event in any way. B: L was tailor-made to be used in event-lists. Most methods that are not applicable to a given event will return an empty list, so you normally do not need to worry about unwanted C values or exceptions being thrown. Mapping over event methods is an entended use, so it works well to produce lists. B Some methods such as C always return a boolean true or false for all events. Any method prefixed with C conveys the intent that the event should have exactly 1 of something, so those will throw an exception when that condition is not true. =over 4 =item $arrayref = $events->map($CALL, %PARAMS) This is essentially: [ map { $_->$CALL(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; $CALL may be either the name of a method on L, or a coderef. =item $arrayref = $events->flatten(%PARAMS) This is essentially: [ map { $_->flatten(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of flattened structures. See L for details on what C returns. =item $arrayref = $events->briefs(%PARAMS) This is essentially: [ map { $_->briefs(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of event briefs. See L for details on what C returns. =item $arrayref = $events->summaries(%PARAMS) This is essentially: [ map { $_->summaries(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of event summaries. See L for details on what C returns. =item $arrayref = $events->subtest_results(%PARAMS) This is essentially: [ map { $_->subtest_result(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of event summaries. See L for details on what C returns. =item $arrayref = $events->diag_messages(%PARAMS) This is essentially: [ map { $_->diag_messages(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of diagnostic messages (strings). See L for details on what C returns. =item $arrayref = $events->note_messages(%PARAMS) This is essentially: [ map { $_->note_messages(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of notification messages (strings). See L for details on what C returns. =item $arrayref = $events->error_messages(%PARAMS) This is essentially: [ map { $_->error_messages(@{ $PARAMS{args} }) } $events->upgrade->event_list ]; It returns a new list of error messages (strings). See L for details on what C returns. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!´Š:`ZZ+perl5/Test2/API/InterceptResult/Squasher.pmnuÏÃ6Ç$package Test2::API::InterceptResult::Squasher; use strict; use warnings; our $VERSION = '1.302183'; use Carp qw/croak/; use List::Util qw/first/; use Test2::Util::HashBase qw{ {+EVENTS}; } sub can_squash { my $self = shift; my ($event) = @_; # No info, no squash return unless $event->has_info; # Do not merge up if one of these is true return if first { $event->$_ } 'causes_fail', 'has_assert', 'has_bailout', 'has_errors', 'has_plan', 'has_subtest'; # Signature if we can squash return $event->trace_signature; } sub process { my $self = shift; my ($event) = @_; return if $self->squash_up($event); return if $self->squash_down($event); $self->flush_down($event); push @{$self->{+EVENTS}} => $event; return; } sub squash_down { my $self = shift; my ($event) = @_; my $sig = $self->can_squash($event) or return; $self->flush_down() if $self->{+DOWN_SIG} && $self->{+DOWN_SIG} ne $sig; $self->{+DOWN_SIG} ||= $sig; push @{$self->{+DOWN_BUFFER}} => $event; return 1; } sub flush_down { my $self = shift; my ($into) = @_; my $sig = delete $self->{+DOWN_SIG}; my $buffer = delete $self->{+DOWN_BUFFER}; return unless $buffer && @$buffer; my $fsig = $into ? $into->trace_signature : undef; if ($fsig && $fsig eq $sig) { $self->squash($into, @$buffer); } else { push @{$self->{+EVENTS}} => @$buffer if $buffer; } } sub clear_up { my $self = shift; return unless $self->{+UP_CLEAR}; delete $self->{+UP_INTO}; delete $self->{+UP_SIG}; delete $self->{+UP_CLEAR}; } sub squash_up { my $self = shift; my ($event) = @_; no warnings 'uninitialized'; $self->clear_up; if ($event->has_assert) { if(my $sig = $event->trace_signature) { $self->{+UP_INTO} = $event; $self->{+UP_SIG} = $sig; $self->{+UP_CLEAR} = 0; } else { $self->{+UP_CLEAR} = 1; $self->clear_up; } return; } my $into = $self->{+UP_INTO} or return; # Next iteration should clear unless something below changes that $self->{+UP_CLEAR} = 1; # Only merge into matching trace signatres my $sig = $self->can_squash($event); return unless $sig eq $self->{+UP_SIG}; # OK Merge! Do not clear merge in case the return event is also a matching sig diag-only $self->{+UP_CLEAR} = 0; $self->squash($into, $event); return 1; } sub squash { my $self = shift; my ($into, @from) = @_; push @{$into->facet_data->{info}} => $_->info for @from; } sub DESTROY { my $self = shift; return unless $self->{+EVENTS}; $self->flush_down(); return; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::InterceptResult::Squasher - Encapsulation of the algorithm that squashes diags into assertions. =head1 DESCRIPTION Internal use only, please ignore. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!‘¡‘ùÇÇ&perl5/Test2/API/InterceptResult/Hub.pmnuÏÃ6Ç$package Test2::API::InterceptResult::Hub; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::Hub; our @ISA = qw(Test2::Hub) } use Test2::Util::HashBase; sub init { my $self = shift; $self->SUPER::init(); $self->{+NESTED} = 0; } sub inherit { my $self = shift; $self->{+NESTED} = 0; } sub terminate { } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::InterceptResult::Hub - Hub used by InterceptResult. =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!ö�oÍÝoÝo(perl5/Test2/API/InterceptResult/Event.pmnuÏÃ6Ç$package Test2::API::InterceptResult::Event; use strict; use warnings; our $VERSION = '1.302183'; use List::Util qw/first/; use Test2::Util qw/pkg_to_file/; use Scalar::Util qw/reftype blessed/; use Storable qw/dclone/; use Carp qw/confess croak/; use Test2::API::InterceptResult::Facet; use Test2::API::InterceptResult::Hub; use Test2::Util::HashBase qw{ +causes_failure import( # We will replace the sub later require => 1, on_require_error => sub { 1 }, search_path => ['Test2::EventFacet'], max_depth => 3, min_depth => 3, ); for my $facet_type (__PACKAGE__->plugins) { my ($key, $list); eval { $key = $facet_type->facet_key; $list = $facet_type->is_list; }; next unless $key && defined($list); $FACETS{$key} = {list => $list, class => $facet_type, loaded => 1}; } } $FACETS{__GENERIC__} = {class => 'Test2::API::InterceptResult::Facet', loaded => 1}; } sub facet_map { \%FACETS } sub facet_info { my $facet = pop; return $FACETS{$facet} if exists $FACETS{$facet}; my $mname = ucfirst(lc($facet)); $mname =~ s/s$//; for my $name ($mname, "${mname}s") { my $file = "Test2/EventFacet/$name.pm"; my $class = "Test2::EventFacet::$name"; local $@; my $ok = eval { require $file; my $key = $class->facet_key; my $list = $class->is_list; $FACETS{$key} = {list => $list, class => $class, loaded => 1}; $FACETS{$facet} = $FACETS{$key} if $facet ne $key; 1; }; return $FACETS{$facet} if $ok && $FACETS{$facet}; } return $FACETS{$facet} = $FACETS{__GENERIC__}; } sub init { my $self = shift; my $rc = $self->{+RESULT_CLASS} ||= 'Test2::API::InterceptResult'; my $rc_file = pkg_to_file($rc); require($rc_file) unless $INC{$rc_file}; my $fd = $self->{+FACET_DATA} ||= {}; for my $facet (keys %$fd) { my $finfo = $self->facet_info($facet); my $is_list = $finfo->{list}; next unless defined $is_list; my $type = reftype($fd->{$facet}); if ($is_list) { confess "Facet '$facet' is a list facet, but got '$type' instead of an arrayref" unless $type eq 'ARRAY'; for my $item (@{$fd->{$facet}}) { my $itype = reftype($item); next if $itype eq 'HASH'; confess "Got item type '$itype' in list-facet '$facet', all items must be hashrefs"; } } else { confess "Facet '$facet' is an only-one facet, but got '$type' instead of a hashref" unless $type eq 'HASH'; } } } sub clone { my $self = shift; my $class = blessed($self); my %data = %$self; $data{+FACET_DATA} = dclone($data{+FACET_DATA}); return bless(\%data, $class); } sub _facet_class { my $self = shift; my ($name) = @_; my $spec = $self->facet_info($name); my $class = $spec->{class}; unless ($spec->{loaded}) { my $file = pkg_to_file($class); require $file unless $INC{$file}; $spec->{loaded} = 1; } return $class; } sub the_facet { my $self = shift; my ($name) = @_; return undef unless defined $self->{+FACET_DATA}->{$name}; my $data = $self->{+FACET_DATA}->{$name}; my $type = reftype($data) or confess "Facet '$name' has a value that is not a reference, this should not happen"; return $self->_facet_class($name)->new(%{dclone($data)}) if $type eq 'HASH'; if ($type eq 'ARRAY') { return undef unless @$data; croak "'the_facet' called for facet '$name', but '$name' has '" . @$data . "' items" if @$data != 1; return $self->_facet_class($name)->new(%{dclone($data->[0])}); } die "Invalid facet data type: $type"; } sub facet { my $self = shift; my ($name) = @_; return () unless exists $self->{+FACET_DATA}->{$name}; my $data = $self->{+FACET_DATA}->{$name}; my $type = reftype($data) or confess "Facet '$name' has a value that is not a reference, this should not happen"; my @out; @out = ($data) if $type eq 'HASH'; @out = (@$data) if $type eq 'ARRAY'; my $class = $self->_facet_class($name); return map { $class->new(%{dclone($_)}) } @out; } sub causes_failure { my $self = shift; return $self->{+CAUSES_FAILURE} if exists $self->{+CAUSES_FAILURE}; my $hub = Test2::API::InterceptResult::Hub->new(); $hub->process($self); return $self->{+CAUSES_FAILURE} = ($hub->is_passing ? 0 : 1); } sub causes_fail { shift->causes_failure } sub trace { $_[0]->facet('trace') } sub the_trace { $_[0]->the_facet('trace') } sub frame { my $t = $_[0]->the_trace or return undef; $t->{frame} || undef } sub trace_details { my $t = $_[0]->the_trace or return undef; $t->{details} || undef } sub trace_package { my $f = $_[0]->frame or return undef; $f->[0] || undef } sub trace_file { my $f = $_[0]->frame or return undef; $f->[1] || undef } sub trace_line { my $f = $_[0]->frame or return undef; $f->[2] || undef } sub trace_subname { my $f = $_[0]->frame or return undef; $f->[3] || undef } sub trace_tool { my $f = $_[0]->frame or return undef; $f->[3] || undef } sub trace_signature { my $t = $_[0]->the_trace or return undef; Test2::EventFacet::Trace::signature($t) || undef } sub brief { my $self = shift; my @try = qw{ bailout_brief error_brief assert_brief plan_brief }; for my $meth (@try) { my $got = $self->$meth or next; return $got; } return; } sub flatten { my $self = shift; my %params = @_; my $todo = {%{$self->{+FACET_DATA}}}; delete $todo->{hubs}; delete $todo->{meta}; delete $todo->{trace}; my $out = $self->summary; delete $out->{brief}; delete $out->{facets}; delete $out->{trace_tool}; delete $out->{trace_details} unless defined($out->{trace_details}); for my $tagged (grep { my $finfo = $self->facet_info($_); $finfo->{list} && $finfo->{class}->can('tag') } keys %FACETS, keys %$todo) { my $set = delete $todo->{$tagged} or next; my $fd = $self->{+FACET_DATA}; my $has_assert = $self->has_assert; my $has_parent = $self->has_subtest; my $has_fatal_error = $self->has_errors && grep { $_->{fail} } $self->errors; next if $tagged eq 'amnesty' && !($has_assert || $has_parent || $has_fatal_error); for my $item (@$set) { push @{$out->{lc($item->{tag})}} => $item->{fail} ? "FATAL: $item->{details}" : $item->{details}; } } if (my $assert = delete $todo->{assert}) { $out->{pass} = $assert->{pass}; $out->{name} = $assert->{details}; } if (my $parent = delete $todo->{parent}) { delete $out->{subtest}->{bailed_out} unless defined $out->{subtest}->{bailed_out}; delete $out->{subtest}->{skip_reason} unless defined $out->{subtest}->{skip_reason}; if (my $res = $self->subtest_result) { my $state = $res->state; delete $state->{$_} for grep { !defined($state->{$_}) } keys %$state; $out->{subtest} = $state; $out->{subevents} = $res->flatten(%params) if $params{include_subevents}; } } if (my $control = delete $todo->{control}) { if ($control->{halt}) { $out->{bailed_out} = $control->{details} || 1; } elsif(defined $control->{details}) { $out->{control} = $control->{details}; } } if (my $plan = delete $todo->{plan}) { $out->{plan} = $self->plan_brief; $out->{plan} =~ s/^PLAN\s*//; } for my $other (keys %$todo) { my $data = $todo->{$other} or next; if (reftype($data) eq 'ARRAY') { if (!$out->{$other} || reftype($out->{$other}) eq 'ARRAY') { for my $item (@$data) { push @{$out->{$other}} => $item->{details} if defined $item->{details}; } } } else { $out->{$other} = $data->{details} if defined($data->{details}) && !defined($out->{$other}); } } if (my $fields = $params{fields}) { $out = { map {exists($out->{$_}) ? ($_ => $out->{$_}) : ()} @$fields }; } if (my $remove = $params{remove}) { delete $out->{$_} for @$remove; } return $out; } sub summary { my $self = shift; my %params = @_; my $out = { brief => $self->brief || '', causes_failure => $self->causes_failure, trace_line => $self->trace_line, trace_file => $self->trace_file, trace_tool => $self->trace_subname, trace_details => $self->trace_details, facets => [ sort keys(%{$self->{+FACET_DATA}}) ], }; if (my $fields = $params{fields}) { $out = { map {exists($out->{$_}) ? ($_ => $out->{$_}) : ()} @$fields }; } if (my $remove = $params{remove}) { delete $out->{$_} for @$remove; } return $out; } sub has_assert { $_[0]->{+FACET_DATA}->{assert} ? 1 : 0 } sub the_assert { $_[0]->the_facet('assert') } sub assert { $_[0]->facet('assert') } sub assert_brief { my $self = shift; my $fd = $self->{+FACET_DATA}; my $as = $fd->{assert} or return; my $am = $fd->{amnesty}; my $out = $as->{pass} ? "PASS" : "FAIL"; $out .= " with amnesty" if $am; return $out; } sub has_subtest { $_[0]->{+FACET_DATA}->{parent} ? 1 : 0 } sub the_subtest { $_[0]->the_facet('parent') } sub subtest { $_[0]->facet('parent') } sub subtest_result { my $self = shift; my $parent = $self->{+FACET_DATA}->{parent} or return; my $children = $parent->{children} || []; $children = $self->{+RESULT_CLASS}->new(@$children)->upgrade unless blessed($children) && $children->isa($self->{+RESULT_CLASS}); return $children; } sub has_bailout { $_[0]->bailout ? 1 : 0 } sub the_bailout { my ($b) = $_[0]->bailout; $b } sub bailout { my $self = shift; my $control = $self->{+FACET_DATA}->{control} or return; return $control if $control->{halt}; return; } sub bailout_brief { my $self = shift; my $bo = $self->bailout or return; my $reason = $bo->{details} or return "BAILED OUT"; return "BAILED OUT: $reason"; } sub bailout_reason { my $self = shift; my $bo = $self->bailout or return; return $bo->{details} || ''; } sub has_plan { $_[0]->{+FACET_DATA}->{plan} ? 1 : 0 } sub the_plan { $_[0]->the_facet('plan') } sub plan { $_[0]->facet('plan') } sub plan_brief { my $self = shift; my $plan = $self->{+FACET_DATA}->{plan} or return; my $base = $self->_plan_brief($plan); my $reason = $plan->{details} or return $base; return "$base: $reason"; } sub _plan_brief { my $self = shift; my ($plan) = @_; return 'NO PLAN' if $plan->{none}; return "SKIP ALL" if $plan->{skip} || !$plan->{count}; return "PLAN $plan->{count}"; } sub has_amnesty { $_[0]->{+FACET_DATA}->{amnesty} ? 1 : 0 } sub the_amnesty { $_[0]->the_facet('amnesty') } sub amnesty { $_[0]->facet('amnesty') } sub amnesty_reasons { map { $_->{details} } $_[0]->amnesty } sub has_todos { &first(sub { uc($_->{tag}) eq 'TODO' }, $_[0]->amnesty) ? 1 : 0 } sub todos { grep { uc($_->{tag}) eq 'TODO' } $_[0]->amnesty } sub todo_reasons { map { $_->{details} || 'TODO' } $_[0]->todos } sub has_skips { &first(sub { uc($_->{tag}) eq 'SKIP' }, $_[0]->amnesty) ? 1 : 0 } sub skips { grep { uc($_->{tag}) eq 'SKIP' } $_[0]->amnesty } sub skip_reasons { map { $_->{details} || 'SKIP' } $_[0]->skips } my %TODO_OR_SKIP = (SKIP => 1, TODO => 1); sub has_other_amnesty { &first( sub { !$TODO_OR_SKIP{uc($_->{tag})} }, $_[0]->amnesty) ? 1 : 0 } sub other_amnesty { grep { !$TODO_OR_SKIP{uc($_->{tag})} } $_[0]->amnesty } sub other_amnesty_reasons { map { $_->{details} || $_->{tag} || 'AMNESTY' } $_[0]->other_amnesty } sub has_errors { $_[0]->{+FACET_DATA}->{errors} ? 1 : 0 } sub the_errors { $_[0]->the_facet('errors') } sub errors { $_[0]->facet('errors') } sub error_messages { map { $_->{details} || $_->{tag} || 'ERROR' } $_[0]->errors } sub error_brief { my $self = shift; my $errors = $self->{+FACET_DATA}->{errors} or return; my $base = @$errors > 1 ? "ERRORS" : "ERROR"; return $base unless @$errors; my ($msg, @extra) = split /[\n\r]+/, $errors->[0]->{details}; my $out = "$base: $msg"; $out .= " [...]" if @extra || @$errors > 1; return $out; } sub has_info { $_[0]->{+FACET_DATA}->{info} ? 1 : 0 } sub the_info { $_[0]->the_facet('info') } sub info { $_[0]->facet('info') } sub info_messages { map { $_->{details} } $_[0]->info } sub has_diags { &first(sub { uc($_->{tag}) eq 'DIAG' }, $_[0]->info) ? 1 : 0 } sub diags { grep { uc($_->{tag}) eq 'DIAG' } $_[0]->info } sub diag_messages { map { $_->{details} || 'DIAG' } $_[0]->diags } sub has_notes { &first(sub { uc($_->{tag}) eq 'NOTE' }, $_[0]->info) ? 1 : 0 } sub notes { grep { uc($_->{tag}) eq 'NOTE' } $_[0]->info } sub note_messages { map { $_->{details} || 'NOTE' } $_[0]->notes } my %NOTE_OR_DIAG = (NOTE => 1, DIAG => 1); sub has_other_info { &first(sub { !$NOTE_OR_DIAG{uc($_->{tag})} }, $_[0]->info) ? 1 : 0 } sub other_info { grep { !$NOTE_OR_DIAG{uc($_->{tag})} } $_[0]->info } sub other_info_messages { map { $_->{details} || $_->{tag} || 'INFO' } $_[0]->other_info } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::API::InterceptResult::Event - Representation of an event for use in testing other test tools. =head1 DESCRIPTION C from L returns an instance of L which is a blessed arrayref of L objects. This POD documents the methods of these events, which are mainly provided for you to use when testing your test tools. =head1 SYNOPSIS use Test2::V0; use Test2::API qw/intercept/; my $events = intercept { ok(1, "A passing assertion"); plan(1); }; # This will convert all events into instances of # Test2::API::InterceptResult::Event. Until we do this they are the # original Test::Event::* instances $events->upgrade(in_place => 1); # Now we can get individual events in this form my $assert = $events->[0]; my $plan = $events->[1]; # Or we can operate on all events at once: my $flattened = $events->flatten; is( $flattened, [ { causes_failure => 0, name => 'A passing assertion', pass => 1, trace_file => 'xxx.t', trace_line => 5, }, { causes_failure => 0, plan => 1, trace_file => 'xxx.t', trace_line => 6, }, ], "Flattened both events and returned an arrayref of the results ); =head1 METHODS =head2 !!! IMPORTANT NOTES ON DESIGN !!! Please pay attention to what these return, many return a scalar when applicable or an empty list when not (as opposed to undef). Many also always return a list of 0 or more items. Some always return a scalar. Note that none of the methods care about context, their behavior is consistent regardless of scalar, list, or void context. This was done because this class was specifically designed to be used in a list and generate more lists in bulk operations. Sometimes in a map you want nothing to show up for the event, and you do not want an undef in its place. In general single event instances are not going to be used alone, though that is allowed. As a general rule any method prefixed with C implies the event should have exactly 1 of the specified item, and and exception will be thrown if there are 0, or more than 1 of the item. =head2 ATTRIBUTES =over 4 =item $hashref = $event->facet_data This will return the facet data hashref, which is all Test2 cares about for any given event. =item $class = $event->result_class This is normally L. This is set at construction so that subtest results can be turned into instances of it on demand. =back =head2 DUPLICATION =over 4 =item $copy = $event->clone Create a deep copy of the event. Modifying either event will not effect the other. =back =head2 CONDENSED MULTI-FACET DATA =over 4 =item $bool = $event->causes_failure =item $bool = $event->causes_fail These are both aliases of the same functionality. This will always return either a true value, or a false value. This never returns a list. This method may be relatively slow (still super fast) because it determines pass or fail by creating an instance of L and asking it to process the event, and then asks the hub for its pass/fail state. This is slower than bulding in logic to do the check, but it is more reliable as it will always tell you what the hub thinks, so the logic will never be out of date relative to the Test2 logic that actually cares. =item STRING_OR_EMPTY_LIST = $event->brief Not all events have a brief, some events are not rendered by the formatter, others have no "brief" data worth seeing. When this is the case an empty list is returned. This is done intentionally so it can be used in a map operation without having C being included in the result. When a brief can be generated it is always a single 1-line string, and is returned as-is, not in a list. Possible briefs: # From control facets "BAILED OUT" "BAILED OUT: $why" # From error facets "ERROR" "ERROR: $message" "ERROR: $partial_message [...]" "ERRORS: $first_error_message [...]" # From assert facets "PASS" "FAIL" "PASS with amnesty" "FAIL with amnesty" # From plan facets "PLAN $count" "NO PLAN" "SKIP ALL" "SKIP ALL: $why" Note that only the first applicable brief is returned. This is essnetially a poor-mans TAP that only includes facets that could (but not necessarily do) cause a failure. =item $hashref = $event->flatten =item $hashref = $event->flatten(include_subevents => 1) This ALWAYS returns a hashref. This puts all the most useful data for the most interesting facets into a single hashref for easy validation. If there are no meaningful facets this will return an empty hashref. If given the 'include_subevents' parameter it will also include subtest data: Here is a list of EVERY possible field. If a field is not applicable it will not be present. =over 4 =item always present causes_failure => 1, # Always present =item Present if the event has a trace facet trace_line => 42, trace_file => 'Foo/Bar.pm', trace_details => 'Extra trace details', # usually not present =item If an assertion is present pass => 0, name => "1 + 1 = 2, so math works", =item If a plan is present: plan => $count_or_SKIP_ALL_or_NO_PLAN, =item If amnesty facets are present You get an array for each type that is present. todo => [ # Yes you could be under multiple todos, this will list them all. "I will fix this later", "I promise to fix these", ], skip => ["This will format the main drive, do not run"], ... => ["Other amnesty"] =item If Info (note/diag) facets are present You get an arrayref for any that are present, the key is not defined if they are not present. diag => [ "Test failed at Foo/Bar.pm line 42", "You forgot to tie your boots", ], note => ["Your boots are red"], ... => ["Other info"], =item If error facets are present Always an arrayref error => [ "non fatal error (does not cause test failure, just an FYI", "FATAL: This is a fatal error (causes failure)", ], # Errors can have alternative tags, but in practice are always 'error', # listing this for completeness. ... => [ ... ] =item Present if the event is a subtest subtest => { count => 2, # Number of assertions made failed => 1, # Number of test failures seen is_passing => 0, # Boolean, true if the test would be passing # after the events are processed. plan => 2, # Plan, either a number, undef, 'SKIP', or 'NO PLAN' follows_plan => 1, # True if there is a plan and it was followed. # False if the plan and assertions did not # match, undef if no plan was present in the # event list. bailed_out => "foo", # if there was a bail-out in the # events in this will be a string explaining # why there was a bailout, if no reason was # given this will simply be set to true (1). skip_reason => "foo", # If there was a skip_all this will give the # reason. }, if C<< (include_subtest => 1) >> was provided as a parameter then the following will be included. This is the result of turning all subtest child events into an L instance and calling the C method on it. subevents => Test2::API::InterceptResult->new(@child_events)->flatten(...), =item If a bail-out is being requested If no reason was given this will be set to 1. bailed_out => "reason", =back =item $hashref = $event->summary() This returns a limited summary. See C, which is usually a better option. { brief => $event->brief || '', causes_failure => $event->causes_failure, trace_line => $event->trace_line, trace_file => $event->trace_file, trace_tool => $event->trace_subname, trace_details => $event->trace_details, facets => [ sort keys(%{$event->{+FACET_DATA}}) ], } =back =head2 DIRECT ARBITRARY FACET ACCESS =over 4 =item @list_of_facets = $event->facet($name) This always returns a list of 0 or more items. This fetches the facet instances from the event. For facets like 'assert' this will always return 0 or 1 item. For events like 'info' (diags, notes) this will return 0 or more instances, once for each instance of the facet. These will be blessed into the proper L subclass. If no subclass can be found it will be blessed as an L generic facet class. =item $undef_or_facet = $event->the_facet($name) If you know you will have exactly 1 instance of a facet you can call this. If you are correct and there is exactly one instance of the facet it will always return the hashref. If there are 0 instances of the facet this will reutrn undef, not an empty list. If there are more than 1 instance this will throw an exception because your assumption was incorrect. =back =head2 TRACE FACET =over 4 =item @list_of_facets = $event->trace TODO =item $undef_or_hashref = $event->the_trace This returns the trace hashref, or undef if it is not present. =item $undef_or_arrayref = $event->frame If a trace is present, and has a caller frame, this will be an arrayref: [$package, $file, $line, $subname] If the trace is not present, or has no caller frame this will return undef. =item $undef_or_string = $event->trace_details This is usually undef, but occasionally has a string that overrides the file/line number debugging a trace usually provides on test failure. =item $undef_or_string = $event->trace_package Same as C<(caller())[0]>, the first element of the trace frame. Will be undef if not present. =item $undef_or_string = $event->trace_file Same as C<(caller())[1]>, the second element of the trace frame. Will be undef if not present. =item $undef_or_integer = $event->trace_line Same as C<(caller())[2]>, the third element of the trace frame. Will be undef if not present. =item $undef_or_string = $event->trace_subname =item $undef_or_string = $event->trace_tool Aliases for the same thing Same as C<(caller($level))[4]>, the fourth element of the trace frame. Will be undef if not present. =item $undef_or_string = $event->trace_signature A string that is a unique signature for the trace. If a single context generates multiple events they will all have the same signature. This can be used to tie assertions and diagnostics sent as seperate events together after the fact. =back =head2 ASSERT FACET =over 4 =item $bool = $event->has_assert Returns true if the event has an assert facet, false if it does not. =item $undef_or_hashref = $event->the_assert Returns the assert facet if present, undef if it is not. =item @list_of_facets = $event->assert TODO =item EMPTY_LIST_OR_STRING = $event->assert_brief Returns a string giving a brief of the assertion if an assertion is present. Returns an empty list if no assertion is present. =back =head2 SUBTESTS (PARENT FACET) =over 4 =item $bool = $event->has_subtest True if a subetest is present in this event. =item $undef_or_hashref = $event->the_subtest Get the one subtest if present, otherwise undef. =item @list_of_facets = $event->subtest TODO =item EMPTY_LIST_OR_OBJECT = $event->subtest_result Returns an empty list if there is no subtest. Get an instance of L representing the subtest. =back =head2 CONTROL FACET (BAILOUT, ENCODING) =over 4 =item $bool = $event->has_bailout True if there was a bailout =item $undef_hashref = $event->the_bailout Return the control facet if it requested a bailout. =item EMPTY_LIST_OR_HASHREF = $event->bailout Get a list of 0 or 1 hashrefs. The hashref will be the control facet if a bail-out was requested. =item EMPTY_LIST_OR_STRING = $event->bailout_brief Get the brief of the balout if present. =item EMPTY_LIST_OR_STRING = $event->bailout_reason Get the reason for the bailout, an empty string if no reason was provided, or an empty list if there was no bailout. =back =head2 PLAN FACET TODO =over 4 =item $bool = $event->has_plan =item $undef_or_hashref = $event->the_plan =item @list_if_hashrefs = $event->plan =item EMPTY_LIST_OR_STRING $event->plan_brief =back =head2 AMNESTY FACET (TODO AND SKIP) TODO =over 4 =item $event->has_amnesty =item $event->the_amnesty =item $event->amnesty =item $event->amnesty_reasons =item $event->has_todos =item $event->todos =item $event->todo_reasons =item $event->has_skips =item $event->skips =item $event->skip_reasons =item $event->has_other_amnesty =item $event->other_amnesty =item $event->other_amnesty_reasons =back =head2 ERROR FACET (CAPTURED EXCEPTIONS) TODO =over 4 =item $event->has_errors =item $event->the_errors =item $event->errors =item $event->error_messages =item $event->error_brief =back =head2 INFO FACET (DIAG, NOTE) TODO =over 4 =item $event->has_info =item $event->the_info =item $event->info =item $event->info_messages =item $event->has_diags =item $event->diags =item $event->diag_messages =item $event->has_notes =item $event->notes =item $event->note_messages =item $event->has_other_info =item $event->other_info =item $event->other_info_messages =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!&RI||(perl5/Test2/API/InterceptResult/Facet.pmnuÏÃ6Ç$package Test2::API::InterceptResult::Facet; use strict; use warnings; our $VERSION = '1.302183'; BEGIN { require Test2::EventFacet; our @ISA = ('Test2::EventFacet'); } our $AUTOLOAD; sub AUTOLOAD { my $self = shift; my $name = $AUTOLOAD; $name =~ s/^.*:://g; return undef unless exists $self->{$name}; return $self->{$name}; } sub DESTROY {} 1; PK!ïrî¸f f perl5/Test2/IPC.pmnuÏÃ6Ç$package Test2::IPC; use strict; use warnings; our $VERSION = '1.302183'; use Test2::API::Instance; use Test2::Util qw/get_tid/; use Test2::API qw{ test2_in_preload test2_init_done test2_ipc test2_has_ipc test2_ipc_enable_polling test2_pid test2_stack test2_tid context }; # Make sure stuff is finalized before anyone tried to fork or start a new thread. { # Avoid warnings if things are loaded at run-time no warnings 'void'; INIT { use warnings 'void'; context()->release() unless test2_in_preload(); } } use Carp qw/confess/; our @EXPORT_OK = qw/cull/; BEGIN { require Exporter; our @ISA = qw(Exporter) } sub unimport { Test2::API::test2_ipc_disable() } sub import { goto &Exporter::import if test2_has_ipc || !test2_init_done(); confess "IPC is disabled" if Test2::API::test2_ipc_disabled(); confess "Cannot add IPC in a child process (" . test2_pid() . " vs $$)" if test2_pid() != $$; confess "Cannot add IPC in a child thread (" . test2_tid() . " vs " . get_tid() . ")" if test2_tid() != get_tid(); Test2::API::_set_ipc(_make_ipc()); apply_ipc(test2_stack()); goto &Exporter::import; } sub _make_ipc { # Find a driver my ($driver) = Test2::API::test2_ipc_drivers(); unless ($driver) { require Test2::IPC::Driver::Files; $driver = 'Test2::IPC::Driver::Files'; } return $driver->new(); } sub apply_ipc { my $stack = shift; my ($root) = @$stack; return unless $root; confess "Cannot add IPC in a child process" if $root->pid != $$; confess "Cannot add IPC in a child thread" if $root->tid != get_tid(); my $ipc = $root->ipc || test2_ipc() || _make_ipc(); # Add the IPC to all hubs for my $hub (@$stack) { my $has = $hub->ipc; confess "IPC Mismatch!" if $has && $has != $ipc; next if $has; $hub->set_ipc($ipc); $ipc->add_hub($hub->hid); } test2_ipc_enable_polling(); return $ipc; } sub cull { my $ctx = context(); $ctx->hub->cull; $ctx->release; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::IPC - Turn on IPC for threading or forking support. =head1 SYNOPSIS You should C as early as possible in your test file. If you import this module after API initialization it will attempt to retrofit IPC onto the existing hubs. =head2 DISABLING IT You can use C to disable IPC for good. You can also use the T2_NO_IPC env var. =head1 EXPORTS All exports are optional. =over 4 =item cull() Cull allows you to collect results from other processes or threads on demand. =back =head1 SOURCE The source code repository for Test2 can be found at F. =head1 MAINTAINERS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 AUTHORS =over 4 =item Chad Granum Eexodist@cpan.orgE =back =head1 COPYRIGHT Copyright 2020 Chad Granum Eexodist@cpan.orgE. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F =cut PK!¤ô!GØsØsperl5/Capture/Tiny.pmnuÏÃ6Ç$use 5.006; use strict; use warnings; package Capture::Tiny; # ABSTRACT: Capture STDOUT and STDERR from Perl, XS or external programs our $VERSION = '0.48'; use Carp (); use Exporter (); use IO::Handle (); use File::Spec (); use File::Temp qw/tempfile tmpnam/; use Scalar::Util qw/reftype blessed/; # Get PerlIO or fake it BEGIN { local $@; eval { require PerlIO; PerlIO->can('get_layers') } or *PerlIO::get_layers = sub { return () }; } #--------------------------------------------------------------------------# # create API subroutines and export them # [do STDOUT flag, do STDERR flag, do merge flag, do tee flag] #--------------------------------------------------------------------------# my %api = ( capture => [1,1,0,0], capture_stdout => [1,0,0,0], capture_stderr => [0,1,0,0], capture_merged => [1,1,1,0], tee => [1,1,0,1], tee_stdout => [1,0,0,1], tee_stderr => [0,1,0,1], tee_merged => [1,1,1,1], ); for my $sub ( keys %api ) { my $args = join q{, }, @{$api{$sub}}; eval "sub $sub(&;@) {unshift \@_, $args; goto \\&_capture_tee;}"; ## no critic } our @ISA = qw/Exporter/; our @EXPORT_OK = keys %api; our %EXPORT_TAGS = ( 'all' => \@EXPORT_OK ); #--------------------------------------------------------------------------# # constants and fixtures #--------------------------------------------------------------------------# my $IS_WIN32 = $^O eq 'MSWin32'; ##our $DEBUG = $ENV{PERL_CAPTURE_TINY_DEBUG}; ## ##my $DEBUGFH; ##open $DEBUGFH, "> DEBUG" if $DEBUG; ## ##*_debug = $DEBUG ? sub(@) { print {$DEBUGFH} @_ } : sub(){0}; our $TIMEOUT = 30; #--------------------------------------------------------------------------# # command to tee output -- the argument is a filename that must # be opened to signal that the process is ready to receive input. # This is annoying, but seems to be the best that can be done # as a simple, portable IPC technique #--------------------------------------------------------------------------# my @cmd = ($^X, '-C0', '-e', <<'HERE'); use Fcntl; $SIG{HUP}=sub{exit}; if ( my $fn=shift ) { sysopen(my $fh, qq{$fn}, O_WRONLY|O_CREAT|O_EXCL) or die $!; print {$fh} $$; close $fh; } my $buf; while (sysread(STDIN, $buf, 2048)) { syswrite(STDOUT, $buf); syswrite(STDERR, $buf); } HERE #--------------------------------------------------------------------------# # filehandle manipulation #--------------------------------------------------------------------------# sub _relayer { my ($fh, $apply_layers) = @_; # _debug("# requested layers (@{$layers}) for @{[fileno $fh]}\n"); # eliminate pseudo-layers binmode( $fh, ":raw" ); # strip off real layers until only :unix is left while ( 1 < ( my $layers =()= PerlIO::get_layers( $fh, output => 1 ) ) ) { binmode( $fh, ":pop" ); } # apply other layers my @to_apply = @$apply_layers; shift @to_apply; # eliminate initial :unix # _debug("# applying layers (unix @to_apply) to @{[fileno $fh]}\n"); binmode($fh, ":" . join(":",@to_apply)); } sub _name { my $glob = shift; no strict 'refs'; ## no critic return *{$glob}{NAME}; } sub _open { open $_[0], $_[1] or Carp::confess "Error from open(" . join(q{, }, @_) . "): $!"; # _debug( "# open " . join( ", " , map { defined $_ ? _name($_) : 'undef' } @_ ) . " as " . fileno( $_[0] ) . "\n" ); } sub _close { # _debug( "# closing " . ( defined $_[0] ? _name($_[0]) : 'undef' ) . " on " . fileno( $_[0] ) . "\n" ); close $_[0] or Carp::confess "Error from close(" . join(q{, }, @_) . "): $!"; } my %dup; # cache this so STDIN stays fd0 my %proxy_count; sub _proxy_std { my %proxies; if ( ! defined fileno STDIN ) { $proxy_count{stdin}++; if (defined $dup{stdin}) { _open \*STDIN, "<&=" . fileno($dup{stdin}); # _debug( "# restored proxy STDIN as " . (defined fileno STDIN ? fileno STDIN : 'undef' ) . "\n" ); } else { _open \*STDIN, "<" . File::Spec->devnull; # _debug( "# proxied STDIN as " . (defined fileno STDIN ? fileno STDIN : 'undef' ) . "\n" ); _open $dup{stdin} = IO::Handle->new, "<&=STDIN"; } $proxies{stdin} = \*STDIN; binmode(STDIN, ':utf8') if $] >= 5.008; ## no critic } if ( ! defined fileno STDOUT ) { $proxy_count{stdout}++; if (defined $dup{stdout}) { _open \*STDOUT, ">&=" . fileno($dup{stdout}); # _debug( "# restored proxy STDOUT as " . (defined fileno STDOUT ? fileno STDOUT : 'undef' ) . "\n" ); } else { _open \*STDOUT, ">" . File::Spec->devnull; # _debug( "# proxied STDOUT as " . (defined fileno STDOUT ? fileno STDOUT : 'undef' ) . "\n" ); _open $dup{stdout} = IO::Handle->new, ">&=STDOUT"; } $proxies{stdout} = \*STDOUT; binmode(STDOUT, ':utf8') if $] >= 5.008; ## no critic } if ( ! defined fileno STDERR ) { $proxy_count{stderr}++; if (defined $dup{stderr}) { _open \*STDERR, ">&=" . fileno($dup{stderr}); # _debug( "# restored proxy STDERR as " . (defined fileno STDERR ? fileno STDERR : 'undef' ) . "\n" ); } else { _open \*STDERR, ">" . File::Spec->devnull; # _debug( "# proxied STDERR as " . (defined fileno STDERR ? fileno STDERR : 'undef' ) . "\n" ); _open $dup{stderr} = IO::Handle->new, ">&=STDERR"; } $proxies{stderr} = \*STDERR; binmode(STDERR, ':utf8') if $] >= 5.008; ## no critic } return %proxies; } sub _unproxy { my (%proxies) = @_; # _debug( "# unproxying: " . join(" ", keys %proxies) . "\n" ); for my $p ( keys %proxies ) { $proxy_count{$p}--; # _debug( "# unproxied " . uc($p) . " ($proxy_count{$p} left)\n" ); if ( ! $proxy_count{$p} ) { _close $proxies{$p}; _close $dup{$p} unless $] < 5.008; # 5.6 will have already closed this as dup delete $dup{$p}; } } } sub _copy_std { my %handles; for my $h ( qw/stdout stderr stdin/ ) { next if $h eq 'stdin' && ! $IS_WIN32; # WIN32 hangs on tee without STDIN copied my $redir = $h eq 'stdin' ? "<&" : ">&"; _open $handles{$h} = IO::Handle->new(), $redir . uc($h); # ">&STDOUT" or "<&STDIN" } return \%handles; } # In some cases we open all (prior to forking) and in others we only open # the output handles (setting up redirection) sub _open_std { my ($handles) = @_; _open \*STDIN, "<&" . fileno $handles->{stdin} if defined $handles->{stdin}; _open \*STDOUT, ">&" . fileno $handles->{stdout} if defined $handles->{stdout}; _open \*STDERR, ">&" . fileno $handles->{stderr} if defined $handles->{stderr}; } #--------------------------------------------------------------------------# # private subs #--------------------------------------------------------------------------# sub _start_tee { my ($which, $stash) = @_; # $which is "stdout" or "stderr" # setup pipes $stash->{$_}{$which} = IO::Handle->new for qw/tee reader/; pipe $stash->{reader}{$which}, $stash->{tee}{$which}; # _debug( "# pipe for $which\: " . _name($stash->{tee}{$which}) . " " . fileno( $stash->{tee}{$which} ) . " => " . _name($stash->{reader}{$which}) . " " . fileno( $stash->{reader}{$which}) . "\n" ); select((select($stash->{tee}{$which}), $|=1)[0]); # autoflush # setup desired redirection for parent and child $stash->{new}{$which} = $stash->{tee}{$which}; $stash->{child}{$which} = { stdin => $stash->{reader}{$which}, stdout => $stash->{old}{$which}, stderr => $stash->{capture}{$which}, }; # flag file is used to signal the child is ready $stash->{flag_files}{$which} = scalar( tmpnam() ) . $$; # execute @cmd as a separate process if ( $IS_WIN32 ) { my $old_eval_err=$@; undef $@; eval "use Win32API::File qw/GetOsFHandle SetHandleInformation fileLastError HANDLE_FLAG_INHERIT INVALID_HANDLE_VALUE/ "; # _debug( "# Win32API::File loaded\n") unless $@; my $os_fhandle = GetOsFHandle( $stash->{tee}{$which} ); # _debug( "# Couldn't get OS handle: " . fileLastError() . "\n") if ! defined $os_fhandle || $os_fhandle == INVALID_HANDLE_VALUE(); my $result = SetHandleInformation( $os_fhandle, HANDLE_FLAG_INHERIT(), 0); # _debug( $result ? "# set no-inherit flag on $which tee\n" : ("# can't disable tee handle flag inherit: " . fileLastError() . "\n")); _open_std( $stash->{child}{$which} ); $stash->{pid}{$which} = system(1, @cmd, $stash->{flag_files}{$which}); # not restoring std here as it all gets redirected again shortly anyway $@=$old_eval_err; } else { # use fork _fork_exec( $which, $stash ); } } sub _fork_exec { my ($which, $stash) = @_; # $which is "stdout" or "stderr" my $pid = fork; if ( not defined $pid ) { Carp::confess "Couldn't fork(): $!"; } elsif ($pid == 0) { # child # _debug( "# in child process ...\n" ); untie *STDIN; untie *STDOUT; untie *STDERR; _close $stash->{tee}{$which}; # _debug( "# redirecting handles in child ...\n" ); _open_std( $stash->{child}{$which} ); # _debug( "# calling exec on command ...\n" ); exec @cmd, $stash->{flag_files}{$which}; } $stash->{pid}{$which} = $pid } my $have_usleep = eval "use Time::HiRes 'usleep'; 1"; sub _files_exist { return 1 if @_ == grep { -f } @_; Time::HiRes::usleep(1000) if $have_usleep; return 0; } sub _wait_for_tees { my ($stash) = @_; my $start = time; my @files = values %{$stash->{flag_files}}; my $timeout = defined $ENV{PERL_CAPTURE_TINY_TIMEOUT} ? $ENV{PERL_CAPTURE_TINY_TIMEOUT} : $TIMEOUT; 1 until _files_exist(@files) || ($timeout && (time - $start > $timeout)); Carp::confess "Timed out waiting for subprocesses to start" if ! _files_exist(@files); unlink $_ for @files; } sub _kill_tees { my ($stash) = @_; if ( $IS_WIN32 ) { # _debug( "# closing handles\n"); close($_) for values %{ $stash->{tee} }; # _debug( "# waiting for subprocesses to finish\n"); my $start = time; 1 until wait == -1 || (time - $start > 30); } else { _close $_ for values %{ $stash->{tee} }; waitpid $_, 0 for values %{ $stash->{pid} }; } } sub _slurp { my ($name, $stash) = @_; my ($fh, $pos) = map { $stash->{$_}{$name} } qw/capture pos/; # _debug( "# slurping captured $name from " . fileno($fh) . " at pos $pos with layers: @{[PerlIO::get_layers($fh)]}\n"); seek( $fh, $pos, 0 ) or die "Couldn't seek on capture handle for $name\n"; my $text = do { local $/; scalar readline $fh }; return defined($text) ? $text : ""; } #--------------------------------------------------------------------------# # _capture_tee() -- generic main sub for capturing or teeing #--------------------------------------------------------------------------# sub _capture_tee { # _debug( "# starting _capture_tee with (@_)...\n" ); my ($do_stdout, $do_stderr, $do_merge, $do_tee, $code, @opts) = @_; my %do = ($do_stdout ? (stdout => 1) : (), $do_stderr ? (stderr => 1) : ()); Carp::confess("Custom capture options must be given as key/value pairs\n") unless @opts % 2 == 0; my $stash = { capture => { @opts } }; for ( keys %{$stash->{capture}} ) { my $fh = $stash->{capture}{$_}; Carp::confess "Custom handle for $_ must be seekable\n" unless ref($fh) eq 'GLOB' || (blessed($fh) && $fh->isa("IO::Seekable")); } # save existing filehandles and setup captures local *CT_ORIG_STDIN = *STDIN ; local *CT_ORIG_STDOUT = *STDOUT; local *CT_ORIG_STDERR = *STDERR; # find initial layers my %layers = ( stdin => [PerlIO::get_layers(\*STDIN) ], stdout => [PerlIO::get_layers(\*STDOUT, output => 1)], stderr => [PerlIO::get_layers(\*STDERR, output => 1)], ); # _debug( "# existing layers for $_\: @{$layers{$_}}\n" ) for qw/stdin stdout stderr/; # get layers from underlying glob of tied filehandles if we can # (this only works for things that work like Tie::StdHandle) $layers{stdout} = [PerlIO::get_layers(tied *STDOUT)] if tied(*STDOUT) && (reftype tied *STDOUT eq 'GLOB'); $layers{stderr} = [PerlIO::get_layers(tied *STDERR)] if tied(*STDERR) && (reftype tied *STDERR eq 'GLOB'); # _debug( "# tied object corrected layers for $_\: @{$layers{$_}}\n" ) for qw/stdin stdout stderr/; # bypass scalar filehandles and tied handles # localize scalar STDIN to get a proxy to pick up FD0, then restore later to CT_ORIG_STDIN my %localize; $localize{stdin}++, local(*STDIN) if grep { $_ eq 'scalar' } @{$layers{stdin}}; $localize{stdout}++, local(*STDOUT) if $do_stdout && grep { $_ eq 'scalar' } @{$layers{stdout}}; $localize{stderr}++, local(*STDERR) if ($do_stderr || $do_merge) && grep { $_ eq 'scalar' } @{$layers{stderr}}; $localize{stdin}++, local(*STDIN), _open( \*STDIN, "<&=0") if tied *STDIN && $] >= 5.008; $localize{stdout}++, local(*STDOUT), _open( \*STDOUT, ">&=1") if $do_stdout && tied *STDOUT && $] >= 5.008; $localize{stderr}++, local(*STDERR), _open( \*STDERR, ">&=2") if ($do_stderr || $do_merge) && tied *STDERR && $] >= 5.008; # _debug( "# localized $_\n" ) for keys %localize; # proxy any closed/localized handles so we don't use fds 0, 1 or 2 my %proxy_std = _proxy_std(); # _debug( "# proxy std: @{ [%proxy_std] }\n" ); # update layers after any proxying $layers{stdout} = [PerlIO::get_layers(\*STDOUT, output => 1)] if $proxy_std{stdout}; $layers{stderr} = [PerlIO::get_layers(\*STDERR, output => 1)] if $proxy_std{stderr}; # _debug( "# post-proxy layers for $_\: @{$layers{$_}}\n" ) for qw/stdin stdout stderr/; # store old handles and setup handles for capture $stash->{old} = _copy_std(); $stash->{new} = { %{$stash->{old}} }; # default to originals for ( keys %do ) { $stash->{new}{$_} = ($stash->{capture}{$_} ||= File::Temp->new); seek( $stash->{capture}{$_}, 0, 2 ) or die "Could not seek on capture handle for $_\n"; $stash->{pos}{$_} = tell $stash->{capture}{$_}; # _debug("# will capture $_ on " . fileno($stash->{capture}{$_})."\n" ); _start_tee( $_ => $stash ) if $do_tee; # tees may change $stash->{new} } _wait_for_tees( $stash ) if $do_tee; # finalize redirection $stash->{new}{stderr} = $stash->{new}{stdout} if $do_merge; # _debug( "# redirecting in parent ...\n" ); _open_std( $stash->{new} ); # execute user provided code my ($exit_code, $inner_error, $outer_error, $orig_pid, @result); { $orig_pid = $$; local *STDIN = *CT_ORIG_STDIN if $localize{stdin}; # get original, not proxy STDIN # _debug( "# finalizing layers ...\n" ); _relayer(\*STDOUT, $layers{stdout}) if $do_stdout; _relayer(\*STDERR, $layers{stderr}) if $do_stderr; # _debug( "# running code $code ...\n" ); my $old_eval_err=$@; undef $@; eval { @result = $code->(); $inner_error = $@ }; $exit_code = $?; # save this for later $outer_error = $@; # save this for later STDOUT->flush if $do_stdout; STDERR->flush if $do_stderr; $@ = $old_eval_err; } # restore prior filehandles and shut down tees # _debug( "# restoring filehandles ...\n" ); _open_std( $stash->{old} ); _close( $_ ) for values %{$stash->{old}}; # don't leak fds # shouldn't need relayering originals, but see rt.perl.org #114404 _relayer(\*STDOUT, $layers{stdout}) if $do_stdout; _relayer(\*STDERR, $layers{stderr}) if $do_stderr; _unproxy( %proxy_std ); # _debug( "# killing tee subprocesses ...\n" ) if $do_tee; _kill_tees( $stash ) if $do_tee; # return captured output, but shortcut in void context # unless we have to echo output to tied/scalar handles; my %got; if ( $orig_pid == $$ and ( defined wantarray or ($do_tee && keys %localize) ) ) { for ( keys %do ) { _relayer($stash->{capture}{$_}, $layers{$_}); $got{$_} = _slurp($_, $stash); # _debug("# slurped " . length($got{$_}) . " bytes from $_\n"); } print CT_ORIG_STDOUT $got{stdout} if $do_stdout && $do_tee && $localize{stdout}; print CT_ORIG_STDERR $got{stderr} if $do_stderr && $do_tee && $localize{stderr}; } $? = $exit_code; $@ = $inner_error if $inner_error; die $outer_error if $outer_error; # _debug( "# ending _capture_tee with (@_)...\n" ); return unless defined wantarray; my @return; push @return, $got{stdout} if $do_stdout; push @return, $got{stderr} if $do_stderr && ! $do_merge; push @return, @result; return wantarray ? @return : $return[0]; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Capture::Tiny - Capture STDOUT and STDERR from Perl, XS or external programs =head1 VERSION version 0.48 =head1 SYNOPSIS use Capture::Tiny ':all'; # capture from external command ($stdout, $stderr, $exit) = capture { system( $cmd, @args ); }; # capture from arbitrary code (Perl or external) ($stdout, $stderr, @result) = capture { # your code here }; # capture partial or merged output $stdout = capture_stdout { ... }; $stderr = capture_stderr { ... }; $merged = capture_merged { ... }; # tee output ($stdout, $stderr) = tee { # your code here }; $stdout = tee_stdout { ... }; $stderr = tee_stderr { ... }; $merged = tee_merged { ... }; =head1 DESCRIPTION Capture::Tiny provides a simple, portable way to capture almost anything sent to STDOUT or STDERR, regardless of whether it comes from Perl, from XS code or from an external program. Optionally, output can be teed so that it is captured while being passed through to the original filehandles. Yes, it even works on Windows (usually). Stop guessing which of a dozen capturing modules to use in any particular situation and just use this one. =head1 USAGE The following functions are available. None are exported by default. =head2 capture ($stdout, $stderr, @result) = capture \&code; $stdout = capture \&code; The C function takes a code reference and returns what is sent to STDOUT and STDERR as well as any return values from the code reference. In scalar context, it returns only STDOUT. If no output was received for a filehandle, it returns an empty string for that filehandle. Regardless of calling context, all output is captured -- nothing is passed to the existing filehandles. It is prototyped to take a subroutine reference as an argument. Thus, it can be called in block form: ($stdout, $stderr) = capture { # your code here ... }; Note that the coderef is evaluated in list context. If you wish to force scalar context on the return value, you must use the C keyword. ($stdout, $stderr, $count) = capture { my @list = qw/one two three/; return scalar @list; # $count will be 3 }; Also note that within the coderef, the C<@_> variable will be empty. So don't use arguments from a surrounding subroutine without copying them to an array first: sub wont_work { my ($stdout, $stderr) = capture { do_stuff( @_ ) }; # WRONG ... } sub will_work { my @args = @_; my ($stdout, $stderr) = capture { do_stuff( @args ) }; # RIGHT ... } Captures are normally done to an anonymous temporary filehandle. To capture via a named file (e.g. to externally monitor a long-running capture), provide custom filehandles as a trailing list of option pairs: my $out_fh = IO::File->new("out.txt", "w+"); my $err_fh = IO::File->new("out.txt", "w+"); capture { ... } stdout => $out_fh, stderr => $err_fh; The filehandles must be read/write and seekable. Modifying the files or filehandles during a capture operation will give unpredictable results. Existing IO layers on them may be changed by the capture. When called in void context, C saves memory and time by not reading back from the capture handles. =head2 capture_stdout ($stdout, @result) = capture_stdout \&code; $stdout = capture_stdout \&code; The C function works just like C except only STDOUT is captured. STDERR is not captured. =head2 capture_stderr ($stderr, @result) = capture_stderr \&code; $stderr = capture_stderr \&code; The C function works just like C except only STDERR is captured. STDOUT is not captured. =head2 capture_merged ($merged, @result) = capture_merged \&code; $merged = capture_merged \&code; The C function works just like C except STDOUT and STDERR are merged. (Technically, STDERR is redirected to the same capturing handle as STDOUT before executing the function.) Caution: STDOUT and STDERR output in the merged result are not guaranteed to be properly ordered due to buffering. =head2 tee ($stdout, $stderr, @result) = tee \&code; $stdout = tee \&code; The C function works just like C, except that output is captured as well as passed on to the original STDOUT and STDERR. When called in void context, C saves memory and time by not reading back from the capture handles, except when the original STDOUT OR STDERR were tied or opened to a scalar handle. =head2 tee_stdout ($stdout, @result) = tee_stdout \&code; $stdout = tee_stdout \&code; The C function works just like C except only STDOUT is teed. STDERR is not teed (output goes to STDERR as usual). =head2 tee_stderr ($stderr, @result) = tee_stderr \&code; $stderr = tee_stderr \&code; The C function works just like C except only STDERR is teed. STDOUT is not teed (output goes to STDOUT as usual). =head2 tee_merged ($merged, @result) = tee_merged \&code; $merged = tee_merged \&code; The C function works just like C except that output is captured as well as passed on to STDOUT. Caution: STDOUT and STDERR output in the merged result are not guaranteed to be properly ordered due to buffering. =head1 LIMITATIONS =head2 Portability Portability is a goal, not a guarantee. C requires fork, except on Windows where C is used instead. Not tested on any particularly esoteric platforms yet. See the L for test result by platform. =head2 PerlIO layers Capture::Tiny does its best to preserve PerlIO layers such as ':utf8' or ':crlf' when capturing (only for Perl 5.8.1+) . Layers should be applied to STDOUT or STDERR I the call to C or C. This may not work for tied filehandles (see below). =head2 Modifying filehandles before capturing Generally speaking, you should do little or no manipulation of the standard IO filehandles prior to using Capture::Tiny. In particular, closing, reopening, localizing or tying standard filehandles prior to capture may cause a variety of unexpected, undesirable and/or unreliable behaviors, as described below. Capture::Tiny does its best to compensate for these situations, but the results may not be what you desire. =head3 Closed filehandles Capture::Tiny will work even if STDIN, STDOUT or STDERR have been previously closed. However, since they will be reopened to capture or tee output, any code within the captured block that depends on finding them closed will, of course, not find them to be closed. If they started closed, Capture::Tiny will close them again when the capture block finishes. Note that this reopening will happen even for STDIN or a filehandle not being captured to ensure that the filehandle used for capture is not opened to file descriptor 0, as this causes problems on various platforms. Prior to Perl 5.12, closed STDIN combined with PERL_UNICODE=D leaks filehandles and also breaks tee() for undiagnosed reasons. So don't do that. =head3 Localized filehandles If code localizes any of Perl's standard filehandles before capturing, the capture will affect the localized filehandles and not the original ones. External system calls are not affected by localizing a filehandle in Perl and will continue to send output to the original filehandles (which will thus not be captured). =head3 Scalar filehandles If STDOUT or STDERR are reopened to scalar filehandles prior to the call to C or C, then Capture::Tiny will override the output filehandle for the duration of the C or C call and then, for C, send captured output to the output filehandle after the capture is complete. (Requires Perl 5.8) Capture::Tiny attempts to preserve the semantics of STDIN opened to a scalar reference, but note that external processes will not be able to read from such a handle. Capture::Tiny tries to ensure that external processes will read from the null device instead, but this is not guaranteed. =head3 Tied output filehandles If STDOUT or STDERR are tied prior to the call to C or C, then Capture::Tiny will attempt to override the tie for the duration of the C or C call and then send captured output to the tied filehandle after the capture is complete. (Requires Perl 5.8) Capture::Tiny may not succeed resending UTF-8 encoded data to a tied STDOUT or STDERR filehandle. Characters may appear as bytes. If the tied filehandle is based on L, then Capture::Tiny will attempt to determine appropriate layers like C<:utf8> from the underlying filehandle and do the right thing. =head3 Tied input filehandle Capture::Tiny attempts to preserve the semantics of tied STDIN, but this requires Perl 5.8 and is not entirely predictable. External processes will not be able to read from such a handle. Unless having STDIN tied is crucial, it may be safest to localize STDIN when capturing: my ($out, $err) = do { local *STDIN; capture { ... } }; =head2 Modifying filehandles during a capture Attempting to modify STDIN, STDOUT or STDERR I C or C is almost certainly going to cause problems. Don't do that. =head3 Forking inside a capture Forks aren't portable. The behavior of filehandles during a fork is even less so. If Capture::Tiny detects that a fork has occurred within a capture, it will shortcut in the child process and return empty strings for captures. Other problems may occur in the child or parent, as well. Forking in a capture block is not recommended. =head3 Using threads Filehandles are global. Mixing up I/O and captures in different threads without coordination is going to cause problems. Besides, threads are officially discouraged. =head3 Dropping privileges during a capture If you drop privileges during a capture, temporary files created to facilitate the capture may not be cleaned up afterwards. =head2 No support for Perl 5.8.0 It's just too buggy when it comes to layers and UTF-8. Perl 5.8.1 or later is recommended. =head2 Limited support for Perl 5.6 Perl 5.6 predates PerlIO. UTF-8 data may not be captured correctly. =head1 ENVIRONMENT =head2 PERL_CAPTURE_TINY_TIMEOUT Capture::Tiny uses subprocesses internally for C. By default, Capture::Tiny will timeout with an error if such subprocesses are not ready to receive data within 30 seconds (or whatever is the value of C<$Capture::Tiny::TIMEOUT>). An alternate timeout may be specified by setting the C environment variable. Setting it to zero will disable timeouts. B, this does not timeout the code reference being captured -- this only prevents Capture::Tiny itself from hanging your process waiting for its child processes to be ready to proceed. =head1 SEE ALSO This module was inspired by L, which provides similar functionality without the ability to tee output and with more complicated code and API. L does not handle layers or most of the unusual cases described in the L section and I no longer recommend it. There are many other CPAN modules that provide some sort of output capture, albeit with various limitations that make them appropriate only in particular circumstances. I'm probably missing some. The long list is provided to show why I felt Capture::Tiny was necessary. =over 4 =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =back =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone https://github.com/dagolden/Capture-Tiny.git =head1 AUTHOR David Golden =head1 CONTRIBUTORS =for stopwords Dagfinn Ilmari MannsÃ¥ker David E. Wheeler fecundf Graham Knop Peter Rabbitson =over 4 =item * Dagfinn Ilmari MannsÃ¥ker =item * David E. Wheeler =item * fecundf =item * Graham Knop =item * Peter Rabbitson =back =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2009 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut PK!uP`y7y7 perl5/HDB.pmnuÏÃ6Ç$############################################################################# ## Name: HDB.pm ## Purpose: HDB - Hybrid database ## Author: Graciliano M. P. ## Modified by: ## Created: 06/01/2003 ## RCS-ID: ## Copyright: (c) 2003 Graciliano M. P. ## Licence: This program is free software; you can redistribute it and/or ## modify it under the same terms as Perl itself ############################################################################# package HDB ; use 5.006 ; use strict qw(vars) ; use vars qw(@ISA $AUTOLOAD) ; no warnings ; our ($VERSION) ; $VERSION = '1.05' ; my $REQUIRED ; ########### # REQUIRE # ########### sub REQUIRE { return if $REQUIRED ; require HDB::CORE ; require HDB::CMDS ; require HDB::Encode ; require HDB::MOD ; require HDB::Object ; $REQUIRED = 1 ; } ########## # SCOPES # ########## use vars qw($HPL_Run_MAIN $HPL_Run_NOW) ; *HPL_Run_MAIN = \$HPL::Run::MAIN ; *HPL_Run_NOW = \$HPL::Run::NOW ; ############ # HPL_MAIN # ############ sub HPL_MAIN { return $HPL_Run_MAIN if UNIVERSAL::isa($HPL_Run_MAIN,'UNIVERSAL') ; return $main::HPL if UNIVERSAL::isa($main::HPL,'UNIVERSAL') ; return ${"main::HPL"} ; } ######## # VARS # ######## my %args_types = ( file => [qw(file dbfile databasefile db database)] , db => [qw(db database)] , host => [[qw(host hostname)],localhost] , user => [qw(user username)] , pass => [qw(pass password)] , type => [[qw(type dbtype databasetype dbd)],auto] , cache => [[qw(cache)],1] , id => [qw(id ident)] , warning => [[qw(warning warnings error errors alert alerts carp)],1] , dynamic => [[qw(dynamic dyn)],1] , conf_hpl => [qw(confhpl hplconf)] , ); my (%PASS , %DB , $WITH_HPL , %MOD_LOADED , $RESET_X) ; ########## # IMPORT # ########## sub import { my $class = shift ; if ($_[0] =~ /HPL/i) { $WITH_HPL = 1 ; &REQUIRE() ; } } ############ # AUTOLOAD # ############ sub AUTOLOAD { if ( $#_ == 0 && ref($_[0]) && UNIVERSAL::isa($_[0],'HDB') ) { if ( ref($_[0]) eq 'HDB' ) { my $this = shift ; my $type = $this->{MOD}{type} ; bless($this , "HDB::MOD::$type") ; $this->connect ; my ($method) = ( $AUTOLOAD =~ /(\w+)$/s ); $this->$method(@_) ; } my ($table) = ( $AUTOLOAD =~ /(\w+)$/s ) ; my $TABLE_OBJ = HDB::TABLE->new($_[0] , $table) ; return $TABLE_OBJ ; } if (ref($_[0])) { my @caller = caller ; &HDB::Error(undef,qq`Can't find $AUTOLOAD at $caller[1] line $caller[2]!`) ; return undef ; } my ($id0) = ( $AUTOLOAD =~ /(\w+)$/ ) ; my $id = lc($id0) ; if ( $WITH_HPL && $id ne '' ) { my $hpl = &HPL_MAIN() ; if ( $hpl ) { my $hpl_root = $hpl->pack_root ; if ( $id eq 'hploo' && !${"$hpl_root\::MYHDB::DB"}{$id} ) { $id = (sort keys %{"$hpl_root\::MYHDB::DB"})[0] ; if ( $id ) { $hpl->warn(qq`HDB id HPLOO not defined, using 1st defined DB for HDB::Object persistence.` , 1) ; ${"$hpl_root\::MYHDB::DB"}{hploo} = ${"$hpl_root\::MYHDB::DB"}{$id} ; } } my $obj = ${"$hpl_root\::MYHDB::DB"}{$id} ; if (!$obj) { $hpl->warn(qq`Can't find HDB id "$id" for dynamic access $_[0]\->$id0 !`) ;} return $obj ; } } else { if (! $DB{$id}) { &HDB::Error(undef,qq`Can't find HDB id "$id" for dynamic access $_[0]\->$id0 !`) ;} return $DB{$id} ; } return undef ; } ########### # ALIASES # ########### sub WITH_HPL { $WITH_HPL ;} sub open { if ( ref $_[0] && UNIVERSAL::isa($_[0],'HDB') ) { $_[0]->connect ; return $_[0] ; } else { return &new(@_) ;} } sub close { $_[0]->disconnect ;} ####### # NEW # ####### sub new { &REQUIRE() ; my $class = shift ; my $this = {} ; &HDB::CORE::parse_args($this , \%args_types , @_) ; $this->{file} = &HDB::CORE::path($this->{file}) if defined $this->{file} ; $this->{id} =~ s/\W//s ; $this->{id} = lc( $this->{id} ) ; if ( $this->{type} eq 'auto' ) { if ( defined $this->{file} ) { $this->{type} = 'sqlite' ;} else { $this->{type} = 'mysql' ;} } else { my $type = $this->{type} ; $this->{type} =~ s/\W//gs ; $this->{type} = lc( $this->{type} ) ; } return Error($this,"Invalid type!") if $this->{type} eq '' ; my $type = $this->{type} ; if ( !&_require_module($type) ) { return Error($this,"Can't find HDB module for $type (HDB::MOD::$type)!") ;} &{"HDB::MOD::$type\::new"}($this) ; return $this->Error("Error on loanding HDB module $type (HDB::MOD::$type)!") if !$this ; if ( ($this->{conf_hpl} || $WITH_HPL ) && $this->{file} ) { my $hpl = &HPL_MAIN() ; if ( defined $hpl->env->{DOCUMENT_ROOT} ) { $this->{file} =~ s/^[\/\\][\/\\]/$hpl->env->{DOCUMENT_ROOT}/se ; } } ## "HIDDE" PASS: $PASS{$this} = $this->{pass} ; delete $this->{pass} ; eval { $this->connect }; if ( !$this || !$this->connected || !$this->dbh ) { $this->Error("Can't connect to DB. Load error!") ; return ;} if ($this->{dynamic} && $this->{id} ne '') { if ( $WITH_HPL ) { $this->{WITH_HPL} = 1 ; my $hpl = &HPL_MAIN() ; if ( $hpl ) { my $hpl_root = $hpl->pack_root ; ${"$hpl_root\::MYHDB::DB"}{ $this->{id} } = $this ; } } else { $DB{ $this->{id} } = $this ;} } if ( $WITH_HPL ) { $this->dbh->{HandleError} = \&HPL_show_error ; } return $this ; } ################## # HPL_SHOW_ERROR # ################## sub HPL_show_error { my $hpl = &HPL_MAIN() ; $hpl->warn($_[0]) if $hpl ; return $_[2] ; } ########### # CONNECT # ########### sub connect { if ( $_[0]->{dbh} ) { return $_[0]->{dbh} ;} $_[0]->MOD_connect( $PASS{$_[0]} ) ; return $_[0]->{dbh} ; } ############# # RECONNECT # ############# sub reconnect { $_[0]->disconnect ; $_[0]->connect ; } ######### # ERROR # ######### sub Error { if ( $_[0]->{sth} ) { $_[0]->{sth}->finish ; $_[0]->{sth} = undef ; } if ($_[0] && !$_[0]->{warning}) { return ;} if ($_[0] && ref $_[0]->{warning} eq 'CODE') { &{$_[0]->{warning}}($_[1]) } else { if ($WITH_HPL) { my $hpl = &HPL_MAIN() ; $hpl->warn($_[1] , $_[2]) if $hpl ; } else { eval { require Carp ; Carp::carp($_[1]) ; }; } } return ; } ################### # _REQUIRE_MODULE # ################### sub _require_module { my ( $module ) = @_ ; return 1 if $MOD_LOADED{$module} ; eval("require HDB::MOD::$module ;") ; return undef if $@ ; return $MOD_LOADED{$module} = 1 ; } ########### # DESTROY # ########### sub DESTROY { delete $PASS{$_[0]} ; $_[0]->disconnect ; } ######### # RESET # ######### sub RESET { ++$RESET_X ; HDB::Object::RESET() if defined &HDB::Object::RESET && (!$WITH_HPL || $RESET_X > 10) ; if ( $WITH_HPL ) { my $hpl = &HPL_MAIN() ; if ( $hpl ) { my $HDB_LINKED = \%{ $hpl->pack_root ."::MYHDB::DB"} ; %$HDB_LINKED = () ; undef %$HDB_LINKED ; eval { foreach my $Key ( keys %$HDB_LINKED ) { $$HDB_LINKED{$Key}->UNLINK ;} }; } } %DB = () ; HDB::Parser::RESET() if defined &HDB::Parser::RESET && (!$WITH_HPL || $RESET_X > 10) ; $RESET_X = 0 if $RESET_X > 10 ; return 1 ; } sub END { &RESET } ######### # TABLE # ######### sub TABLE { HDB::TABLE->new(@_) ;} ############## # HDB::TABLE # ############## package HDB::TABLE ; use vars qw($AUTOLOAD) ; ####### # NEW # ####### sub new { bless({ hdb => $_[1] , table => $_[2] , },$_[0]) ; } sub DESTROY { ##print main::STDOUT "DESTROY>> @_\n" ; } sub AUTOLOAD { my $obj = shift ; my ($method) = ( $AUTOLOAD =~ /(\w+)$/s ) ; my $class = ref $obj->{hdb} ; return ($obj->{hdb})->$method($obj->{table} , @_) ; } ############# # HDB::CMDS # ############# package HDB::CMDS ; sub default_types { require HDB::CMDS ; &default_types ;} sub predefined_columns { require HDB::CMDS ; &predefined_columns ;} sub default_mod { require HDB::CMDS ; &default_mod ;} ####### # END # ####### 1; __END__ =head1 NAME HDB - Hybrid Database - Handles multiple databases with the same interface. =head1 DESCRIPTION B. With it you B that you are using. HDB will make all the work around between the differences of any database. From HDB you still can use DBI and SQL commands if needed, but this won't be portable between database types. If you use only HDB querys (not DBI) B For example, you can test/develope your code in your desktop (let's say Win32) with SQLite, and send your code to the Server (Linux), where you use MySQL. HDB borns like a module to access in a easy way MySQL databases from HPL Documents. From HPL6, when it was fully rewrited, the module MYSQL was rewrited too and called HDB, where the resources were expanded for other DB types, like SQLite. Also HDB was turned into a Perl module, that can run independent of HPL when not called from it. =head1 USAGE use HDB ; my $HDB = HDB->new( type => 'sqlite' , file => 'test.db' , ) ; ... or ... my $HDB = HDB->new( type => 'mysql' , host => 'some.domain.com' , user => 'foo' , pass => 'bar' , ) ; $HDB->create('users',[ 'user' => 100 , 'name' => 100 , 'age' => 'int(200)' , 'more' => 1024*4 , ]); $HDB->insert( 'users' , { user => 'joe' , name => 'joe tribianny' , age => '30' , } ) ; ... or ... $HDB->users->insert( { user => 'joe' , name => 'joe tribianny' , age => '30' , } ) ; ... my @sel = $HDB->select('users' , 'name =~ joe' , '@%' ) ; foreach my $sel_i ( @sel ) { my %cols = %$sel_i ; ... } ... my $hdbhandle = $HDB->select('users' , '<%>'); while( my %cols = <$hdbhandle> ) { foreach my $Key ( keys %cols ) { print "$Key = $cols{$Key}\n" ;} ... } ... $HDB->update('users' , 'user eq joe' , { user => 'JoeT' } ) ... $HDB->disconnect ; =head1 METHODS =head2 new Create the HDB object connected to the DB. B =over 10 =item FILE File for flat databases, like SQLite. =item DB The database name. =item HOST The host of the database server. If omited and needed will use "localhost". =item USER The user for connection. =item PASS The password for connection. =item TYPE The database type. See modules inside HDB/MOD for installed names. =item CACHE (boolean) Turn on/off the cache of sth and col names. =item ID Set a global ID for dynamic access. =item DYNAMIC (boolean) Enable/disable the dynamic acess. =item WARNING (boolean) Turn on/off errors/warnings. =back =head2 open Alias for new. =head2 connect Connect to the database. Note, no arguments are needed, they will be get from the object. ** Password will be hidden inside the class, not int the object. =head2 disconnect Disconnect the database and free any sth or cache. =head2 reconnect Disconnect, if needed, and reconnect the database. =head2 dbh Use to access in the DBI way: $HDB->dbh->do("select * from users") ; ... my $sth = $HDB->dbh->prepare("INSERT INTO users VALUES (?, ?, ?)") ; $sth->execute("joe", "Joe Tribiany", "joe\friends.com") ; You can use I too: $HDB->dbi->do("select * from users") ; B<** Try to avoid this way to keep your code portable between database types and OS>. =head1 COMMANDS METHODS ** See L for usage. B select, insert, update, delete, create, drop, cmd, names, tables, table_columns... =head1 DYNAMIC ACCESS You can access the database connection without have the object variable. With this you have a global access to any connection with the ID set. The Dynamic Access allow the use of a table as a method too: $HDB->users->select('name == joe'); Since the table is always the first argument, HDB will paste the fake method (table name) to the CMD (select) as the fisrt argument. ** Note that the name of the table can't be a HDB method. =head2 USAGE my $HDB = HDB->new( type => 'mysql' , db => 'test' , user => 'joe' , pass => '12345' , id => 'TEST' ; ) ; ... HDB->TEST->select(users , 'user == joe'); ... my $HDB = HDB->TEST ; $HDB->users->update('name == joe',{name => 'Jeff'}) ; ... or ... my $table_users = $HDB->TABLE(users) ; $table_users->update('name == joe',{name => 'Jeff'}) ; ... or ... HDB->TEST->users->update('name == joe',{name => 'Jeff'}) ; ... B<** Dynamic access is used for global connections in HPL (connections set in the config file: .conf.hpl).> =head1 HDB::Object - Persistent Objects An automatic persistence framework was built over HDB, where is possible to create persistent classes in a easy and fast way. HDB was designed to handle any type of DB behind it, what extends the persistence framework to any DB that DBI can handle with standart SQL. Take a look at L. =head1 SEE ALSO L, L, L, L. L, L. =head1 AUTHOR Graciliano M. P. I will appreciate any type of feedback (include your opinions and/or suggestions). ;-P =head1 COPYRIGHT This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!Ñ ŒÄO¢O¢perl5/local/lib.pmnuÏÃ6Ç$package local::lib; use 5.006; BEGIN { if ($ENV{RELEASE_TESTING}) { require strict; strict->import; require warnings; warnings->import; } } use Config (); our $VERSION = '2.000029'; $VERSION =~ tr/_//d; BEGIN { *_WIN32 = ($^O eq 'MSWin32' || $^O eq 'NetWare' || $^O eq 'symbian') ? sub(){1} : sub(){0}; # punt on these systems *_USE_FSPEC = ($^O eq 'MacOS' || $^O eq 'VMS' || $INC{'File/Spec.pm'}) ? sub(){1} : sub(){0}; } my $_archname = $Config::Config{archname}; my $_version = $Config::Config{version}; my @_inc_version_list = reverse split / /, $Config::Config{inc_version_list}; my $_path_sep = $Config::Config{path_sep}; our $_DIR_JOIN = _WIN32 ? '\\' : '/'; our $_DIR_SPLIT = (_WIN32 || $^O eq 'cygwin') ? qr{[\\/]} : qr{/}; our $_ROOT = _WIN32 ? do { my $UNC = qr{[\\/]{2}[^\\/]+[\\/][^\\/]+}; qr{^(?:$UNC|[A-Za-z]:|)$_DIR_SPLIT}; } : qr{^/}; our $_PERL; sub _perl { if (!$_PERL) { # untaint and validate ($_PERL, my $exe) = $^X =~ /((?:.*$_DIR_SPLIT)?(.+))/; $_PERL = 'perl' if $exe !~ /perl/; if (_is_abs($_PERL)) { } elsif (-x $Config::Config{perlpath}) { $_PERL = $Config::Config{perlpath}; } elsif ($_PERL =~ $_DIR_SPLIT && -x $_PERL) { $_PERL = _rel2abs($_PERL); } else { ($_PERL) = map { /(.*)/ } grep { -x $_ } map { ($_, _WIN32 ? ("$_.exe") : ()) } map { join($_DIR_JOIN, $_, $_PERL) } split /\Q$_path_sep\E/, $ENV{PATH}; } } $_PERL; } sub _cwd { if (my $cwd = defined &Cwd::sys_cwd ? \&Cwd::sys_cwd : defined &Cwd::cwd ? \&Cwd::cwd : undef ) { no warnings 'redefine'; *_cwd = $cwd; goto &$cwd; } my $drive = shift; return Win32::GetCwd() if _WIN32 && defined &Win32::GetCwd && !$drive; local @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)}; delete @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)}; my $cmd = $drive ? "eval { Cwd::getdcwd(q($drive)) }" : 'getcwd'; my $perl = _perl; my $cwd = `"$perl" -MCwd -le "print $cmd"`; chomp $cwd; if (!length $cwd && $drive) { $cwd = $drive; } $cwd =~ s/$_DIR_SPLIT?$/$_DIR_JOIN/; $cwd; } sub _catdir { if (_USE_FSPEC) { require File::Spec; File::Spec->catdir(@_); } else { my $dir = join($_DIR_JOIN, @_); $dir =~ s{($_DIR_SPLIT)(?:\.?$_DIR_SPLIT)+}{$1}g; $dir; } } sub _is_abs { if (_USE_FSPEC) { require File::Spec; File::Spec->file_name_is_absolute($_[0]); } else { $_[0] =~ $_ROOT; } } sub _rel2abs { my ($dir, $base) = @_; return $dir if _is_abs($dir); $base = _WIN32 && $dir =~ s/^([A-Za-z]:)// ? _cwd("$1") : $base ? _rel2abs($base) : _cwd; return _catdir($base, $dir); } our $_DEVNULL; sub _devnull { return $_DEVNULL ||= _USE_FSPEC ? (require File::Spec, File::Spec->devnull) : _WIN32 ? 'nul' : $^O eq 'os2' ? '/dev/nul' : '/dev/null'; } sub import { my ($class, @args) = @_; if ($0 eq '-') { push @args, @ARGV; require Cwd; } my @steps; my %opts; my %attr; my $shelltype; while (@args) { my $arg = shift @args; # check for lethal dash first to stop processing before causing problems # the fancy dash is U+2212 or \xE2\x88\x92 if ($arg =~ /\xE2\x88\x92/) { die <<'DEATH'; WHOA THERE! It looks like you've got some fancy dashes in your commandline! These are *not* the traditional -- dashes that software recognizes. You probably got these by copy-pasting from the perldoc for this module as rendered by a UTF8-capable formatter. This most typically happens on an OS X terminal, but can happen elsewhere too. Please try again after replacing the dashes with normal minus signs. DEATH } elsif ($arg eq '--self-contained') { die <<'DEATH'; FATAL: The local::lib --self-contained flag has never worked reliably and the original author, Mark Stosberg, was unable or unwilling to maintain it. As such, this flag has been removed from the local::lib codebase in order to prevent misunderstandings and potentially broken builds. The local::lib authors recommend that you look at the lib::core::only module shipped with this distribution in order to create a more robust environment that is equivalent to what --self-contained provided (although quite possibly not what you originally thought it provided due to the poor quality of the documentation, for which we apologise). DEATH } elsif( $arg =~ /^--deactivate(?:=(.*))?$/ ) { my $path = defined $1 ? $1 : shift @args; push @steps, ['deactivate', $path]; } elsif ( $arg eq '--deactivate-all' ) { push @steps, ['deactivate_all']; } elsif ( $arg =~ /^--shelltype(?:=(.*))?$/ ) { $shelltype = defined $1 ? $1 : shift @args; } elsif ( $arg eq '--no-create' ) { $opts{no_create} = 1; } elsif ( $arg eq '--quiet' ) { $attr{quiet} = 1; } elsif ( $arg eq '--always' ) { $attr{always} = 1; } elsif ( $arg =~ /^--/ ) { die "Unknown import argument: $arg"; } else { push @steps, ['activate', $arg, \%opts]; } } if (!@steps) { push @steps, ['activate', undef, \%opts]; } my $self = $class->new(%attr); for (@steps) { my ($method, @args) = @$_; $self = $self->$method(@args); } if ($0 eq '-') { print $self->environment_vars_string($shelltype); exit 0; } else { $self->setup_local_lib; } } sub new { my $class = shift; bless {@_}, $class; } sub clone { my $self = shift; bless {%$self, @_}, ref $self; } sub inc { $_[0]->{inc} ||= \@INC } sub libs { $_[0]->{libs} ||= [ \'PERL5LIB' ] } sub bins { $_[0]->{bins} ||= [ \'PATH' ] } sub roots { $_[0]->{roots} ||= [ \'PERL_LOCAL_LIB_ROOT' ] } sub extra { $_[0]->{extra} ||= {} } sub quiet { $_[0]->{quiet} } sub _as_list { my $list = shift; grep length, map { !(ref $_ && ref $_ eq 'SCALAR') ? $_ : ( defined $ENV{$$_} ? split(/\Q$_path_sep/, $ENV{$$_}) : () ) } ref $list ? @$list : $list; } sub _remove_from { my ($list, @remove) = @_; return @$list if !@remove; my %remove = map { $_ => 1 } @remove; grep !$remove{$_}, _as_list($list); } my @_lib_subdirs = ( [$_version, $_archname], [$_version], [$_archname], (map [$_], @_inc_version_list), [], ); sub install_base_bin_path { my ($class, $path) = @_; return _catdir($path, 'bin'); } sub install_base_perl_path { my ($class, $path) = @_; return _catdir($path, 'lib', 'perl5'); } sub install_base_arch_path { my ($class, $path) = @_; _catdir($class->install_base_perl_path($path), $_archname); } sub lib_paths_for { my ($class, $path) = @_; my $base = $class->install_base_perl_path($path); return map { _catdir($base, @$_) } @_lib_subdirs; } sub _mm_escape_path { my $path = shift; $path =~ s/\\/\\\\/g; if ($path =~ s/ /\\ /g) { $path = qq{"$path"}; } return $path; } sub _mb_escape_path { my $path = shift; $path =~ s/\\/\\\\/g; return qq{"$path"}; } sub installer_options_for { my ($class, $path) = @_; return ( PERL_MM_OPT => defined $path ? "INSTALL_BASE="._mm_escape_path($path) : undef, PERL_MB_OPT => defined $path ? "--install_base "._mb_escape_path($path) : undef, ); } sub active_paths { my ($self) = @_; $self = ref $self ? $self : $self->new; return grep { # screen out entries that aren't actually reflected in @INC my $active_ll = $self->install_base_perl_path($_); grep { $_ eq $active_ll } @{$self->inc}; } _as_list($self->roots); } sub deactivate { my ($self, $path) = @_; $self = $self->new unless ref $self; $path = $self->resolve_path($path); $path = $self->normalize_path($path); my @active_lls = $self->active_paths; if (!grep { $_ eq $path } @active_lls) { warn "Tried to deactivate inactive local::lib '$path'\n"; return $self; } my %args = ( bins => [ _remove_from($self->bins, $self->install_base_bin_path($path)) ], libs => [ _remove_from($self->libs, $self->install_base_perl_path($path)) ], inc => [ _remove_from($self->inc, $self->lib_paths_for($path)) ], roots => [ _remove_from($self->roots, $path) ], ); $args{extra} = { $self->installer_options_for($args{roots}[0]) }; $self->clone(%args); } sub deactivate_all { my ($self) = @_; $self = $self->new unless ref $self; my @active_lls = $self->active_paths; my %args; if (@active_lls) { %args = ( bins => [ _remove_from($self->bins, map $self->install_base_bin_path($_), @active_lls) ], libs => [ _remove_from($self->libs, map $self->install_base_perl_path($_), @active_lls) ], inc => [ _remove_from($self->inc, map $self->lib_paths_for($_), @active_lls) ], roots => [ _remove_from($self->roots, @active_lls) ], ); } $args{extra} = { $self->installer_options_for(undef) }; $self->clone(%args); } sub activate { my ($self, $path, $opts) = @_; $opts ||= {}; $self = $self->new unless ref $self; $path = $self->resolve_path($path); $self->ensure_dir_structure_for($path, { quiet => $self->quiet }) unless $opts->{no_create}; $path = $self->normalize_path($path); my @active_lls = $self->active_paths; if (grep { $_ eq $path } @active_lls[1 .. $#active_lls]) { $self = $self->deactivate($path); } my %args; if ($opts->{always} || !@active_lls || $active_lls[0] ne $path) { %args = ( bins => [ $self->install_base_bin_path($path), @{$self->bins} ], libs => [ $self->install_base_perl_path($path), @{$self->libs} ], inc => [ $self->lib_paths_for($path), @{$self->inc} ], roots => [ $path, @{$self->roots} ], ); } $args{extra} = { $self->installer_options_for($path) }; $self->clone(%args); } sub normalize_path { my ($self, $path) = @_; $path = ( Win32::GetShortPathName($path) || $path ) if $^O eq 'MSWin32'; return $path; } sub build_environment_vars_for { my $self = $_[0]->new->activate($_[1], { always => 1 }); $self->build_environment_vars; } sub build_activate_environment_vars_for { my $self = $_[0]->new->activate($_[1], { always => 1 }); $self->build_environment_vars; } sub build_deactivate_environment_vars_for { my $self = $_[0]->new->deactivate($_[1]); $self->build_environment_vars; } sub build_deact_all_environment_vars_for { my $self = $_[0]->new->deactivate_all; $self->build_environment_vars; } sub build_environment_vars { my $self = shift; ( PATH => join($_path_sep, _as_list($self->bins)), PERL5LIB => join($_path_sep, _as_list($self->libs)), PERL_LOCAL_LIB_ROOT => join($_path_sep, _as_list($self->roots)), %{$self->extra}, ); } sub setup_local_lib_for { my $self = $_[0]->new->activate($_[1]); $self->setup_local_lib; } sub setup_local_lib { my $self = shift; # if Carp is already loaded, ensure Carp::Heavy is also loaded, to avoid # $VERSION mismatch errors (Carp::Heavy loads Carp, so we do not need to # check in the other direction) require Carp::Heavy if $INC{'Carp.pm'}; $self->setup_env_hash; @INC = @{$self->inc}; } sub setup_env_hash_for { my $self = $_[0]->new->activate($_[1]); $self->setup_env_hash; } sub setup_env_hash { my $self = shift; my %env = $self->build_environment_vars; for my $key (keys %env) { if (defined $env{$key}) { $ENV{$key} = $env{$key}; } else { delete $ENV{$key}; } } } sub print_environment_vars_for { print $_[0]->environment_vars_string_for(@_[1..$#_]); } sub environment_vars_string_for { my $self = $_[0]->new->activate($_[1], { always => 1}); $self->environment_vars_string; } sub environment_vars_string { my ($self, $shelltype) = @_; $shelltype ||= $self->guess_shelltype; my $extra = $self->extra; my @envs = ( PATH => $self->bins, PERL5LIB => $self->libs, PERL_LOCAL_LIB_ROOT => $self->roots, map { $_ => $extra->{$_} } sort keys %$extra, ); $self->_build_env_string($shelltype, \@envs); } sub _build_env_string { my ($self, $shelltype, $envs) = @_; my @envs = @$envs; my $build_method = "build_${shelltype}_env_declaration"; my $out = ''; while (@envs) { my ($name, $value) = (shift(@envs), shift(@envs)); if ( ref $value && @$value == 1 && ref $value->[0] && ref $value->[0] eq 'SCALAR' && ${$value->[0]} eq $name) { next; } $out .= $self->$build_method($name, $value); } my $wrap_method = "wrap_${shelltype}_output"; if ($self->can($wrap_method)) { return $self->$wrap_method($out); } return $out; } sub build_bourne_env_declaration { my ($class, $name, $args) = @_; my $value = $class->_interpolate($args, '${%s:-}', qr/["\\\$!`]/, '\\%s'); if (!defined $value) { return qq{unset $name;\n}; } $value =~ s/(^|\G|$_path_sep)\$\{$name:-\}$_path_sep/$1\${$name}\${$name:+$_path_sep}/g; $value =~ s/$_path_sep\$\{$name:-\}$/\${$name:+$_path_sep\${$name}}/; qq{${name}="$value"; export ${name};\n} } sub build_csh_env_declaration { my ($class, $name, $args) = @_; my ($value, @vars) = $class->_interpolate($args, '${%s}', qr/["\$]/, '"\\%s"'); if (!defined $value) { return qq{unsetenv $name;\n}; } my $out = ''; for my $var (@vars) { $out .= qq{if ! \$?$name setenv $name '';\n}; } my $value_without = $value; if ($value_without =~ s/(?:^|$_path_sep)\$\{$name\}(?:$_path_sep|$)//g) { $out .= qq{if "\${$name}" != '' setenv $name "$value";\n}; $out .= qq{if "\${$name}" == '' }; } $out .= qq{setenv $name "$value_without";\n}; return $out; } sub build_cmd_env_declaration { my ($class, $name, $args) = @_; my $value = $class->_interpolate($args, '%%%s%%', qr(%), '%s'); if (!$value) { return qq{\@set $name=\n}; } my $out = ''; my $value_without = $value; if ($value_without =~ s/(?:^|$_path_sep)%$name%(?:$_path_sep|$)//g) { $out .= qq{\@if not "%$name%"=="" set "$name=$value"\n}; $out .= qq{\@if "%$name%"=="" }; } $out .= qq{\@set "$name=$value_without"\n}; return $out; } sub build_powershell_env_declaration { my ($class, $name, $args) = @_; my $value = $class->_interpolate($args, '$env:%s', qr/["\$]/, '`%s'); if (!$value) { return qq{Remove-Item -ErrorAction 0 Env:\\$name;\n}; } my $maybe_path_sep = qq{\$(if("\$env:$name"-eq""){""}else{"$_path_sep"})}; $value =~ s/(^|\G|$_path_sep)\$env:$name$_path_sep/$1\$env:$name"+$maybe_path_sep+"/g; $value =~ s/$_path_sep\$env:$name$/"+$maybe_path_sep+\$env:$name+"/; qq{\$env:$name = \$("$value");\n}; } sub wrap_powershell_output { my ($class, $out) = @_; return $out || " \n"; } sub build_fish_env_declaration { my ($class, $name, $args) = @_; my $value = $class->_interpolate($args, '$%s', qr/[\\"'$ ]/, '\\%s'); if (!defined $value) { return qq{set -e $name;\n}; } # fish has special handling for PATH, CDPATH, and MANPATH. They are always # treated as arrays, and joined with ; when storing the environment. Other # env vars can be arrays, but will be joined without a separator. We only # really care about PATH, but might as well make this routine more general. if ($name =~ /^(?:CD|MAN)?PATH$/) { $value =~ s/$_path_sep/ /g; my $silent = $name =~ /^(?:CD)?PATH$/ ? " 2>"._devnull : ''; return qq{set -x $name $value$silent;\n}; } my $out = ''; my $value_without = $value; if ($value_without =~ s/(?:^|$_path_sep)\$$name(?:$_path_sep|$)//g) { $out .= qq{set -q $name; and set -x $name $value;\n}; $out .= qq{set -q $name; or }; } $out .= qq{set -x $name $value_without;\n}; $out; } sub _interpolate { my ($class, $args, $var_pat, $escape, $escape_pat) = @_; return unless defined $args; my @args = ref $args ? @$args : $args; return unless @args; my @vars = map { $$_ } grep { ref $_ eq 'SCALAR' } @args; my $string = join $_path_sep, map { ref $_ eq 'SCALAR' ? sprintf($var_pat, $$_) : do { s/($escape)/sprintf($escape_pat, $1)/ge; $_; }; } @args; return wantarray ? ($string, \@vars) : $string; } sub pipeline; sub pipeline { my @methods = @_; my $last = pop(@methods); if (@methods) { \sub { my ($obj, @args) = @_; $obj->${pipeline @methods}( $obj->$last(@args) ); }; } else { \sub { shift->$last(@_); }; } } sub resolve_path { my ($class, $path) = @_; $path = $class->${pipeline qw( resolve_relative_path resolve_home_path resolve_empty_path )}($path); $path; } sub resolve_empty_path { my ($class, $path) = @_; if (defined $path) { $path; } else { '~/perl5'; } } sub resolve_home_path { my ($class, $path) = @_; $path =~ /^~([^\/]*)/ or return $path; my $user = $1; my $homedir = do { if (! length($user) && defined $ENV{HOME}) { $ENV{HOME}; } else { require File::Glob; File::Glob::bsd_glob("~$user", File::Glob::GLOB_TILDE()); } }; unless (defined $homedir) { require Carp; require Carp::Heavy; Carp::croak( "Couldn't resolve homedir for " .(defined $user ? $user : 'current user') ); } $path =~ s/^~[^\/]*/$homedir/; $path; } sub resolve_relative_path { my ($class, $path) = @_; _rel2abs($path); } sub ensure_dir_structure_for { my ($class, $path, $opts) = @_; $opts ||= {}; my @dirs; foreach my $dir ( $class->lib_paths_for($path), $class->install_base_bin_path($path), ) { my $d = $dir; while (!-d $d) { push @dirs, $d; require File::Basename; $d = File::Basename::dirname($d); } } warn "Attempting to create directory ${path}\n" if !$opts->{quiet} && @dirs; my %seen; foreach my $dir (reverse @dirs) { next if $seen{$dir}++; mkdir $dir or -d $dir or die "Unable to create $dir: $!" } return; } sub guess_shelltype { my $shellbin = defined $ENV{SHELL} && length $ENV{SHELL} ? ($ENV{SHELL} =~ /([\w.]+)$/)[-1] : ( $^O eq 'MSWin32' && exists $ENV{'!EXITCODE'} ) ? 'bash' : ( $^O eq 'MSWin32' && $ENV{PROMPT} && $ENV{COMSPEC} ) ? ($ENV{COMSPEC} =~ /([\w.]+)$/)[-1] : ( $^O eq 'MSWin32' && !$ENV{PROMPT} ) ? 'powershell.exe' : 'sh'; for ($shellbin) { return /csh$/ ? 'csh' : /fish$/ ? 'fish' : /command(?:\.com)?$/i ? 'cmd' : /cmd(?:\.exe)?$/i ? 'cmd' : /4nt(?:\.exe)?$/i ? 'cmd' : /powershell(?:\.exe)?$/i ? 'powershell' : 'bourne'; } } 1; __END__ =encoding utf8 =head1 NAME local::lib - create and use a local lib/ for perl modules with PERL5LIB =head1 SYNOPSIS In code - use local::lib; # sets up a local lib at ~/perl5 use local::lib '~/foo'; # same, but ~/foo # Or... use FindBin; use local::lib "$FindBin::Bin/../support"; # app-local support library From the shell - # Install LWP and its missing dependencies to the '~/perl5' directory perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)' # Just print out useful shell commands $ perl -Mlocal::lib PERL_MB_OPT='--install_base /home/username/perl5'; export PERL_MB_OPT; PERL_MM_OPT='INSTALL_BASE=/home/username/perl5'; export PERL_MM_OPT; PERL5LIB="/home/username/perl5/lib/perl5"; export PERL5LIB; PATH="/home/username/perl5/bin:$PATH"; export PATH; PERL_LOCAL_LIB_ROOT="/home/usename/perl5:$PERL_LOCAL_LIB_ROOT"; export PERL_LOCAL_LIB_ROOT; From a F<.bash_profile> or F<.bashrc> file - eval "$(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)" =head2 The bootstrapping technique A typical way to install local::lib is using what is known as the "bootstrapping" technique. You would do this if your system administrator hasn't already installed local::lib. In this case, you'll need to install local::lib in your home directory. Even if you do have administrative privileges, you will still want to set up your environment variables, as discussed in step 4. Without this, you would still install the modules into the system CPAN installation and also your Perl scripts will not use the lib/ path you bootstrapped with local::lib. By default local::lib installs itself and the CPAN modules into ~/perl5. Windows users must also see L. =over 4 =item 1. Download and unpack the local::lib tarball from CPAN (search for "Download" on the CPAN page about local::lib). Do this as an ordinary user, not as root or administrator. Unpack the file in your home directory or in any other convenient location. =item 2. Run this: perl Makefile.PL --bootstrap If the system asks you whether it should automatically configure as much as possible, you would typically answer yes. =item 3. Run this: (local::lib assumes you have make installed on your system) make test && make install =item 4. Now we need to setup the appropriate environment variables, so that Perl starts using our newly generated lib/ directory. If you are using bash or any other Bourne shells, you can add this to your shell startup script this way: echo 'eval "$(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)"' >>~/.bashrc If you are using C shell, you can do this as follows: % echo $SHELL /bin/csh $ echo 'eval `perl -I$HOME/perl5/lib/perl5 -Mlocal::lib`' >> ~/.cshrc After writing your shell configuration file, be sure to re-read it to get the changed settings into your current shell's environment. Bourne shells use C<. ~/.bashrc> for this, whereas C shells use C. =back =head3 Bootstrapping into an alternate directory In order to install local::lib into a directory other than the default, you need to specify the name of the directory when you call bootstrap. Then, when setting up the environment variables, both perl and local::lib must be told the location of the bootstrap directory. The setup process would look as follows: perl Makefile.PL --bootstrap=~/foo make test && make install echo 'eval "$(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)"' >>~/.bashrc . ~/.bashrc =head3 Other bootstrapping options If you're on a slower machine, or are operating under draconian disk space limitations, you can disable the automatic generation of manpages from POD when installing modules by using the C<--no-manpages> argument when bootstrapping: perl Makefile.PL --bootstrap --no-manpages To avoid doing several bootstrap for several Perl module environments on the same account, for example if you use it for several different deployed applications independently, you can use one bootstrapped local::lib installation to install modules in different directories directly this way: cd ~/mydir1 perl -Mlocal::lib=./ eval $(perl -Mlocal::lib=./) ### To set the environment for this shell alone printenv ### You will see that ~/mydir1 is in the PERL5LIB perl -MCPAN -e install ... ### whatever modules you want cd ../mydir2 ... REPEAT ... If you use F<.bashrc> to activate a local::lib automatically, the local::lib will be re-enabled in any sub-shells used, overriding adjustments you may have made in the parent shell. To avoid this, you can initialize the local::lib in F<.bash_profile> rather than F<.bashrc>, or protect the local::lib invocation with a C<$SHLVL> check: [ $SHLVL -eq 1 ] && eval "$(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)" If you are working with several C environments, you may want to remove some of them from the current environment without disturbing the others. You can deactivate one environment like this (using bourne sh): eval $(perl -Mlocal::lib=--deactivate,~/path) which will generate and run the commands needed to remove C<~/path> from your various search paths. Whichever environment was B will remain the target for module installations. That is, if you activate C<~/path_A> and then you activate C<~/path_B>, new modules you install will go in C<~/path_B>. If you deactivate C<~/path_B> then modules will be installed into C<~/pathA> -- but if you deactivate C<~/path_A> then they will still be installed in C<~/pathB> because pathB was activated later. You can also ask C to clean itself completely out of the current shell's environment with the C<--deactivate-all> option. For multiple environments for multiple apps you may need to include a modified version of the C<< use FindBin >> instructions in the "In code" sample above. If you did something like the above, you have a set of Perl modules at C<< ~/mydir1/lib >>. If you have a script at C<< ~/mydir1/scripts/myscript.pl >>, you need to tell it where to find the modules you installed for it at C<< ~/mydir1/lib >>. In C<< ~/mydir1/scripts/myscript.pl >>: use strict; use warnings; use local::lib "$FindBin::Bin/.."; ### points to ~/mydir1 and local::lib finds lib use lib "$FindBin::Bin/../lib"; ### points to ~/mydir1/lib Put this before any BEGIN { ... } blocks that require the modules you installed. =head2 Differences when using this module under Win32 To set up the proper environment variables for your current session of C, you can use this: C:\>perl -Mlocal::lib set PERL_MB_OPT=--install_base C:\DOCUME~1\ADMINI~1\perl5 set PERL_MM_OPT=INSTALL_BASE=C:\DOCUME~1\ADMINI~1\perl5 set PERL5LIB=C:\DOCUME~1\ADMINI~1\perl5\lib\perl5 set PATH=C:\DOCUME~1\ADMINI~1\perl5\bin;%PATH% ### To set the environment for this shell alone C:\>perl -Mlocal::lib > %TEMP%\tmp.bat && %TEMP%\tmp.bat && del %TEMP%\tmp.bat ### instead of $(perl -Mlocal::lib=./) If you want the environment entries to persist, you'll need to add them to the Control Panel's System applet yourself or use L. The "~" is translated to the user's profile directory (the directory named for the user under "Documents and Settings" (Windows XP or earlier) or "Users" (Windows Vista or later)) unless $ENV{HOME} exists. After that, the home directory is translated to a short name (which means the directory must exist) and the subdirectories are created. =head3 PowerShell local::lib also supports PowerShell, and can be used with the C cmdlet. Invoke-Expression "$(perl -Mlocal::lib)" =head1 RATIONALE The version of a Perl package on your machine is not always the version you need. Obviously, the best thing to do would be to update to the version you need. However, you might be in a situation where you're prevented from doing this. Perhaps you don't have system administrator privileges; or perhaps you are using a package management system such as Debian, and nobody has yet gotten around to packaging up the version you need. local::lib solves this problem by allowing you to create your own directory of Perl packages downloaded from CPAN (in a multi-user system, this would typically be within your own home directory). The existing system Perl installation is not affected; you simply invoke Perl with special options so that Perl uses the packages in your own local package directory rather than the system packages. local::lib arranges things so that your locally installed version of the Perl packages takes precedence over the system installation. If you are using a package management system (such as Debian), you don't need to worry about Debian and CPAN stepping on each other's toes. Your local version of the packages will be written to an entirely separate directory from those installed by Debian. =head1 DESCRIPTION This module provides a quick, convenient way of bootstrapping a user-local Perl module library located within the user's home directory. It also constructs and prints out for the user the list of environment variables using the syntax appropriate for the user's current shell (as specified by the C environment variable), suitable for directly adding to one's shell configuration file. More generally, local::lib allows for the bootstrapping and usage of a directory containing Perl modules outside of Perl's C<@INC>. This makes it easier to ship an application with an app-specific copy of a Perl module, or collection of modules. Useful in cases like when an upstream maintainer hasn't applied a patch to a module of theirs that you need for your application. On import, local::lib sets the following environment variables to appropriate values: =over 4 =item PERL_MB_OPT =item PERL_MM_OPT =item PERL5LIB =item PATH =item PERL_LOCAL_LIB_ROOT =back When possible, these will be appended to instead of overwritten entirely. These values are then available for reference by any code after import. =head1 CREATING A SELF-CONTAINED SET OF MODULES See L for one way to do this - but note that there are a number of caveats, and the best approach is always to perform a build against a clean perl (i.e. site and vendor as close to empty as possible). =head1 IMPORT OPTIONS Options are values that can be passed to the C import besides the directory to use. They are specified as C or C. =head2 --deactivate Remove the chosen path (or the default path) from the module search paths if it was added by C, instead of adding it. =head2 --deactivate-all Remove all directories that were added to search paths by C from the search paths. =head2 --quiet Don't output any messages about directories being created. =head2 --always Always add directories to environment variables, ignoring if they are already included. =head2 --shelltype Specify the shell type to use for output. By default, the shell will be detected based on the environment. Should be one of: C, C, C, or C. =head2 --no-create Prevents C from creating directories when activating dirs. This is likely to cause issues on Win32 systems. =head1 CLASS METHODS =head2 ensure_dir_structure_for =over 4 =item Arguments: $path =item Return value: None =back Attempts to create a local::lib directory, including subdirectories and all required parent directories. Throws an exception on failure. =head2 print_environment_vars_for =over 4 =item Arguments: $path =item Return value: None =back Prints to standard output the variables listed above, properly set to use the given path as the base directory. =head2 build_environment_vars_for =over 4 =item Arguments: $path =item Return value: %environment_vars =back Returns a hash with the variables listed above, properly set to use the given path as the base directory. =head2 setup_env_hash_for =over 4 =item Arguments: $path =item Return value: None =back Constructs the C<%ENV> keys for the given path, by calling L. =head2 active_paths =over 4 =item Arguments: None =item Return value: @paths =back Returns a list of active C paths, according to the C environment variable and verified against what is really in C<@INC>. =head2 install_base_perl_path =over 4 =item Arguments: $path =item Return value: $install_base_perl_path =back Returns a path describing where to install the Perl modules for this local library installation. Appends the directories C and C to the given path. =head2 lib_paths_for =over 4 =item Arguments: $path =item Return value: @lib_paths =back Returns the list of paths perl will search for libraries, given a base path. This includes the base path itself, the architecture specific subdirectory, and perl version specific subdirectories. These paths may not all exist. =head2 install_base_bin_path =over 4 =item Arguments: $path =item Return value: $install_base_bin_path =back Returns a path describing where to install the executable programs for this local library installation. Appends the directory C to the given path. =head2 installer_options_for =over 4 =item Arguments: $path =item Return value: %installer_env_vars =back Returns a hash of environment variables that should be set to cause installation into the given path. =head2 resolve_empty_path =over 4 =item Arguments: $path =item Return value: $base_path =back Builds and returns the base path into which to set up the local module installation. Defaults to C<~/perl5>. =head2 resolve_home_path =over 4 =item Arguments: $path =item Return value: $home_path =back Attempts to find the user's home directory. If no definite answer is available, throws an exception. =head2 resolve_relative_path =over 4 =item Arguments: $path =item Return value: $absolute_path =back Translates the given path into an absolute path. =head2 resolve_path =over 4 =item Arguments: $path =item Return value: $absolute_path =back Calls the following in a pipeline, passing the result from the previous to the next, in an attempt to find where to configure the environment for a local library installation: L, L, L. Passes the given path argument to L which then returns a result that is passed to L, which then has its result passed to L. The result of this final call is returned from L. =head1 OBJECT INTERFACE =head2 new =over 4 =item Arguments: %attributes =item Return value: $local_lib =back Constructs a new C object, representing the current state of C<@INC> and the relevant environment variables. =head1 ATTRIBUTES =head2 roots An arrayref representing active C directories. =head2 inc An arrayref representing C<@INC>. =head2 libs An arrayref representing the PERL5LIB environment variable. =head2 bins An arrayref representing the PATH environment variable. =head2 extra A hashref of extra environment variables (e.g. C and C) =head2 no_create If set, C will not try to create directories when activating them. =head1 OBJECT METHODS =head2 clone =over 4 =item Arguments: %attributes =item Return value: $local_lib =back Constructs a new C object based on the existing one, overriding the specified attributes. =head2 activate =over 4 =item Arguments: $path =item Return value: $new_local_lib =back Constructs a new instance with the specified path active. =head2 deactivate =over 4 =item Arguments: $path =item Return value: $new_local_lib =back Constructs a new instance with the specified path deactivated. =head2 deactivate_all =over 4 =item Arguments: None =item Return value: $new_local_lib =back Constructs a new instance with all C directories deactivated. =head2 environment_vars_string =over 4 =item Arguments: [ $shelltype ] =item Return value: $shell_env_string =back Returns a string to set up the C, meant to be run by a shell. =head2 build_environment_vars =over 4 =item Arguments: None =item Return value: %environment_vars =back Returns a hash with the variables listed above, properly set to use the given path as the base directory. =head2 setup_env_hash =over 4 =item Arguments: None =item Return value: None =back Constructs the C<%ENV> keys for the given path, by calling L. =head2 setup_local_lib Constructs the C<%ENV> hash using L, and set up C<@INC>. =head1 A WARNING ABOUT UNINST=1 Be careful about using local::lib in combination with "make install UNINST=1". The idea of this feature is that will uninstall an old version of a module before installing a new one. However it lacks a safety check that the old version and the new version will go in the same directory. Used in combination with local::lib, you can potentially delete a globally accessible version of a module while installing the new version in a local place. Only combine "make install UNINST=1" and local::lib if you understand these possible consequences. =head1 LIMITATIONS =over 4 =item * Directory names with spaces in them are not well supported by the perl toolchain and the programs it uses. Pure-perl distributions should support spaces, but problems are more likely with dists that require compilation. A workaround you can do is moving your local::lib to a directory with spaces B you installed all modules inside your local::lib bootstrap. But be aware that you can't update or install CPAN modules after the move. =item * Rather basic shell detection. Right now anything with csh in its name is assumed to be a C shell or something compatible, and everything else is assumed to be Bourne, except on Win32 systems. If the C environment variable is not set, a Bourne-compatible shell is assumed. =item * Kills any existing PERL_MM_OPT or PERL_MB_OPT. =item * Should probably auto-fixup CPAN config if not already done. =item * On VMS and MacOS Classic (pre-OS X), local::lib loads L. This means any L version installed in the local::lib will be ignored by scripts using local::lib. A workaround for this is using C instead of using C directly. =item * Conflicts with L's C option. C uses the C option, as it has more predictable and sane behavior. If something attempts to use the C option when running a F, L will refuse to run, as the two options conflict. This can be worked around by temporarily unsetting the C environment variable. =item * Conflicts with L's C<--prefix> option. Similar to the previous limitation, but any C<--prefix> option specified will be ignored. This can be worked around by temporarily unsetting the C environment variable. =back Patches very much welcome for any of the above. =over 4 =item * On Win32 systems, does not have a way to write the created environment variables to the registry, so that they can persist through a reboot. =back =head1 TROUBLESHOOTING If you've configured local::lib to install CPAN modules somewhere in to your home directory, and at some point later you try to install a module with C, but it fails with an error like: C and buried within the install log is an error saying C<'INSTALL_BASE' is not a known MakeMaker parameter name>, then you've somehow lost your updated ExtUtils::MakeMaker module. To remedy this situation, rerun the bootstrapping procedure documented above. Then, run C Finally, re-run C and it should install without problems. =head1 ENVIRONMENT =over 4 =item SHELL =item COMSPEC local::lib looks at the user's C environment variable when printing out commands to add to the shell configuration file. On Win32 systems, C is also examined. =back =head1 SEE ALSO =over 4 =item * L =back =head1 SUPPORT IRC: Join #toolchain on irc.perl.org. =head1 AUTHOR Matt S Trout http://www.shadowcat.co.uk/ auto_install fixes kindly sponsored by http://www.takkle.com/ =head1 CONTRIBUTORS Patches to correctly output commands for csh style shells, as well as some documentation additions, contributed by Christopher Nehren . Doc patches for a custom local::lib directory, more cleanups in the english documentation and a L contributed by Torsten Raudssus . Hans Dieter Pearcey sent in some additional tests for ensuring things will install properly, submitted a fix for the bug causing problems with writing Makefiles during bootstrapping, contributed an example program, and submitted yet another fix to ensure that local::lib can install and bootstrap properly. Many, many thanks! pattern of Freenode IRC contributed the beginnings of the Troubleshooting section. Many thanks! Patch to add Win32 support contributed by Curtis Jewell . Warnings for missing PATH/PERL5LIB (as when not running interactively) silenced by a patch from Marco Emilio Poleggi. Mark Stosberg provided the code for the now deleted '--self-contained' option. Documentation patches to make win32 usage clearer by David Mertens (run4flat). Brazilian L and minor doc patches contributed by Breno G. de Oliveira . Improvements to stacking multiple local::lib dirs and removing them from the environment later on contributed by Andrew Rodland . Patch for Carp version mismatch contributed by Hakim Cassimally . Rewrite of internals and numerous bug fixes and added features contributed by Graham Knop . =head1 COPYRIGHT Copyright (c) 2007 - 2013 the local::lib L and L as listed above. =head1 LICENSE 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 PK!ÆäEª1$1$perl5/libwww/lwpcook.podnuÏÃ6Ç$=head1 NAME lwpcook - The libwww-perl cookbook =head1 DESCRIPTION This document contain some examples that show typical usage of the libwww-perl library. You should consult the documentation for the individual modules for more detail. All examples should be runnable programs. You can, in most cases, test the code sections by piping the program text directly to perl. =head1 GET It is very easy to use this library to just fetch documents from the net. The LWP::Simple module provides the get() function that return the document specified by its URL argument: use LWP::Simple; $doc = get 'http://search.cpan.org/dist/libwww-perl/'; or, as a perl one-liner using the getprint() function: perl -MLWP::Simple -e 'getprint "http://search.cpan.org/dist/libwww-perl/"' or, how about fetching the latest perl by running this command: perl -MLWP::Simple -e ' getstore "ftp://ftp.sunet.se/pub/lang/perl/CPAN/src/latest.tar.gz", "perl.tar.gz"' You will probably first want to find a CPAN site closer to you by running something like the following command: perl -MLWP::Simple -e 'getprint "http://www.cpan.org/SITES.html"' Enough of this simple stuff! The LWP object oriented interface gives you more control over the request sent to the server. Using this interface you have full control over headers sent and how you want to handle the response returned. use LWP::UserAgent; $ua = LWP::UserAgent->new; $ua->agent("$0/0.1 " . $ua->agent); # $ua->agent("Mozilla/8.0") # pretend we are very capable browser $req = HTTP::Request->new( GET => 'http://search.cpan.org/dist/libwww-perl/'); $req->header('Accept' => 'text/html'); # send request $res = $ua->request($req); # check the outcome if ($res->is_success) { print $res->decoded_content; } else { print "Error: " . $res->status_line . "\n"; } The lwp-request program (alias GET) that is distributed with the library can also be used to fetch documents from WWW servers. =head1 HEAD If you just want to check if a document is present (i.e. the URL is valid) try to run code that looks like this: use LWP::Simple; if (head($url)) { # ok document exists } The head() function really returns a list of meta-information about the document. The first three values of the list returned are the document type, the size of the document, and the age of the document. More control over the request or access to all header values returned require that you use the object oriented interface described for GET above. Just s/GET/HEAD/g. =head1 POST There is no simple procedural interface for posting data to a WWW server. You must use the object oriented interface for this. The most common POST operation is to access a WWW form application: use LWP::UserAgent; $ua = LWP::UserAgent->new; my $req = HTTP::Request->new( POST => 'https://rt.cpan.org/Public/Dist/Display.html'); $req->content_type('application/x-www-form-urlencoded'); $req->content('Status=Active&Name=libwww-perl'); my $res = $ua->request($req); print $res->as_string; Lazy people use the HTTP::Request::Common module to set up a suitable POST request message (it handles all the escaping issues) and has a suitable default for the content_type: use HTTP::Request::Common qw(POST); use LWP::UserAgent; $ua = LWP::UserAgent->new; my $req = POST 'https://rt.cpan.org/Public/Dist/Display.html', [ Status => 'Active', Name => 'libwww-perl' ]; print $ua->request($req)->as_string; The lwp-request program (alias POST) that is distributed with the library can also be used for posting data. =head1 PROXIES Some sites use proxies to go through fire wall machines, or just as cache in order to improve performance. Proxies can also be used for accessing resources through protocols not supported directly (or supported badly :-) by the libwww-perl library. You should initialize your proxy setting before you start sending requests: use LWP::UserAgent; $ua = LWP::UserAgent->new; $ua->env_proxy; # initialize from environment variables # or $ua->proxy(ftp => 'http://proxy.myorg.com'); $ua->proxy(wais => 'http://proxy.myorg.com'); $ua->no_proxy(qw(no se fi)); my $req = HTTP::Request->new(GET => 'wais://xxx.com/'); print $ua->request($req)->as_string; The LWP::Simple interface will call env_proxy() for you automatically. Applications that use the $ua->env_proxy() method will normally not use the $ua->proxy() and $ua->no_proxy() methods. Some proxies also require that you send it a username/password in order to let requests through. You should be able to add the required header, with something like this: use LWP::UserAgent; $ua = LWP::UserAgent->new; $ua->proxy(['http', 'ftp'] => 'http://username:password@proxy.myorg.com'); $req = HTTP::Request->new('GET',"http://www.perl.com"); $res = $ua->request($req); print $res->decoded_content if $res->is_success; Replace C, C and C with something suitable for your site. =head1 ACCESS TO PROTECTED DOCUMENTS Documents protected by basic authorization can easily be accessed like this: use LWP::UserAgent; $ua = LWP::UserAgent->new; $req = HTTP::Request->new(GET => 'http://www.linpro.no/secret/'); $req->authorization_basic('aas', 'mypassword'); print $ua->request($req)->as_string; The other alternative is to provide a subclass of I that overrides the get_basic_credentials() method. Study the I program for an example of this. =head1 COOKIES Some sites like to play games with cookies. By default LWP ignores cookies provided by the servers it visits. LWP will collect cookies and respond to cookie requests if you set up a cookie jar. LWP doesn't provide a cookie jar itself, but if you install L, it can be used like this: use LWP::UserAgent; use HTTP::CookieJar::LWP; $ua = LWP::UserAgent->new( cookie_jar => HTTP::CookieJar::LWP->new, ); # and then send requests just as you used to do $res = $ua->request(HTTP::Request->new(GET => "http://no.yahoo.com/")); print $res->status_line, "\n"; =head1 HTTPS URLs with https scheme are accessed in exactly the same way as with http scheme, provided that an SSL interface module for LWP has been properly installed (see the F file found in the libwww-perl distribution for more details). If no SSL interface is installed for LWP to use, then you will get "501 Protocol scheme 'https' is not supported" errors when accessing such URLs. Here's an example of fetching and printing a WWW page using SSL: use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $req = HTTP::Request->new(GET => 'https://www.helsinki.fi/'); my $res = $ua->request($req); if ($res->is_success) { print $res->as_string; } else { print "Failed: ", $res->status_line, "\n"; } =head1 MIRRORING If you want to mirror documents from a WWW server, then try to run code similar to this at regular intervals: use LWP::Simple; %mirrors = ( 'http://www.sn.no/' => 'sn.html', 'http://www.perl.com/' => 'perl.html', 'http://search.cpan.org/distlibwww-perl/' => 'lwp.html', 'gopher://gopher.sn.no/' => 'gopher.html', ); while (($url, $localfile) = each(%mirrors)) { mirror($url, $localfile); } Or, as a perl one-liner: perl -MLWP::Simple -e 'mirror("http://www.perl.com/", "perl.html")'; The document will not be transferred unless it has been updated. =head1 LARGE DOCUMENTS If the document you want to fetch is too large to be kept in memory, then you have two alternatives. You can instruct the library to write the document content to a file (second $ua->request() argument is a file name): use LWP::UserAgent; $ua = LWP::UserAgent->new; my $req = HTTP::Request->new(GET => 'http://www.cpan.org/CPAN/authors/id/O/OA/OALDERS/libwww-perl-6.26.tar.gz'); $res = $ua->request($req, "libwww-perl.tar.gz"); if ($res->is_success) { print "ok\n"; } else { print $res->status_line, "\n"; } Or you can process the document as it arrives (second $ua->request() argument is a code reference): use LWP::UserAgent; $ua = LWP::UserAgent->new; $URL = 'ftp://ftp.isc.org/pub/rfc/rfc-index.txt'; my $expected_length; my $bytes_received = 0; my $res = $ua->request(HTTP::Request->new(GET => $URL), sub { my($chunk, $res) = @_; $bytes_received += length($chunk); unless (defined $expected_length) { $expected_length = $res->content_length || 0; } if ($expected_length) { printf STDERR "%d%% - ", 100 * $bytes_received / $expected_length; } print STDERR "$bytes_received bytes received\n"; # XXX Should really do something with the chunk itself # print $chunk; }); print $res->status_line, "\n"; =head1 COPYRIGHT Copyright 1996-2001, Gisle Aas This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!�ÄÙvavaperl5/libwww/lwptut.podnuÏÃ6Ç$=head1 NAME lwptut -- An LWP Tutorial =head1 DESCRIPTION LWP (short for "Library for WWW in Perl") is a very popular group of Perl modules for accessing data on the Web. Like most Perl module-distributions, each of LWP's component modules comes with documentation that is a complete reference to its interface. However, there are so many modules in LWP that it's hard to know where to start looking for information on how to do even the simplest most common things. Really introducing you to using LWP would require a whole book -- a book that just happens to exist, called I. But this article should give you a taste of how you can go about some common tasks with LWP. =head2 Getting documents with LWP::Simple If you just want to get what's at a particular URL, the simplest way to do it is LWP::Simple's functions. In a Perl program, you can call its C function. It will try getting that URL's content. If it works, then it'll return the content; but if there's some error, it'll return undef. my $url = 'http://www.npr.org/programs/fa/?todayDate=current'; # Just an example: the URL for the most recent /Fresh Air/ show use LWP::Simple; my $content = get $url; die "Couldn't get $url" unless defined $content; # Then go do things with $content, like this: if($content =~ m/jazz/i) { print "They're talking about jazz today on Fresh Air!\n"; } else { print "Fresh Air is apparently jazzless today.\n"; } The handiest variant on C is C, which is useful in Perl one-liners. If it can get the page whose URL you provide, it sends it to STDOUT; otherwise it complains to STDERR. % perl -MLWP::Simple -e "getprint 'http://www.cpan.org/RECENT'" That is the URL of a plain text file that lists new files in CPAN in the past two weeks. You can easily make it part of a tidy little shell command, like this one that mails you the list of new C modules: % perl -MLWP::Simple -e "getprint 'http://www.cpan.org/RECENT'" \ | grep "/by-module/Acme" | mail -s "New Acme modules! Joy!" $USER There are other useful functions in LWP::Simple, including one function for running a HEAD request on a URL (useful for checking links, or getting the last-revised time of a URL), and two functions for saving/mirroring a URL to a local file. See L for the full details, or chapter 2 of I for more examples. =for comment ########################################################################## =head2 The Basics of the LWP Class Model LWP::Simple's functions are handy for simple cases, but its functions don't support cookies or authorization, don't support setting header lines in the HTTP request, generally don't support reading header lines in the HTTP response (notably the full HTTP error message, in case of an error). To get at all those features, you'll have to use the full LWP class model. While LWP consists of dozens of classes, the main two that you have to understand are L and L. LWP::UserAgent is a class for "virtual browsers" which you use for performing requests, and L is a class for the responses (or error messages) that you get back from those requests. The basic idiom is C<< $response = $browser->get($url) >>, or more fully illustrated: # Early in your program: use LWP 5.64; # Loads all important LWP classes, and makes # sure your version is reasonably recent. my $browser = LWP::UserAgent->new; ... # Then later, whenever you need to make a get request: my $url = 'http://www.npr.org/programs/fa/?todayDate=current'; my $response = $browser->get( $url ); die "Can't get $url -- ", $response->status_line unless $response->is_success; die "Hey, I was expecting HTML, not ", $response->content_type unless $response->content_type eq 'text/html'; # or whatever content-type you're equipped to deal with # Otherwise, process the content somehow: if($response->decoded_content =~ m/jazz/i) { print "They're talking about jazz today on Fresh Air!\n"; } else { print "Fresh Air is apparently jazzless today.\n"; } There are two objects involved: C<$browser>, which holds an object of class LWP::UserAgent, and then the C<$response> object, which is of class HTTP::Response. You really need only one browser object per program; but every time you make a request, you get back a new HTTP::Response object, which will have some interesting attributes: =over =item * A status code indicating success or failure (which you can test with C<< $response->is_success >>). =item * An HTTP status line that is hopefully informative if there's failure (which you can see with C<< $response->status_line >>, returning something like "404 Not Found"). =item * A MIME content-type like "text/html", "image/gif", "application/xml", etc., which you can see with C<< $response->content_type >> =item * The actual content of the response, in C<< $response->decoded_content >>. If the response is HTML, that's where the HTML source will be; if it's a GIF, then C<< $response->decoded_content >> will be the binary GIF data. =item * And dozens of other convenient and more specific methods that are documented in the docs for L, and its superclasses L and L. =back =for comment ########################################################################## =head2 Adding Other HTTP Request Headers The most commonly used syntax for requests is C<< $response = $browser->get($url) >>, but in truth, you can add extra HTTP header lines to the request by adding a list of key-value pairs after the URL, like so: $response = $browser->get( $url, $key1, $value1, $key2, $value2, ... ); For example, here's how to send some commonly used headers, in case you're dealing with a site that would otherwise reject your request: my @ns_headers = ( 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)', 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', 'Accept-Charset' => 'iso-8859-1,*,utf-8', 'Accept-Language' => 'en-US', ); ... $response = $browser->get($url, @ns_headers); If you weren't reusing that array, you could just go ahead and do this: $response = $browser->get($url, 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)', 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', 'Accept-Charset' => 'iso-8859-1,*,utf-8', 'Accept-Language' => 'en-US', ); If you were only ever changing the 'User-Agent' line, you could just change the C<$browser> object's default line from "libwww-perl/5.65" (or the like) to whatever you like, using the LWP::UserAgent C method: $browser->agent('Mozilla/4.76 [en] (Win98; U)'); =for comment ########################################################################## =head2 Enabling Cookies A default LWP::UserAgent object acts like a browser with its cookies support turned off. There are various ways of turning it on, by setting its C attribute. A "cookie jar" is an object representing a little database of all the HTTP cookies that a browser knows about. It can correspond to a file on disk or an in-memory object that starts out empty, and whose collection of cookies will disappear once the program is finished running. To give a browser an in-memory empty cookie jar, you set its C attribute like so: use HTTP::CookieJar::LWP; $browser->cookie_jar( HTTP::CookieJar::LWP->new ); To save a cookie jar to disk, see L<< HTTP::CookieJar/dump_cookies >>. To load cookies from disk into a jar, see L<< HTTP::CookieJar/load_cookies >>. =for comment ########################################################################## =head2 Posting Form Data Many HTML forms send data to their server using an HTTP POST request, which you can send with this syntax: $response = $browser->post( $url, [ formkey1 => value1, formkey2 => value2, ... ], ); Or if you need to send HTTP headers: $response = $browser->post( $url, [ formkey1 => value1, formkey2 => value2, ... ], headerkey1 => value1, headerkey2 => value2, ); For example, the following program makes a search request to AltaVista (by sending some form data via an HTTP POST request), and extracts from the HTML the report of the number of matches: use strict; use warnings; use LWP 5.64; my $browser = LWP::UserAgent->new; my $word = 'tarragon'; my $url = 'http://search.yahoo.com/yhs/search'; my $response = $browser->post( $url, [ 'q' => $word, # the Altavista query string 'fr' => 'altavista', 'pg' => 'q', 'avkw' => 'tgz', 'kl' => 'XX', ] ); die "$url error: ", $response->status_line unless $response->is_success; die "Weird content type at $url -- ", $response->content_type unless $response->content_is_html; if( $response->decoded_content =~ m{([0-9,]+)(?:<.*?>)? results for} ) { # The substring will be like "996,000 results for" print "$word: $1\n"; } else { print "Couldn't find the match-string in the response\n"; } =for comment ########################################################################## =head2 Sending GET Form Data Some HTML forms convey their form data not by sending the data in an HTTP POST request, but by making a normal GET request with the data stuck on the end of the URL. For example, if you went to C and ran a search on "Blade Runner", the URL you'd see in your browser window would be: http://www.imdb.com/find?s=all&q=Blade+Runner To run the same search with LWP, you'd use this idiom, which involves the URI class: use URI; my $url = URI->new( 'http://www.imdb.com/find' ); # makes an object representing the URL $url->query_form( # And here the form data pairs: 'q' => 'Blade Runner', 's' => 'all', ); my $response = $browser->get($url); See chapter 5 of I for a longer discussion of HTML forms and of form data, and chapters 6 through 9 for a longer discussion of extracting data from HTML. =head2 Absolutizing URLs The URI class that we just mentioned above provides all sorts of methods for accessing and modifying parts of URLs (such as asking sort of URL it is with C<< $url->scheme >>, and asking what host it refers to with C<< $url->host >>, and so on, as described in L. However, the methods of most immediate interest are the C method seen above, and now the C method for taking a probably-relative URL string (like "../foo.html") and getting back an absolute URL (like "http://www.perl.com/stuff/foo.html"), as shown here: use URI; $abs = URI->new_abs($maybe_relative, $base); For example, consider this program that matches URLs in the HTML list of new modules in CPAN: use strict; use warnings; use LWP; my $browser = LWP::UserAgent->new; my $url = 'http://www.cpan.org/RECENT.html'; my $response = $browser->get($url); die "Can't get $url -- ", $response->status_line unless $response->is_success; my $html = $response->decoded_content; while( $html =~ m/ method, by changing the C loop to this: while( $html =~ m/new_abs( $1, $response->base ) ,"\n"; } (The C<< $response->base >> method from L is for returning what URL should be used for resolving relative URLs -- it's usually just the same as the URL that you requested.) That program then emits nicely absolute URLs: http://www.cpan.org/MIRRORING.FROM http://www.cpan.org/RECENT http://www.cpan.org/RECENT.html http://www.cpan.org/authors/00whois.html http://www.cpan.org/authors/01mailrc.txt.gz http://www.cpan.org/authors/id/A/AA/AASSAD/CHECKSUMS ... See chapter 4 of I for a longer discussion of URI objects. Of course, using a regexp to match hrefs is a bit simplistic, and for more robust programs, you'll probably want to use an HTML-parsing module like L or L or even maybe L. =for comment ########################################################################## =head2 Other Browser Attributes LWP::UserAgent objects have many attributes for controlling how they work. Here are a few notable ones: =over =item * C<< $browser->timeout(15); >> This sets this browser object to give up on requests that don't answer within 15 seconds. =item * C<< $browser->protocols_allowed( [ 'http', 'gopher'] ); >> This sets this browser object to not speak any protocols other than HTTP and gopher. If it tries accessing any other kind of URL (like an "ftp:" or "mailto:" or "news:" URL), then it won't actually try connecting, but instead will immediately return an error code 500, with a message like "Access to 'ftp' URIs has been disabled". =item * C<< use LWP::ConnCache; $browser->conn_cache(LWP::ConnCache->new()); >> This tells the browser object to try using the HTTP/1.1 "Keep-Alive" feature, which speeds up requests by reusing the same socket connection for multiple requests to the same server. =item * C<< $browser->agent( 'SomeName/1.23 (more info here maybe)' ) >> This changes how the browser object will identify itself in the default "User-Agent" line is its HTTP requests. By default, it'll send "libwww-perl/I", like "libwww-perl/5.65". You can change that to something more descriptive like this: $browser->agent( 'SomeName/3.14 (contact@robotplexus.int)' ); Or if need be, you can go in disguise, like this: $browser->agent( 'Mozilla/4.0 (compatible; MSIE 5.12; Mac_PowerPC)' ); =item * C<< push @{ $ua->requests_redirectable }, 'POST'; >> This tells this browser to obey redirection responses to POST requests (like most modern interactive browsers), even though the HTTP RFC says that should not normally be done. =back For more options and information, see L. =for comment ########################################################################## =head2 Writing Polite Robots If you want to make sure that your LWP-based program respects F files and doesn't make too many requests too fast, you can use the LWP::RobotUA class instead of the LWP::UserAgent class. LWP::RobotUA class is just like LWP::UserAgent, and you can use it like so: use LWP::RobotUA; my $browser = LWP::RobotUA->new('YourSuperBot/1.34', 'you@yoursite.com'); # Your bot's name and your email address my $response = $browser->get($url); But HTTP::RobotUA adds these features: =over =item * If the F on C<$url>'s server forbids you from accessing C<$url>, then the C<$browser> object (assuming it's of class LWP::RobotUA) won't actually request it, but instead will give you back (in C<$response>) a 403 error with a message "Forbidden by robots.txt". That is, if you have this line: die "$url -- ", $response->status_line, "\nAborted" unless $response->is_success; then the program would die with an error message like this: http://whatever.site.int/pith/x.html -- 403 Forbidden by robots.txt Aborted at whateverprogram.pl line 1234 =item * If this C<$browser> object sees that the last time it talked to C<$url>'s server was too recently, then it will pause (via C) to avoid making too many requests too often. How long it will pause for, is by default one minute -- but you can control it with the C<< $browser->delay( I ) >> attribute. For example, this code: $browser->delay( 7/60 ); ...means that this browser will pause when it needs to avoid talking to any given server more than once every 7 seconds. =back For more options and information, see L. =for comment ########################################################################## =head2 Using Proxies In some cases, you will want to (or will have to) use proxies for accessing certain sites and/or using certain protocols. This is most commonly the case when your LWP program is running (or could be running) on a machine that is behind a firewall. To make a browser object use proxies that are defined in the usual environment variables (C, etc.), just call the C on a user-agent object before you go making any requests on it. Specifically: use LWP::UserAgent; my $browser = LWP::UserAgent->new; # And before you go making any requests: $browser->env_proxy; For more information on proxy parameters, see L, specifically the C, C, and C methods. =for comment ########################################################################## =head2 HTTP Authentication Many web sites restrict access to documents by using "HTTP Authentication". This isn't just any form of "enter your password" restriction, but is a specific mechanism where the HTTP server sends the browser an HTTP code that says "That document is part of a protected 'realm', and you can access it only if you re-request it and add some special authorization headers to your request". For example, the Unicode.org admins stop email-harvesting bots from harvesting the contents of their mailing list archives, by protecting them with HTTP Authentication, and then publicly stating the username and password (at C) -- namely username "unicode-ml" and password "unicode". For example, consider this URL, which is part of the protected area of the web site: http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html If you access that with a browser, you'll get a prompt like "Enter username and password for 'Unicode-MailList-Archives' at server 'www.unicode.org'". In LWP, if you just request that URL, like this: use LWP; my $browser = LWP::UserAgent->new; my $url = 'http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html'; my $response = $browser->get($url); die "Error: ", $response->header('WWW-Authenticate') || 'Error accessing', # ('WWW-Authenticate' is the realm-name) "\n ", $response->status_line, "\n at $url\n Aborting" unless $response->is_success; Then you'll get this error: Error: Basic realm="Unicode-MailList-Archives" 401 Authorization Required at http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html Aborting at auth1.pl line 9. [or wherever] ...because the C<$browser> doesn't know any the username and password for that realm ("Unicode-MailList-Archives") at that host ("www.unicode.org"). The simplest way to let the browser know about this is to use the C method to let it know about a username and password that it can try using for that realm at that host. The syntax is: $browser->credentials( 'servername:portnumber', 'realm-name', 'username' => 'password' ); In most cases, the port number is 80, the default TCP/IP port for HTTP; and you usually call the C method before you make any requests. For example: $browser->credentials( 'reports.mybazouki.com:80', 'web_server_usage_reports', 'plinky' => 'banjo123' ); So if we add the following to the program above, right after the C<< $browser = LWP::UserAgent->new; >> line... $browser->credentials( # add this to our $browser 's "key ring" 'www.unicode.org:80', 'Unicode-MailList-Archives', 'unicode-ml' => 'unicode' ); ...then when we run it, the request succeeds, instead of causing the C to be called. =for comment ########################################################################## =head2 Accessing HTTPS URLs When you access an HTTPS URL, it'll work for you just like an HTTP URL would -- if your LWP installation has HTTPS support (via an appropriate Secure Sockets Layer library). For example: use LWP; my $url = 'https://www.paypal.com/'; # Yes, HTTPS! my $browser = LWP::UserAgent->new; my $response = $browser->get($url); die "Error at $url\n ", $response->status_line, "\n Aborting" unless $response->is_success; print "Whee, it worked! I got that ", $response->content_type, " document!\n"; If your LWP installation doesn't have HTTPS support set up, then the response will be unsuccessful, and you'll get this error message: Error at https://www.paypal.com/ 501 Protocol scheme 'https' is not supported Aborting at paypal.pl line 7. [or whatever program and line] If your LWP installation I have HTTPS support installed, then the response should be successful, and you should be able to consult C<$response> just like with any normal HTTP response. For information about installing HTTPS support for your LWP installation, see the helpful F file that comes in the libwww-perl distribution. =for comment ########################################################################## =head2 Getting Large Documents When you're requesting a large (or at least potentially large) document, a problem with the normal way of using the request methods (like C<< $response = $browser->get($url) >>) is that the response object in memory will have to hold the whole document -- I. If the response is a thirty megabyte file, this is likely to be quite an imposition on this process's memory usage. A notable alternative is to have LWP save the content to a file on disk, instead of saving it up in memory. This is the syntax to use: $response = $ua->get($url, ':content_file' => $filespec, ); For example, $response = $ua->get('http://search.cpan.org/', ':content_file' => '/tmp/sco.html' ); When you use this C<:content_file> option, the C<$response> will have all the normal header lines, but C<< $response->content >> will be empty. Errors writing to the content file (for example due to permission denied or the filesystem being full) will be reported via the C or C response headers, and not the C method: if ($response->header('Client-Aborted') eq 'die') { # handle error ... Note that this ":content_file" option isn't supported under older versions of LWP, so you should consider adding C to check the LWP version, if you think your program might run on systems with older versions. If you need to be compatible with older LWP versions, then use this syntax, which does the same thing: use HTTP::Request::Common; $response = $ua->request( GET($url), $filespec ); =for comment ########################################################################## =head1 SEE ALSO Remember, this article is just the most rudimentary introduction to LWP -- to learn more about LWP and LWP-related tasks, you really must read from the following: =over =item * L -- simple functions for getting/heading/mirroring URLs =item * L -- overview of the libwww-perl modules =item * L -- the class for objects that represent "virtual browsers" =item * L -- the class for objects that represent the response to a LWP response, as in C<< $response = $browser->get(...) >> =item * L and L -- classes that provide more methods to HTTP::Response. =item * L -- class for objects that represent absolute or relative URLs =item * L -- functions for URL-escaping and URL-unescaping strings (like turning "this & that" to and from "this%20%26%20that"). =item * L -- functions for HTML-escaping and HTML-unescaping strings (like turning "C. & E. BrontE" to and from "C. & E. Brontë") =item * L and L -- classes for parsing HTML =item * L -- class for finding links in HTML documents =item * The book I by Sean M. Burke. O'Reilly & Associates, 2002. ISBN: 0-596-00178-9, L. The whole book is also available free online: L. =back =head1 COPYRIGHT Copyright 2002, Sean M. Burke. You can redistribute this document and/or modify it, but only under the same terms as Perl itself. =head1 AUTHOR Sean M. Burke C =for comment ########################################################################## =cut # End of Pod PK!! M}éAéAperl5/alienfile.pmnuÏÃ6Ç$package alienfile; use strict; use warnings; use 5.008004; use Alien::Build; use Exporter (); use Path::Tiny (); use Carp (); sub _path { Path::Tiny::path(@_) } # ABSTRACT: Specification for defining an external dependency for CPAN our $VERSION = '2.83'; # VERSION our @EXPORT = qw( requires on plugin probe configure share sys download fetch decode prefer extract patch patch_ffi build build_ffi gather gather_ffi meta_prop ffi log test start_url before after digest ); sub requires { my($module, $version) = @_; $version ||= 0; my $caller = caller; my $meta = $caller->meta; $meta->add_requires($meta->{phase}, $module, $version); (); } sub plugin { my($name, @args) = @_; my $caller = caller; $caller->meta->apply_plugin($name, @args); return; } sub probe { my($instr) = @_; my $caller = caller; if(my $phase = $caller->meta->{phase}) { Carp::croak "probe must not be in a $phase block" if $phase ne 'any'; } $caller->meta->register_hook(probe => $instr); return; } sub _phase { my($code, $phase) = @_; my $caller = caller(1); my $meta = $caller->meta; local $meta->{phase} = $phase; $code->(); return; } sub configure (&) { _phase($_[0], 'configure'); } sub sys (&) { _phase($_[0], 'system'); } sub share (&) { _phase($_[0], 'share'); } sub _in_phase { my($phase) = @_; my $caller = caller(1); my(undef, undef, undef, $sub) = caller(1); my $meta = $caller->meta; $sub =~ s/^.*:://; Carp::croak "$sub must be in a $phase block" unless $meta->{phase} eq $phase; } sub start_url { my($url) = @_; _in_phase 'share'; my $caller = caller; my $meta = $caller->meta; $meta->prop->{start_url} = $url; $meta->add_requires('configure' => 'Alien::Build' => '1.19'); return; } sub digest { my($algo, $digest) = @_; my $caller = caller; $caller->meta->apply_plugin('Digest', [$algo, $digest]); return; } sub download { my($instr) = @_; _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(download => $instr); return; } sub fetch { my($instr) = @_; _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(fetch => $instr); return; } sub decode { my($instr) = @_; _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(decode => $instr); return; } sub prefer { my($instr) = @_; _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(prefer => $instr); return; } sub extract { my($instr) = @_; _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(extract => $instr); return; } sub patch { my($instr) = @_; _in_phase 'share'; my $caller = caller; my $suffix = $caller->meta->{build_suffix}; $caller->meta->register_hook("patch$suffix" => $instr); return; } sub patch_ffi { my($instr) = @_; Carp::carp("patch_ffi is deprecated, use ffi { patch ... } } instead"); _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(patch_ffi => $instr); return; } sub build { my($instr) = @_; _in_phase 'share'; my $caller = caller; my $suffix = $caller->meta->{build_suffix}; $caller->meta->register_hook("build$suffix" => $instr); return; } sub build_ffi { my($instr) = @_; Carp::carp("build_ffi is deprecated, use ffi { build ... } } instead"); _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(build_ffi => $instr); return; } sub gather { my($instr) = @_; my $caller = caller; my $meta = $caller->meta; my $phase = $meta->{phase}; Carp::croak "gather is not allowed in configure block" if $phase eq 'configure'; my $suffix = $caller->meta->{build_suffix}; if($suffix eq '_ffi') { $meta->register_hook(gather_ffi => $instr) } else { $meta->register_hook(gather_system => $instr) if $phase =~ /^(any|system)$/; $meta->register_hook(gather_share => $instr) if $phase =~ /^(any|share)$/; } return; } sub gather_ffi { my($instr) = @_; Carp::carp("gather_ffi is deprecated, use ffi { gather ... } } instead"); _in_phase 'share'; my $caller = caller; $caller->meta->register_hook(gather_ffi => $instr); return; } sub ffi (&) { my($code) = @_; _in_phase 'share'; my $caller = caller; local $caller->meta->{build_suffix} = '_ffi'; $code->(); return; } sub meta_prop { my $caller = caller; my $meta = $caller->meta; $meta->prop; } sub log { unshift @_, 'Alien::Build'; goto &Alien::Build::log; } sub test { my($instr) = @_; my $caller = caller; my $meta = $caller->meta; my $phase = $meta->{phase}; Carp::croak "test is not allowed in $phase block" if $phase eq 'any' || $phase eq 'configure'; $meta->add_requires('configure' => 'Alien::Build' => '1.14'); if($phase eq 'share') { my $suffix = $caller->meta->{build_suffix} || '_share'; $meta->register_hook( "test$suffix" => $instr, ); } elsif($phase eq 'system') { $meta->register_hook( "test_system" => $instr, ); } else { die "unknown phase: $phase"; } } my %modifiers = ( probe => { any => 'probe' }, download => { share => 'download' }, fetch => { share => 'fetch' }, decode => { share => 'fetch' }, prefer => { share => 'prefer' }, extract => { share => 'extract' }, patch => { share => 'patch$' }, build => { share => 'build$' }, test => { share => 'test$' }, # Note: below special case gather_ffi for the ffi block :P gather => { share => 'gather_share', system => 'gather_system', any => 'gather_share,gather_system' }, ); sub _add_modifier { my($type, $stage, $sub) = @_; my $method = "${type}_hook"; Carp::croak "No such stage $stage" unless defined $modifiers{$stage}; Carp::croak "$type $stage argument must be a code reference" unless defined $sub && ref($sub) eq 'CODE'; my $caller = caller; my $meta = $caller->meta; Carp::croak "$type $stage is not allowed in sys block" unless defined $modifiers{$stage}->{$meta->{phase}}; $meta->add_requires('configure' => 'Alien::Build' => '1.40'); my $suffix = $meta->{build_suffix}; if($suffix eq '_ffi' && $stage eq 'gather') { $meta->$method('gather_ffi' => $sub); } foreach my $hook ( map { split /,/, $_ } # split on , for when multiple hooks must be attached (gather in any) map { my $x = $_ ; $x =~ s/\$/$suffix/; $x } # substitute $ at the end for a suffix (_ffi) if any $modifiers{$stage}->{$meta->{phase}}) # get the list of modifiers { $meta->$method($hook => $sub); } return; } sub before { my($stage, $sub) = @_; @_ = ('before', @_); goto &alienfile::_add_modifier; } sub after { my($stage, $sub) = @_; @_ = ('after', @_); goto &alienfile::_add_modifier; } sub import { strict->import; warnings->import; goto &Exporter::import; } 1; __END__ =pod =encoding UTF-8 =head1 NAME alienfile - Specification for defining an external dependency for CPAN =head1 VERSION version 2.83 =head1 SYNOPSIS Do-it-yourself approach: use alienfile; probe [ 'pkg-config --exists libarchive' ]; share { start_url 'http://libarchive.org/downloads/libarchive-3.2.2.tar.gz'; # the first one which succeeds will be used download [ 'wget %{.meta.start_url}' ]; download [ 'curl -o %{.meta.start_url}' ]; extract [ 'tar xf %{.install.download}' ]; build [ # Note: will not work on Windows, better to use Build::Autoconf plugin # if you need windows support './configure --prefix=%{.install.prefix} --disable-shared', '%{make}', '%{make} install', ]; } gather [ [ 'pkg-config', '--modversion', 'libarchive', \'%{.runtime.version}' ], [ 'pkg-config', '--cflags', 'libarchive', \'%{.runtime.cflags}' ], [ 'pkg-config', '--libs', 'libarchive', \'%{.runtime.libs}' ], ]; With plugins (better): use alienfile; plugin 'PkgConfig' => 'libarchive'; share { start_url 'http://libarchive.org/downloads/'; plugin Download => ( filter => qr/^libarchive-.*\.tar\.gz$/, version => qr/([0-9\.]+)/, ); plugin Extract => 'tar.gz'; plugin 'Build::Autoconf'; plugin 'Gather::IsolateDynamic'; build [ '%{configure}', '%{make}', '%{make} install', ]; }; =head1 DESCRIPTION An alienfile is a recipe used by L to, probe for system libraries or download from the internet, and build source for those libraries. This document acts as reference for the alienfile system, but if you are starting out writing your own Alien you should read L, which will teach you how to write your own complete Alien using alienfile + L + L. Special attention should be taken to the section "a note about dynamic vs. static libraries". =head1 DIRECTIVES =head2 requires "any" requirement (either share or system): requires $module; requires $module => $version; configure time requirement: configure { requires $module; requires $module => $version; }; system requirement: sys { requires $module; requires $module => $version; }; share requirement: share { requires $module; requires $module => $version; }; specifies a requirement. L takes advantage of dynamic requirements, so only modules that are needed for the specific type of install need to be loaded. Here are the different types of requirements: =over =item configure Configure requirements should already be installed before the alienfile is loaded. =item any "Any" requirements are those that are needed either for the probe stage, or in either the system or share installs. =item share Share requirements are those modules needed when downloading and building from source. =item system System requirements are those modules needed when the system provides the library or tool. =back =head2 plugin plugin $name => (%args); plugin $name => $arg; Load the given plugin. If you prefix the plugin name with an C<=> sign, then it will be assumed to be a fully qualified path name. Otherwise the plugin will be assumed to live in the C namespace. If there is an appropriate negotiate plugin, that one will be loaded. Examples: # Loads Alien::Build::Plugin::Fetch::Negotiate # which will pick the best Alien::Build::Plugin::Fetch # plugin based on the URL, and system configuration plugin 'Fetch' => 'http://ftp.gnu.org/gnu/gcc'; # loads the plugin with the badly named class! plugin '=Badly::Named::Plugin::Not::In::Alien::Build::Namespace'; # explicitly loads Alien::Build::Plugin::Prefer::SortVersions plugin 'Prefer::SortVersions' => ( filter => qr/^gcc-.*\.tar\.gz$/, version => qr/([0-9\.]+)/, ); =head2 probe probe \&code; probe \@commandlist; Instructions for the probe stage. May be either a code reference, or a command list. Multiple probes and probe plugins can be given. These will be used in sequence, stopping at the first that detects a system installation. L will use a share install if no system installation is detected by the probes. =head2 configure configure { ... }; Configure block. The only directive allowed in a configure block is requires. =head2 sys sys { ... }; System block. Allowed directives are: requires and gather. =head2 share share { ... }; System block. Allowed directives are: download, fetch, decode, prefer, extract, build, gather. =head2 start_url share { start_url $url; }; Set the start URL for download. This should be the URL to an index page, or the actual tarball of the source. =head2 digest [experimental] share { digest $algorithm, $digest; }; Check fetched and downloaded files against the given algorithm and digest. Typically you will want to use SHA256 as the algorithm. =head2 download share { download \&code; download \@commandlist; }; Instructions for the download stage. May be either a code reference, or a command list. =head2 fetch share { fetch \&code; fetch \@commandlist; }; Instructions for the fetch stage. May be either a code reference, or a command list. =head2 decode share { decode \&code; decode \@commandlist; }; Instructions for the decode stage. May be either a code reference, or a command list. =head2 prefer share { prefer \&code; prefer \@commandlist; }; Instructions for the prefer stage. May be either a code reference, or a command list. =head2 extract share { extract \&code; extract \@commandlist; }; Instructions for the extract stage. May be either a code reference, or a command list. =head2 patch share { patch \&code; patch \@commandlist; }; Instructions for the patch stage. May be either a code reference, or a command list. =head2 patch_ffi share { patch_ffi \&code; patch_ffi \@commandlist; }; [DEPRECATED] Instructions for the patch_ffi stage. May be either a code reference, or a command list. =head2 build share { build \&code; build \@commandlist; }; Instructions for the build stage. May be either a code reference, or a command list. =head2 build_ffi share { build \&code; build \@commandlist; }; [DEPRECATED] Instructions for the build FFI stage. Builds shared libraries instead of static. This is optional, and is only necessary if a fresh and separate build needs to be done for FFI. =head2 gather gather \&code; gather \@commandlist; share { gather \&code; gather \@commandlist; }; sys { gather \&code; gather \@commandlist; }; Instructions for the gather stage. May be either a code reference, or a command list. In the root block of the alienfile it will trigger in both share and system build. In the share or sys block it will only trigger in the corresponding build. =head2 gather_ffi share { gather_ffi \&code; gather_ffi \@commandlist; } [DEPRECATED] Gather specific to C. Not usually necessary. =head2 ffi share { ffi { patch \&code; patch \@commandlist; build \&code; build \@commandlist; gather \&code; gather \@commandlist; } } Specify patch, build or gather stages related to FFI. =head2 meta_prop my $hash = meta_prop; Get the meta_prop hash reference. =head2 meta my $meta = meta; Returns the meta object for your L. For methods that can be used on the meta object, see L. =head2 log log($message); Prints the given log to stdout. =head2 test share { test \&code; test \@commandlist; }; sys { test \&code; test \@commandlist; }; Run the tests =head2 before before $stage => \&code; Execute the given code before the given stage. Stage should be one of C, C, C, C, C, C, C, C, C, and C. The before directive is only legal in the same blocks as the stage would normally be legal in. For example, you can't do this: use alienfile; sys { before 'build' => sub { ... }; }; Because a C wouldn't be legal inside a C block. =head2 after after $stage => \&code; Execute the given code after the given stage. Stage should be one of C, C, C, C, C, C, C, C, C, and C. The after directive is only legal in the same blocks as the stage would normally be legal in. For example, you can't do this: use alienfile; sys { after 'build' => sub { ... }; }; Because a C wouldn't be legal inside a C block. =head1 SEE ALSO =over 4 =item L =item L =item L =item L =back =head1 AUTHOR Author: Graham Ollis Eplicease@cpan.orgE Contributors: Diab Jerius (DJERIUS) Roy Storey (KIWIROY) Ilya Pavlov David Mertens (run4flat) Mark Nunberg (mordy, mnunberg) Christian Walde (Mithaldu) Brian Wightman (MidLifeXis) Zaki Mughal (zmughal) mohawk (mohawk2, ETJ) Vikas N Kumar (vikasnkumar) Flavio Poletti (polettix) Salvador Fandiño (salva) Gianni Ceccarelli (dakkar) Pavel Shaydo (zwon, trinitum) Kang-min Liu (劉康民, gugod) Nicholas Shipp (nshp) Juan Julián Merelo Guervós (JJ) Joel Berger (JBERGER) Petr PísaÅ™ (ppisar) Lance Wicks (LANCEW) Ahmad Fatoum (a3f, ATHREEF) José Joaquín Atria (JJATRIA) Duke Leto (LETO) Shoichi Kaji (SKAJI) Shawn Laffan (SLAFFAN) Paul Evans (leonerd, PEVANS) HÃ¥kon Hægland (hakonhagland, HAKONH) nick nauwelaerts (INPHOBIA) Florian Weimer =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011-2022 by Graham Ollis. 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 PK!ÊèË|11perl5/cPanelUserConfig.pmnu„[µü¤# cpanel - cPanelUserConfig.pm Copyright(c) 2021 cPanel, L.L.C. # All Rights Reserved. # copyright@cpanel.net http://cpanel.net # This code is subject to the cPanel license. Unauthorized copying is prohibited BEGIN { if ( $> != 0 ) { my $b__dir = ( getpwuid($>) )[7] . '/perl'; unshift @INC, $b__dir . '5/lib/perl5', $b__dir . '5/lib/perl5/x86_64-linux-thread-multi', map { $b__dir . $_ } grep { $_ ne '.' } @INC; } } 1; PK!X6qù—R—Rperl5/Try/Tiny.pmnuÏÃ6Ç$package Try::Tiny; # git description: v0.30-11-g1b81d0a use 5.006; # ABSTRACT: Minimal try/catch with proper preservation of $@ our $VERSION = '0.31'; use strict; use warnings; use Exporter 5.57 'import'; our @EXPORT = our @EXPORT_OK = qw(try catch finally); use Carp; $Carp::Internal{+__PACKAGE__}++; BEGIN { my $su = $INC{'Sub/Util.pm'} && defined &Sub::Util::set_subname; my $sn = $INC{'Sub/Name.pm'} && eval { Sub::Name->VERSION(0.08) }; unless ($su || $sn) { $su = eval { require Sub::Util; } && defined &Sub::Util::set_subname; unless ($su) { $sn = eval { require Sub::Name; Sub::Name->VERSION(0.08) }; } } *_subname = $su ? \&Sub::Util::set_subname : $sn ? \&Sub::Name::subname : sub { $_[1] }; *_HAS_SUBNAME = ($su || $sn) ? sub(){1} : sub(){0}; } my %_finally_guards; # Need to prototype as @ not $$ because of the way Perl evaluates the prototype. # Keeping it at $$ means you only ever get 1 sub because we need to eval in a list # context & not a scalar one sub try (&;@) { my ( $try, @code_refs ) = @_; # we need to save this here, the eval block will be in scalar context due # to $failed my $wantarray = wantarray; # work around perl bug by explicitly initializing these, due to the likelyhood # this will be used in global destruction (perl rt#119311) my ( $catch, @finally ) = (); # find labeled blocks in the argument list. # catch and finally tag the blocks by blessing a scalar reference to them. foreach my $code_ref (@code_refs) { if ( ref($code_ref) eq 'Try::Tiny::Catch' ) { croak 'A try() may not be followed by multiple catch() blocks' if $catch; $catch = ${$code_ref}; } elsif ( ref($code_ref) eq 'Try::Tiny::Finally' ) { push @finally, ${$code_ref}; } else { croak( 'try() encountered an unexpected argument (' . ( defined $code_ref ? $code_ref : 'undef' ) . ') - perhaps a missing semi-colon before or' ); } } # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's # not perfect, but we could provide a list of additional errors for # $catch->(); # name the blocks if we have Sub::Name installed _subname(caller().'::try {...} ' => $try) if _HAS_SUBNAME; # set up scope guards to invoke the finally blocks at the end. # this should really be a function scope lexical variable instead of # file scope + local but that causes issues with perls < 5.20 due to # perl rt#119311 local $_finally_guards{guards} = [ map Try::Tiny::ScopeGuard->_new($_), @finally ]; # save the value of $@ so we can set $@ back to it in the beginning of the eval # and restore $@ after the eval finishes my $prev_error = $@; my ( @ret, $error ); # failed will be true if the eval dies, because 1 will not be returned # from the eval body my $failed = not eval { $@ = $prev_error; # evaluate the try block in the correct context if ( $wantarray ) { @ret = $try->(); } elsif ( defined $wantarray ) { $ret[0] = $try->(); } else { $try->(); }; return 1; # properly set $failed to false }; # preserve the current error and reset the original value of $@ $error = $@; $@ = $prev_error; # at this point $failed contains a true value if the eval died, even if some # destructor overwrote $@ as the eval was unwinding. if ( $failed ) { # pass $error to the finally blocks push @$_, $error for @{$_finally_guards{guards}}; # if we got an error, invoke the catch block. if ( $catch ) { # This works like given($error), but is backwards compatible and # sets $_ in the dynamic scope for the body of C<$catch> for ($error) { return $catch->($error); } # in case when() was used without an explicit return, the C # loop will be aborted and there's no useful return value } return; } else { # no failure, $@ is back to what it was, everything is fine return $wantarray ? @ret : $ret[0]; } } sub catch (&;@) { my ( $block, @rest ) = @_; croak 'Useless bare catch()' unless wantarray; _subname(caller().'::catch {...} ' => $block) if _HAS_SUBNAME; return ( bless(\$block, 'Try::Tiny::Catch'), @rest, ); } sub finally (&;@) { my ( $block, @rest ) = @_; croak 'Useless bare finally()' unless wantarray; _subname(caller().'::finally {...} ' => $block) if _HAS_SUBNAME; return ( bless(\$block, 'Try::Tiny::Finally'), @rest, ); } { package # hide from PAUSE Try::Tiny::ScopeGuard; use constant UNSTABLE_DOLLARAT => ("$]" < '5.013002') ? 1 : 0; sub _new { shift; bless [ @_ ]; } sub DESTROY { my ($code, @args) = @{ $_[0] }; local $@ if UNSTABLE_DOLLARAT; eval { $code->(@args); 1; } or do { warn "Execution of finally() block $code resulted in an exception, which " . '*CAN NOT BE PROPAGATED* due to fundamental limitations of Perl. ' . 'Your program will continue as if this event never took place. ' . "Original exception text follows:\n\n" . (defined $@ ? $@ : '$@ left undefined...') . "\n" ; } } } __PACKAGE__ __END__ =pod =encoding UTF-8 =head1 NAME Try::Tiny - Minimal try/catch with proper preservation of $@ =head1 VERSION version 0.31 =head1 SYNOPSIS You can use Try::Tiny's C and C to expect and handle exceptional conditions, avoiding quirks in Perl and common mistakes: # handle errors with a catch handler try { die "foo"; } catch { warn "caught error: $_"; # not $@ }; You can also use it like a standalone C to catch and ignore any error conditions. Obviously, this is an extreme measure not to be undertaken lightly: # just silence errors try { die "foo"; }; =head1 DESCRIPTION This module provides bare bones C/C/C statements that are designed to minimize common mistakes with eval blocks, and NOTHING else. This is unlike L which provides a nice syntax and avoids adding another call stack layer, and supports calling C from the C block to return from the parent subroutine. These extra features come at a cost of a few dependencies, namely L and L which are occasionally problematic, and the additional catch filtering uses L type constraints which may not be desirable either. The main focus of this module is to provide simple and reliable error handling for those having a hard time installing L, but who still want to write correct C blocks without 5 lines of boilerplate each time. It's designed to work as correctly as possible in light of the various pathological edge cases (see L) and to be compatible with any style of error values (simple strings, references, objects, overloaded objects, etc). If the C block dies, it returns the value of the last statement executed in the C block, if there is one. Otherwise, it returns C in scalar context or the empty list in list context. The following examples all assign C<"bar"> to C<$x>: my $x = try { die "foo" } catch { "bar" }; my $x = try { die "foo" } || "bar"; my $x = (try { die "foo" }) // "bar"; my $x = eval { die "foo" } || "bar"; You can add C blocks, yielding the following: my $x; try { die 'foo' } finally { $x = 'bar' }; try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' }; C blocks are always executed making them suitable for cleanup code which cannot be handled using local. You can add as many C blocks to a given C block as you like. Note that adding a C block without a preceding C block suppresses any errors. This behaviour is consistent with using a standalone C, but it is not consistent with C/C patterns found in other programming languages, such as Java, Python, Javascript or C#. If you learned the C/C pattern from one of these languages, watch out for this. =head1 EXPORTS All functions are exported by default using L. If you need to rename the C, C or C keyword consider using L to get L's flexibility. =over 4 =item try (&;@) Takes one mandatory C subroutine, an optional C subroutine and C subroutine. The mandatory subroutine is evaluated in the context of an C block. If no error occurred the value from the first block is returned, preserving list/scalar context. If there was an error and the second subroutine was given it will be invoked with the error in C<$_> (localized) and as that block's first and only argument. C<$@> does B contain the error. Inside the C block it has the same value it had before the C block was executed. Note that the error may be false, but if that happens the C block will still be invoked. Once all execution is finished then the C block, if given, will execute. =item catch (&;@) Intended to be used in the second argument position of C. Returns a reference to the subroutine it was given but blessed as C which allows try to decode correctly what to do with this code reference. catch { ... } Inside the C block the caught error is stored in C<$_>, while previous value of C<$@> is still available for use. This value may or may not be meaningful depending on what happened before the C, but it might be a good idea to preserve it in an error stack. For code that captures C<$@> when throwing new errors (i.e. L), you'll need to do: local $@ = $_; =item finally (&;@) try { ... } catch { ... } finally { ... }; Or try { ... } finally { ... }; Or even try { ... } finally { ... } catch { ... }; Intended to be the second or third element of C. C blocks are always executed in the event of a successful C or if C is run. This allows you to locate cleanup code which cannot be done via C e.g. closing a file handle. When invoked, the C block is passed the error that was caught. If no error was caught, it is passed nothing. (Note that the C block does not localize C<$_> with the error, since unlike in a C block, there is no way to know if C<$_ == undef> implies that there were no errors.) In other words, the following code does just what you would expect: try { die_sometimes(); } catch { # ...code run in case of error } finally { if (@_) { print "The try block died with: @_\n"; } else { print "The try block ran without error.\n"; } }; B block>. C will not do anything about handling possible errors coming from code located in these blocks. Furthermore B blocks are not trappable and are unable to influence the execution of your program>. This is due to limitation of C-based scope guards, which C is implemented on top of. This may change in a future version of Try::Tiny. In the same way C blesses the code reference this subroutine does the same except it bless them as C. =back =head1 BACKGROUND There are a number of issues with C. =head2 Clobbering $@ When you run an C block and it succeeds, C<$@> will be cleared, potentially clobbering an error that is currently being caught. This causes action at a distance, clearing previous errors your caller may have not yet handled. C<$@> must be properly localized before invoking C in order to avoid this issue. More specifically, L C<$@> was clobbered at the beginning of the C, which also made it impossible to capture the previous error before you die (for instance when making exception objects with error stacks). For this reason C will actually set C<$@> to its previous value (the one available before entering the C block) in the beginning of the C block. =head2 Localizing $@ silently masks errors Inside an C block, C behaves sort of like: sub die { $@ = $_[0]; return_undef_from_eval(); } This means that if you were polite and localized C<$@> you can't die in that scope, or your error will be discarded (printing "Something's wrong" instead). The workaround is very ugly: my $error = do { local $@; eval { ... }; $@; }; ... die $error; =head2 $@ might not be a true value This code is wrong: if ( $@ ) { ... } because due to the previous caveats it may have been unset. C<$@> could also be an overloaded error object that evaluates to false, but that's asking for trouble anyway. The classic failure mode (fixed in L) is: sub Object::DESTROY { eval { ... } } eval { my $obj = Object->new; die "foo"; }; if ( $@ ) { } In this case since C is not localizing C<$@> but still uses C, it will set C<$@> to C<"">. The destructor is called when the stack is unwound, after C sets C<$@> to C<"foo at Foo.pm line 42\n">, so by the time C is evaluated it has been cleared by C in the destructor. The workaround for this is even uglier than the previous ones. Even though we can't save the value of C<$@> from code that doesn't localize, we can at least be sure the C was aborted due to an error: my $failed = not eval { ... return 1; }; This is because an C that caught a C will always return a false value. =head1 ALTERNATE SYNTAX Using Perl 5.10 you can use L (but please don't, because that syntax has since been deprecated because there was too much unexpected magical behaviour). =for stopwords topicalizer The C block is invoked in a topicalizer context (like a C block), but note that you can't return a useful value from C using the C blocks without an explicit C. This is somewhat similar to Perl 6's C blocks. You can use it to concisely match errors: try { require Foo; } catch { when (/^Can't locate .*?\.pm in \@INC/) { } # ignore default { die $_ } }; =head1 CAVEATS =over 4 =item * C<@_> is not available within the C block, so you need to copy your argument list. In case you want to work with argument values directly via C<@_> aliasing (i.e. allow C<$_[1] = "foo">), you need to pass C<@_> by reference: sub foo { my ( $self, @args ) = @_; try { $self->bar(@args) } } or sub bar_in_place { my $self = shift; my $args = \@_; try { $_ = $self->bar($_) for @$args } } =item * C returns from the C block, not from the parent sub (note that this is also how C works, but not how L works): sub parent_sub { try { die; } catch { return; }; say "this text WILL be displayed, even though an exception is thrown"; } Instead, you should capture the return value: sub parent_sub { my $success = try { die; 1; }; return unless $success; say "This text WILL NEVER appear!"; } # OR sub parent_sub_with_catch { my $success = try { die; 1; } catch { # do something with $_ return undef; #see note }; return unless $success; say "This text WILL NEVER appear!"; } Note that if you have a C block, it must return C for this to work, since if a C block exists, its return value is returned in place of C when an exception is thrown. =item * C introduces another caller stack frame. L is not used. L will not report this when using full stack traces, though, because C<%Carp::Internal> is used. This lack of magic is considered a feature. =for stopwords unhygienically =item * The value of C<$_> in the C block is not guaranteed to be the value of the exception thrown (C<$@>) in the C block. There is no safe way to ensure this, since C may be used unhygienically in destructors. The only guarantee is that the C will be called if an exception is thrown. =item * The return value of the C block is not ignored, so if testing the result of the expression for truth on success, be sure to return a false value from the C block: my $obj = try { MightFail->new; } catch { ... return; # avoid returning a true value; }; return unless $obj; =item * C<$SIG{__DIE__}> is still in effect. Though it can be argued that C<$SIG{__DIE__}> should be disabled inside of C blocks, since it isn't people have grown to rely on it. Therefore in the interests of compatibility, C does not disable C<$SIG{__DIE__}> for the scope of the error throwing code. =item * Lexical C<$_> may override the one set by C. For example Perl 5.10's C form uses a lexical C<$_>, creating some confusing behavior: given ($foo) { when (...) { try { ... } catch { warn $_; # will print $foo, not the error warn $_[0]; # instead, get the error like this } } } Note that this behavior was changed once again in L. However, since the entirety of lexical C<$_> is now L, it is unclear whether the new version 18 behavior is final. =back =head1 SEE ALSO =over 4 =item L Only available on perls >= 5.14, with a slightly different syntax (e.g. no trailing C<;> because it's actually a keyword, not a sub, but this means you can C and C within it). Use L to automatically switch to the native C syntax in newer perls (when available). See also L. =item L Much more feature complete, more convenient semantics, but at the cost of implementation complexity. =item L Automatic error throwing for builtin functions and more. Also designed to work well with C/C. =item L A lightweight role for rolling your own exception classes. =item L Exception object implementation with a C statement. Does not localize C<$@>. =item L Provides a C statement, but properly calling C is your responsibility. The C keyword pushes C<$@> onto an error stack, avoiding some of the issues with C<$@>, but you still need to localize to prevent clobbering. =back =head1 LIGHTNING TALK I gave a lightning talk about this module, you can see the slides (Firefox only): L Or read the source: L =head1 SUPPORT Bugs may be submitted through L (or L). =head1 AUTHORS =over 4 =item * יובל קוג'מן (Yuval Kogman) =item * Jesse Luehrs =back =head1 CONTRIBUTORS =for stopwords Karen Etheridge Peter Rabbitson Ricardo Signes Mark Fowler Graham Knop Aristotle Pagaltzis Dagfinn Ilmari MannsÃ¥ker Lukas Mai Alex anaxagoras Andrew Yates awalker chromatic cm-perl David Lowe Glenn Hans Dieter Pearcey Jens Berthold Jonathan Yu Marc Mims Stosberg Pali Paul Howarth Rudolf Leermakers =over 4 =item * Karen Etheridge =item * Peter Rabbitson =item * Ricardo Signes =item * Mark Fowler =item * Graham Knop =item * Aristotle Pagaltzis =item * Dagfinn Ilmari MannsÃ¥ker =item * Lukas Mai =item * Alex =item * anaxagoras =item * Andrew Yates =item * awalker =item * chromatic =item * cm-perl =item * David Lowe =item * Glenn Fowler =item * Hans Dieter Pearcey =item * Jens Berthold =item * Jonathan Yu =item * Marc Mims =item * Mark Stosberg =item * Pali =item * Paul Howarth =item * Rudolf Leermakers =back =head1 COPYRIGHT AND LICENCE This software is Copyright (c) 2009 by יובל קוג'מן (Yuval Kogman). This is free software, licensed under: The MIT (X11) License =cut PK!¤Ñ-}}@perl5/x86_64-linux-thread-multi/.meta/Net-HTTP-6.19/install.jsonnuÏÃ6Ç${"provides":{"Net::HTTP":{"version":6.19,"file":"lib/Net/HTTP.pm"},"Net::HTTPS":{"version":6.19,"file":"lib/Net/HTTPS.pm"},"Net::HTTP::NB":{"version":6.19,"file":"lib/Net/HTTP/NB.pm"},"Net::HTTP::Methods":{"version":6.19,"file":"lib/Net/HTTP/Methods.pm"}},"target":"Net::HTTP","version":6.19,"name":"Net::HTTP","dist":"Net-HTTP-6.19","pathname":"O/OA/OALDERS/Net-HTTP-6.19.tar.gz"}PK!Õ+tH8k8k?perl5/x86_64-linux-thread-multi/.meta/Net-HTTP-6.19/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Low-level HTTP connection (client)", "author" : [ "Gisle Aas " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Net-HTTP", "no_index" : { "directory" : [ "examples", "t", "xt" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "requires" : { "Test::More" : "0", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "Carp" : "0", "Compress::Raw::Zlib" : "0", "IO::Socket::INET" : "0", "IO::Uncompress::Gunzip" : "0", "URI" : "0", "base" : "0", "perl" : "5.006002", "strict" : "0", "vars" : "0", "warnings" : "0" }, "suggests" : { "IO::Socket" : "0", "IO::Socket::INET6" : "0", "IO::Socket::IP" : "0", "IO::Socket::SSL" : "2.012", "Symbol" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "Data::Dumper" : "0", "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "IO::Select" : "0", "Socket" : "0", "Test::More" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/libwww-perl/Net-HTTP/issues" }, "homepage" : "https://github.com/libwww-perl/Net-HTTP", "repository" : { "type" : "git", "url" : "https://github.com/libwww-perl/Net-HTTP.git", "web" : "https://github.com/libwww-perl/Net-HTTP" }, "x_IRC" : "irc://irc.perl.org/#lwp", "x_MailingList" : "mailto:libwww@perl.org" }, "version" : "6.19", "x_Dist_Zilla" : { "perl" : { "version" : "5.026001" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "MetaResources", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "requires" } }, "name" : "Prereqs", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::Author::OALDERS" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, build", "version" : "0.055" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 1, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, release", "version" : "0.055" }, { "class" : "Dist::Zilla::Plugin::MAXMIND::TidyAll", "name" : "@Author::OALDERS/MAXMIND::TidyAll", "version" : "0.83" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1 } }, "name" : "@Author::OALDERS/MakeMaker", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::CPANFile", "name" : "@Author::OALDERS/CPANFile", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::ContributorsFile", "name" : "@Author::OALDERS/ContributorsFile", "version" : "0.3.0" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::OALDERS/MetaJSON", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::OALDERS/MetaYAML", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::OALDERS/Manifest", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Author::OALDERS/MetaNoIndex", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::OALDERS/MetaConfig", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "@Author::OALDERS/MetaResources", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::OALDERS/License", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000033", "version" : "0.004" } }, "name" : "@Author::OALDERS/InstallGuide", "version" : "1.200013" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@Author::OALDERS/ExecDir", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::OALDERS/PodSyntaxTests", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Author::OALDERS/TestRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Author::OALDERS/Test::ReportPrereqs", "version" : "0.027" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1 } }, "name" : "@Author::OALDERS/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Default/SingleEncoding", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Default/Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Default/Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Default/Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Default/Authors", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Default/Legal", "version" : "4.015" } ] } }, "name" : "@Author::OALDERS/PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@Author::OALDERS/PruneCruft", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromBuild", "name" : "@Author::OALDERS/CopyFilesFromBuild", "version" : "0.170880" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@Author::OALDERS/GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@Author::OALDERS/Git::GatherDir", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Install" ], "match" : [] } }, "name" : "@Author::OALDERS/CopyFilesFromRelease", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.21.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Check", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.21.0", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "@Author::OALDERS/Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "@Author::OALDERS/ReadmeMdInBuild", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@Author::OALDERS/ShareDir", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::TravisCI::StatusBadge", "name" : "@Author::OALDERS/TravisCI::StatusBadge", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CheckIssues", "name" : "@Author::OALDERS/CheckIssues", "version" : "0.010" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::OALDERS/ConfirmRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Author::OALDERS/UploadToCPAN", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Author::OALDERS/@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Author::OALDERS/@Git::VersionManager/CopyFilesFromRelease", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.21.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/release snapshot", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v6.19", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.21.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/Git::Tag", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Author::OALDERS/@Git::VersionManager/NextRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.21.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/post-release commit", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.21.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Push", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "AutoPrereqs", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "suggests" } }, "name" : "RuntimeSuggests", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Prereqs::Soften", "config" : { "Dist::Zilla::Plugin::Prereqs::Soften" : { "copy_to" : [], "modules" : [ "IO::Socket", "IO::Socket::INET6", "IO::Socket::IP", "IO::Socket::SSL", "Symbol" ], "modules_from_features" : null, "to_relationship" : "suggests" } }, "name" : "Prereqs::Soften", "version" : "0.006003" }, { "class" : "Dist::Zilla::Plugin::StaticInstall", "config" : { "Dist::Zilla::Plugin::StaticInstall" : { "dry_run" : 0, "mode" : "on" } }, "name" : "StaticInstall", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.012" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.012" } }, "x_contributors" : [ "Adam Kennedy ", "Adam Sjogren ", "Alexey Tourbin ", "Alex Kapranoff ", "amire80 ", "Andreas J. Koenig ", "Andy Grundman ", "Bill Mann ", "Bron Gondwana ", "Chase Whitener ", "Dagfinn Ilmari MannsÃ¥ker ", "Daniel Hedlund ", "Dave Rolsky ", "David E. Wheeler ", "DAVIDRW ", "David Steinbrunner ", "Eric Wong ", "Father Chrysostomos ", "FWILES ", "Gavin Peters ", "Gisle Aas ", "Gisle Aas ", "Gisle Aas ", "Gisle Aas ", "Graeme Thompson ", "Hans-H. Froehlich ", "Ian Kilgore ", "Jacob J ", "Jason A Fesler ", "Jay Hannah ", "Jean-Louis Martineau ", "jefflee ", "Jesse Luehrs ", "john9art ", "Karen Etheridge ", "Kent Fredric ", "Lasse Makholm ", "Marinos Yannikos ", "Mark Overmeer ", "Mark Stosberg ", "Mark Stosberg ", "Mark Stosberg ", "Mike Schilli ", "Mike Schilli ", "Mohammad S Anwar ", "murphy ", "Olaf Alders ", "Ondrej Hanak ", "Peter Rabbitson ", "phrstbrn ", "Robert Stone ", "Rolf Grossmann ", "ruff ", "sasao ", "Sean M. Burke ", "Shoichi Kaji ", "Slaven Rezic ", "Slaven Rezic ", "Spiros Denaxas ", "Steffen Ullrich ", "Steve Hay ", "Todd Lipcon ", "Tom Hukins ", "Tony Finch ", "Toru Yamaguchi ", "uid39246 ", "Ville Skytta ", "Yuri Karaban ", "Zefram " ], "x_generated_by_perl" : "v5.26.1", "x_serialization_backend" : "JSON::PP version 2.97001", "x_static_install" : 1 } PK!|æîßööAperl5/x86_64-linux-thread-multi/.meta/HTML-Form-6.07/install.jsonnuÏÃ6Ç${"provides":{"HTML::Form":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::ListInput":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::TextInput":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::ImageInput":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::FileInput":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::IgnoreInput":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::KeygenInput":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::Input":{"version":"6.07","file":"lib/HTML/Form.pm"},"HTML::Form::SubmitInput":{"version":"6.07","file":"lib/HTML/Form.pm"}},"target":"HTML::Form","version":"6.07","name":"HTML::Form","dist":"HTML-Form-6.07","pathname":"O/OA/OALDERS/HTML-Form-6.07.tar.gz"}PK!QìeêÀsÀs@perl5/x86_64-linux-thread-multi/.meta/HTML-Form-6.07/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Class that represents an HTML form element", "author" : [ "Gisle Aas " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "HTML-Form", "no_index" : { "directory" : [ "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "recommends" : { "Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007" }, "requires" : { "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Test::EOL" : "0", "Test::MinimumVersion" : "0", "Test::Mojibake" : "0", "Test::More" : "0.94", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1", "perl" : "5.006", "warnings" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "Encode" : "2", "HTML::TokeParser" : "0", "HTTP::Request" : "6", "HTTP::Request::Common" : "6.03", "URI" : "1.10", "perl" : "5.008001", "strict" : "0", "vars" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "HTTP::Response" : "0", "Test" : "0", "Test::More" : "0", "lib" : "0", "warnings" : "0" } } }, "provides" : { "HTML::Form" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::FileInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::IgnoreInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::ImageInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::Input" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::KeygenInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::ListInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::SubmitInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" }, "HTML::Form::TextInput" : { "file" : "lib/HTML/Form.pm", "version" : "6.07" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/libwww-perl/HTML-Form/issues" }, "homepage" : "https://github.com/libwww-perl/HTML-Form", "repository" : { "type" : "git", "url" : "https://github.com/libwww-perl/HTML-Form.git", "web" : "https://github.com/libwww-perl/HTML-Form" }, "x_IRC" : "irc://irc.perl.org/#lwp", "x_MailingList" : "mailto:libwww@perl.org" }, "version" : "6.07", "x_Dist_Zilla" : { "perl" : { "version" : "5.026001" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "Git::GatherDir", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "MetaConfig", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Package", "config" : { "Dist::Zilla::Plugin::MetaProvides::Package" : { "finder_objects" : [ { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.012" } ], "include_underscores" : 0 }, "Dist::Zilla::Role::MetaProvider::Provider" : { "$Dist::Zilla::Role::MetaProvider::Provider::VERSION" : "2.002004", "inherit_missing" : 1, "inherit_version" : 1, "meta_noindex" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000036", "version" : "0.006" } }, "name" : "MetaProvides::Package", "version" : "2.004003" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "MetaNoIndex", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "MetaYAML", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "MetaJSON", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "MetaResources", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.25.0", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Authority", "name" : "Authority", "version" : "1.009" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "Manifest", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "License", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000036", "version" : "0.006" } }, "name" : "InstallGuide", "version" : "1.200013" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "ExecDir", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "requires" } }, "name" : "Prereqs", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "AutoPrereqs", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::CPANFile", "name" : "CPANFile", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1 } }, "name" : "MakeMaker", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::Test::Version", "name" : "Test::Version", "version" : "1.09" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "Test::ReportPrereqs", "version" : "0.027" }, { "class" : "Dist::Zilla::Plugin::Test::Compile", "config" : { "Dist::Zilla::Plugin::Test::Compile" : { "bail_out_on_fail" : "1", "fail_on_warning" : "author", "fake_home" : 0, "filename" : "xt/author/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "develop", "script_finder" : [ ":PerlExecFiles" ], "skips" : [], "switch" : [] } }, "name" : "Test::Compile", "version" : "2.058" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "00-compile.t", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "Test::Portability", "version" : "2.001000" }, { "class" : "Dist::Zilla::Plugin::Test::EOL", "config" : { "Dist::Zilla::Plugin::Test::EOL" : { "filename" : "xt/author/eol.t", "finder" : [ ":ExecFiles", ":InstallModules", ":TestFiles" ], "trailing_whitespace" : 1 } }, "name" : "Test::EOL", "version" : "0.19" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "changes_has_content.t", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Test::MinimumVersion", "config" : { "Dist::Zilla::Plugin::Test::MinimumVersion" : { "max_target_perl" : null } }, "name" : "Test::MinimumVersion", "version" : "2.000010" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "PodSyntaxTests", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable", "name" : "Test::Pod::Coverage::Configurable", "version" : "0.07" }, { "class" : "Dist::Zilla::Plugin::Test::PodSpelling", "config" : { "Dist::Zilla::Plugin::Test::PodSpelling" : { "directories" : [ "bin", "lib" ], "spell_cmd" : "aspell list", "stopwords" : [ "CGI", "autocomplete", "checkbox", "readonly", "unsetting", "unvisited" ], "wordlist" : "Pod::Wordlist" } }, "name" : "Test::PodSpelling", "version" : "2.007005" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.25.0", "repo_root" : "." } }, "name" : "Git::Check", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::CheckStrictVersion", "name" : "CheckStrictVersion", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1 } }, "name" : "RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Default/SingleEncoding", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Default/Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Default/Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Default/Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Default/Authors", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Default/Legal", "version" : "4.015" } ] } }, "name" : "PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::CheckChangeLog", "name" : "CheckChangeLog", "version" : "0.05" }, { "class" : "Dist::Zilla::Plugin::CheckChangesHasContent", "name" : "CheckChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "TestRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "UploadToCPAN", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "Markdown_Readme", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "LICENSE", "META.json", "Makefile.PL", "cpanfile" ], "match" : [] } }, "name" : "CopyFilesFromRelease", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Git::VersionManager/pluginbundle version", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Git::VersionManager/CopyFilesFromRelease", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "LICENSE", "META.json", "README.md", "cpanfile" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.25.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git::VersionManager/release snapshot", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v6.07", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.25.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git::VersionManager/Git::Tag", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Git::VersionManager/NextRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.25.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git::VersionManager/post-release commit", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.25.0", "repo_root" : "." } }, "name" : "Git::Push", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "ConfirmRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.012" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.012" } }, "x_authority" : "cpan:LWWWP", "x_contributors" : [ "Adam Kennedy ", "Adam Sjogren ", "Alessandro Ghedini ", "Alexandr Ciornii ", "Alexey Tourbin ", "Alex Kapranoff ", "amire80 ", "Andreas J. Koenig ", "Bill Mann ", "Bron Gondwana ", "Daniel Hedlund ", "David E. Wheeler ", "DAVIDRW ", "David Steinbrunner ", "E. Choroba ", "Father Chrysostomos ", "FWILES ", "Gavin Peters ", "Gisle Aas ", "Gisle Aas ", "Gisle Aas ", "Gisle Aas ", "Graeme Thompson ", "Hans-H. Froehlich ", "Ian Kilgore ", "Jacob J ", "jefflee ", "john9art ", "Julien Fiegehenn ", "Lance Wicks ", "Lukas Mai ", "Mark Stosberg ", "Mark Stosberg ", "Mark Stosberg ", "Mike Schilli ", "mschilli ", "murphy ", "Olaf Alders ", "Ondrej Hanak ", "Peter Rabbitson ", "phrstbrn ", "Robert Stone ", "Rolf Grossmann ", "ruff ", "sasao ", "Sean M. Burke ", "Slaven Rezic ", "Slaven Rezic ", "Spiros Denaxas ", "Steve Hay ", "Todd Lipcon ", "Tom Hukins ", "Tony Finch ", "Toru Yamaguchi ", "uid39246 ", "Ville Skytta ", "Yuri Karaban ", "Zefram " ], "x_generated_by_perl" : "v5.26.1", "x_serialization_backend" : "Cpanel::JSON::XS version 4.10" } PK! Ɖ8UUIperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.102/install.jsonnuÏÃ6Ç${"provides":{"Template::Directive":{"version":"3.100","file":"lib/Template/Directive.pm"},"Template::Document":{"file":"lib/Template/Document.pm","version":"3.100"},"Template::Plugin":{"version":"3.100","file":"lib/Template/Plugin.pm"},"Template::Plugin::Iterator":{"version":"3.100","file":"lib/Template/Plugin/Iterator.pm"},"Template::Toolkit":{"file":"lib/Template/Toolkit.pm","version":"3.100"},"Template::Plugin::Pod":{"version":"3.100","file":"lib/Template/Plugin/Pod.pm"},"Template::Plugin::Date":{"file":"lib/Template/Plugin/Date.pm","version":"3.100"},"Template::Parser":{"version":"3.100","file":"lib/Template/Parser.pm"},"Template::Plugin::Image":{"file":"lib/Template/Plugin/Image.pm","version":"3.100"},"Template::Monad::Assert":{"version":"3.100","file":"lib/Template/Plugin/Assert.pm"},"Template::Constants":{"version":"3.100","file":"lib/Template/Constants.pm"},"Template::TieString":{"file":"lib/Template/Config.pm","version":"3.100"},"Template::Perl":{"version":"3.100","file":"lib/Template/Filters.pm"},"Template::Stash::XS":{"file":"lib/Template/Stash/XS.pm"},"Template::Plugin::Procedural":{"version":"3.100","file":"lib/Template/Plugin/Procedural.pm"},"Template::Plugin::Table":{"file":"lib/Template/Plugin/Table.pm","version":"3.100"},"Template::Service":{"file":"lib/Template/Service.pm","version":"3.100"},"Template::Provider":{"version":"3.100","file":"lib/Template/Provider.pm"},"Template::Plugin::Scalar":{"version":"3.100","file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::View":{"version":"3.100","file":"lib/Template/Plugin/View.pm"},"Template::Plugin::HTML":{"file":"lib/Template/Plugin/HTML.pm","version":"3.100"},"Template::Config":{"version":"3.100","file":"lib/Template/Config.pm"},"Template::Plugin::Datafile":{"file":"lib/Template/Plugin/Datafile.pm","version":"3.100"},"Template::Plugin::Date::Manip":{"file":"lib/Template/Plugin/Date.pm","version":"3.100"},"Template::Context":{"file":"lib/Template/Context.pm","version":"3.100"},"Template::Iterator":{"version":"3.100","file":"lib/Template/Iterator.pm"},"Template::VMethods":{"file":"lib/Template/VMethods.pm","version":"3.100"},"Template::Base":{"version":"3.100","file":"lib/Template/Base.pm"},"Template":{"file":"lib/Template.pm","version":3.102},"Template::Monad::Scalar":{"file":"lib/Template/Plugin/Scalar.pm","version":"3.100"},"Template::Plugin::Directory":{"version":"3.100","file":"lib/Template/Plugin/Directory.pm"},"Template::Test":{"file":"lib/Template/Test.pm","version":"3.100"},"Template::Plugin::Wrap":{"file":"lib/Template/Plugin/Wrap.pm","version":"3.100"},"Template::Plugin::Format":{"version":"3.100","file":"lib/Template/Plugin/Format.pm"},"Template::Exception":{"version":"3.100","file":"lib/Template/Exception.pm"},"Template::App::ttree":{"file":"lib/Template/App/ttree.pm","version":2.91},"Template::Stash":{"version":"3.100","file":"lib/Template/Stash.pm"},"Template::View":{"version":"3.100","file":"lib/Template/View.pm"},"Template::Plugin::Dumper":{"file":"lib/Template/Plugin/Dumper.pm","version":"3.100"},"Template::Plugin::String":{"file":"lib/Template/Plugin/String.pm","version":"3.100"},"Template::Namespace::Constants":{"version":"3.100","file":"lib/Template/Namespace/Constants.pm"},"Template::Plugin::Math":{"version":"3.100","file":"lib/Template/Plugin/Math.pm"},"Template::Plugins":{"file":"lib/Template/Plugins.pm","version":"3.100"},"Template::Plugin::Date::Calc":{"version":"3.100","file":"lib/Template/Plugin/Date.pm"},"Template::Plugin::URL":{"version":"3.100","file":"lib/Template/Plugin/URL.pm"},"Template::Stash::Context":{"version":"3.100","file":"lib/Template/Stash/Context.pm"},"Template::Plugin::File":{"version":"3.100","file":"lib/Template/Plugin/File.pm"},"Template::Grammar":{"file":"lib/Template/Grammar.pm","version":"3.100"},"Template::Plugin::Assert":{"file":"lib/Template/Plugin/Assert.pm","version":"3.100"},"Template::Filters":{"version":"3.100","file":"lib/Template/Filters.pm"},"Template::Plugin::Filter":{"version":"3.100","file":"lib/Template/Plugin/Filter.pm"}},"pathname":"T/TO/TODDR/Template-Toolkit-3.102.tar.gz","dist":"Template-Toolkit-3.102","version":3.102,"target":"Template::Constants","name":"Template"}PK!†‡DôôHperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.102/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "comprehensive template processing system", "author" : [ "Andy Wardley " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Template-Toolkit", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "AppConfig" : "1.56", "File::Spec" : "0.8", "File::Temp" : "0.12", "Scalar::Util" : "0" } }, "test" : { "requires" : { "Test::LeakTrace" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/abw/Template2/issues" }, "homepage" : "http://www.template-toolkit.org", "repository" : { "type" : "git", "url" : "https://github.com/abw/Template2.git", "web" : "https://github.com/abw/Template2" } }, "version" : "3.102", "x_serialization_backend" : "JSON::PP version 4.07" } PK!§~‹'ÛÛEperl5/x86_64-linux-thread-multi/.meta/File-Slurp-9999.32/install.jsonnuÏÃ6Ç${"provides":{"File::Slurp":{"version":9999.32,"file":"lib/File/Slurp.pm"}},"target":"File::Slurp","version":9999.32,"name":"File::Slurp","dist":"File-Slurp-9999.32","pathname":"C/CA/CAPOEIRAB/File-Slurp-9999.32.tar.gz"}PK!ŠòF7  Dperl5/x86_64-linux-thread-multi/.meta/File-Slurp-9999.32/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Simple and Efficient Reading/Writing/Modifying of Complete Files", "author" : [ "Uri Guttman " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.44, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "File-Slurp", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "B" : "0", "Carp" : "0", "Errno" : "0", "Exporter" : "5.57", "Fcntl" : "0", "File::Basename" : "0", "File::Spec" : "3.01", "File::Temp" : "0", "IO::Handle" : "0", "POSIX" : "0", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Carp" : "0", "Exporter" : "5.57", "Fcntl" : "0", "File::Basename" : "0", "File::Spec" : "3.01", "File::Temp" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "1.00", "Socket" : "0", "Symbol" : "0", "Test::More" : "0", "overload" : "0", "strict" : "0", "warnings" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/perhunter/slurp.git", "web" : "https://github.com/perhunter/slurp" } }, "version" : "9999.32", "x_contributors" : [ "Aristotle Pagaltzis ", "Chase Whitener ", "Dan Book ", "Graham Knop ", "James E Keenan " ], "x_serialization_backend" : "JSON::PP version 4.04" } PK!ƒ‚:ü±±>perl5/x86_64-linux-thread-multi/.meta/Expect-1.35/install.jsonnuÏÃ6Ç${"provides":{"Expect":{"version":1.35,"file":"lib/Expect.pm"}},"target":"Expect","version":1.35,"name":"Expect","dist":"Expect-1.35","pathname":"J/JA/JACOBY/Expect-1.35.tar.gz"}PK!c LM``=perl5/x86_64-linux-thread-multi/.meta/Expect-1.35/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "automate interactions with command line programs that expose a text terminal interface.", "author" : [ "Austin Schutz ", "Roland Giersig ", "Dave Jacoby " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Expect", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : {} }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.64" } }, "runtime" : { "requires" : { "Carp" : "0", "Errno" : "0", "Exporter" : "0", "Fcntl" : "0", "IO::Handle" : "0", "IO::Pty" : "1.11", "IO::Tty" : "1.11", "POSIX" : "0", "perl" : "5.006000" } }, "test" : { "requires" : { "File::Temp" : "0", "Test::More" : "1.00" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "http://github.com/jacoby/expect.pm.git", "web" : "http://github.com/jacoby/expect.pm" } }, "version" : "1.35", "x_serialization_backend" : "JSON::PP version 2.27400" } PK!“¼ ÚmmAperl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.34/install.jsonnuÏÃ6Ç${"target":"YAML::Syck","dist":"YAML-Syck-1.34","version":1.34,"provides":{"YAML::Dumper::Syck":{"file":"lib/YAML/Dumper/Syck.pm"},"YAML::Syck":{"file":"lib/YAML/Syck.pm","version":1.34},"JSON::Syck":{"version":1.34,"file":"lib/JSON/Syck.pm"},"YAML::Loader::Syck":{"file":"lib/YAML/Loader/Syck.pm"}},"name":"YAML::Syck","pathname":"T/TO/TODDR/YAML-Syck-1.34.tar.gz"}PK!{Œ�+  @perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.34/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Fast, lightweight YAML loader and dumper", "author" : [ "Todd Rinaldo " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.44, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "YAML-Syck", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/YAML-Syck/issues" }, "homepage" : "http://github.com/toddr/YAML-Syck", "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "http://github.com/toddr/YAML-Syck" } }, "version" : "1.34", "x_serialization_backend" : "JSON::PP version 4.04" } PK!’"‡yÿÿCperl5/x86_64-linux-thread-multi/.meta/libwww-perl-6.49/install.jsonnuÏÃ6Ç${"provides":{"LWP::Protocol::ftp":{"version":"6.49","file":"lib/LWP/Protocol/ftp.pm"},"LWP::Protocol::cpan":{"version":"6.49","file":"lib/LWP/Protocol/cpan.pm"},"LWP::Protocol::data":{"version":"6.49","file":"lib/LWP/Protocol/data.pm"},"LWP::Protocol::nogo":{"version":"6.49","file":"lib/LWP/Protocol/nogo.pm"},"LWP::Protocol::nntp":{"version":"6.49","file":"lib/LWP/Protocol/nntp.pm"},"LWP::Simple":{"version":"6.49","file":"lib/LWP/Simple.pm"},"LWP::Protocol::mailto":{"version":"6.49","file":"lib/LWP/Protocol/mailto.pm"},"LWP::Debug::TraceHTTP":{"version":"6.49","file":"lib/LWP/Debug/TraceHTTP.pm"},"LWP::DebugFile":{"version":"6.49","file":"lib/LWP/DebugFile.pm"},"LWP::RobotUA":{"version":"6.49","file":"lib/LWP/RobotUA.pm"},"LWP::ConnCache":{"version":"6.49","file":"lib/LWP/ConnCache.pm"},"LWP::Protocol::gopher":{"version":"6.49","file":"lib/LWP/Protocol/gopher.pm"},"LWP::Protocol::file":{"version":"6.49","file":"lib/LWP/Protocol/file.pm"},"LWP::Authen::Digest":{"version":"6.49","file":"lib/LWP/Authen/Digest.pm"},"LWP::Protocol::http":{"version":"6.49","file":"lib/LWP/Protocol/http.pm"},"LWP::MemberMixin":{"version":"6.49","file":"lib/LWP/MemberMixin.pm"},"LWP::UserAgent":{"version":"6.49","file":"lib/LWP/UserAgent.pm"},"LWP::Protocol::loopback":{"version":"6.49","file":"lib/LWP/Protocol/loopback.pm"},"LWP::Debug":{"x_deprecated":1,"version":"6.49","file":"lib/LWP/Debug.pm"},"LWP::Authen::Ntlm":{"version":"6.49","file":"lib/LWP/Authen/Ntlm.pm"},"LWP::Authen::Basic":{"version":"6.49","file":"lib/LWP/Authen/Basic.pm"},"LWP::Protocol":{"version":"6.49","file":"lib/LWP/Protocol.pm"},"LWP":{"version":"6.49","file":"lib/LWP.pm"}},"target":"LWP::UserAgent","version":"6.49","name":"libwww::perl","dist":"libwww-perl-6.49","pathname":"O/OA/OALDERS/libwww-perl-6.49.tar.gz"}PK!æí¥^†^†Bperl5/x86_64-linux-thread-multi/.meta/libwww-perl-6.49/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "The World-Wide Web library for Perl", "author" : [ "Gisle Aas " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.015, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "libwww-perl", "no_index" : { "directory" : [ "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "CPAN::Meta::Requirements" : "2.120620", "ExtUtils::MakeMaker" : "0", "File::Copy" : "0", "Getopt::Long" : "0", "Module::Metadata" : "0" } }, "develop" : { "recommends" : { "Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007" }, "requires" : { "Authen::NTLM" : "1.02", "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Test::EOL" : "0", "Test::LeakTrace" : "0.16", "Test::MinimumVersion" : "0", "Test::Mojibake" : "0", "Test::More" : "0.94", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1" } }, "runtime" : { "requires" : { "Digest::MD5" : "0", "Encode" : "2.12", "Encode::Locale" : "0", "File::Listing" : "6", "HTML::Entities" : "0", "HTML::HeadParser" : "0", "HTTP::Cookies" : "6", "HTTP::Daemon" : "6", "HTTP::Date" : "6", "HTTP::Negotiate" : "6", "HTTP::Request" : "6", "HTTP::Request::Common" : "6", "HTTP::Response" : "6", "HTTP::Status" : "6.07", "IO::Select" : "0", "IO::Socket" : "0", "LWP::MediaTypes" : "6", "MIME::Base64" : "2.1", "Net::FTP" : "2.58", "Net::HTTP" : "6.18", "Scalar::Util" : "0", "Try::Tiny" : "0", "URI" : "1.10", "URI::Escape" : "0", "WWW::RobotRules" : "6", "base" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" }, "suggests" : { "Authen::NTLM" : "1.02", "Data::Dump" : "1.13", "IO::Socket::INET" : "0", "LWP::Protocol::https" : "6.02" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900", "Test::LeakTrace" : "0" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "FindBin" : "0", "Test::Fatal" : "0", "Test::More" : "0", "Test::Needs" : "0", "Test::RequiresInternet" : "0" } } }, "provides" : { "LWP" : { "file" : "lib/LWP.pm", "version" : "6.49" }, "LWP::Authen::Basic" : { "file" : "lib/LWP/Authen/Basic.pm", "version" : "6.49" }, "LWP::Authen::Digest" : { "file" : "lib/LWP/Authen/Digest.pm", "version" : "6.49" }, "LWP::Authen::Ntlm" : { "file" : "lib/LWP/Authen/Ntlm.pm", "version" : "6.49" }, "LWP::ConnCache" : { "file" : "lib/LWP/ConnCache.pm", "version" : "6.49" }, "LWP::Debug" : { "file" : "lib/LWP/Debug.pm", "version" : "6.49", "x_deprecated" : 1 }, "LWP::Debug::TraceHTTP" : { "file" : "lib/LWP/Debug/TraceHTTP.pm", "version" : "6.49" }, "LWP::DebugFile" : { "file" : "lib/LWP/DebugFile.pm", "version" : "6.49" }, "LWP::MemberMixin" : { "file" : "lib/LWP/MemberMixin.pm", "version" : "6.49" }, "LWP::Protocol" : { "file" : "lib/LWP/Protocol.pm", "version" : "6.49" }, "LWP::Protocol::cpan" : { "file" : "lib/LWP/Protocol/cpan.pm", "version" : "6.49" }, "LWP::Protocol::data" : { "file" : "lib/LWP/Protocol/data.pm", "version" : "6.49" }, "LWP::Protocol::file" : { "file" : "lib/LWP/Protocol/file.pm", "version" : "6.49" }, "LWP::Protocol::ftp" : { "file" : "lib/LWP/Protocol/ftp.pm", "version" : "6.49" }, "LWP::Protocol::gopher" : { "file" : "lib/LWP/Protocol/gopher.pm", "version" : "6.49" }, "LWP::Protocol::http" : { "file" : "lib/LWP/Protocol/http.pm", "version" : "6.49" }, "LWP::Protocol::loopback" : { "file" : "lib/LWP/Protocol/loopback.pm", "version" : "6.49" }, "LWP::Protocol::mailto" : { "file" : "lib/LWP/Protocol/mailto.pm", "version" : "6.49" }, "LWP::Protocol::nntp" : { "file" : "lib/LWP/Protocol/nntp.pm", "version" : "6.49" }, "LWP::Protocol::nogo" : { "file" : "lib/LWP/Protocol/nogo.pm", "version" : "6.49" }, "LWP::RobotUA" : { "file" : "lib/LWP/RobotUA.pm", "version" : "6.49" }, "LWP::Simple" : { "file" : "lib/LWP/Simple.pm", "version" : "6.49" }, "LWP::UserAgent" : { "file" : "lib/LWP/UserAgent.pm", "version" : "6.49" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/libwww-perl/libwww-perl/issues" }, "homepage" : "https://github.com/libwww-perl/libwww-perl", "repository" : { "type" : "git", "url" : "https://github.com/libwww-perl/libwww-perl.git", "web" : "https://github.com/libwww-perl/libwww-perl" }, "x_IRC" : "irc://irc.perl.org/#lwp", "x_MailingList" : "mailto:libwww@perl.org" }, "version" : "6.49", "x_Dist_Zilla" : { "perl" : { "version" : "5.026001" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "LICENSE", "META.json", "README.md" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "Git::GatherDir", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "MetaConfig", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Package", "config" : { "Dist::Zilla::Plugin::MetaProvides::Package" : { "finder_objects" : [ { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.015" } ], "include_underscores" : 0 }, "Dist::Zilla::Role::MetaProvider::Provider" : { "$Dist::Zilla::Role::MetaProvider::Provider::VERSION" : "2.002004", "inherit_missing" : 1, "inherit_version" : 1, "meta_noindex" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.004" } }, "name" : "MetaProvides::Package", "version" : "2.004003" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "MetaNoIndex", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "MetaYAML", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "MetaJSON", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "MetaResources", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Deprecated", "config" : { "Dist::Zilla::Plugin::Deprecated" : { "all" : 0, "modules" : [ "LWP::Debug" ] } }, "name" : "Deprecated", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.28.0", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Authority", "name" : "Authority", "version" : "1.009" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "Manifest", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "License", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.004" } }, "name" : "InstallGuide", "version" : "1.200013" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "ExecDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Prereqs::FromCPANfile", "name" : "Prereqs::FromCPANfile", "version" : "0.08" }, { "class" : "Dist::Zilla::Plugin::DynamicPrereqs", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.004" } }, "name" : "DynamicPrereqs", "version" : "0.037" }, { "class" : "Dist::Zilla::Plugin::MakeMaker::Awesome", "config" : { "Dist::Zilla::Plugin::MakeMaker" : { "make_path" : "make", "version" : "6.015" }, "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4", "version" : "6.015" } }, "name" : "MakeMaker::Awesome", "version" : "0.48" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::Test::Version", "name" : "Test::Version", "version" : "1.09" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "Test::ReportPrereqs", "version" : "0.027" }, { "class" : "Dist::Zilla::Plugin::Test::Compile", "config" : { "Dist::Zilla::Plugin::Test::Compile" : { "bail_out_on_fail" : "1", "fail_on_warning" : "author", "fake_home" : 0, "filename" : "xt/author/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "develop", "script_finder" : [ ":PerlExecFiles" ], "skips" : [], "switch" : [] } }, "name" : "Test::Compile", "version" : "2.058" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "00-compile.t", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "Test::Portability", "version" : "2.001000" }, { "class" : "Dist::Zilla::Plugin::Test::EOL", "config" : { "Dist::Zilla::Plugin::Test::EOL" : { "filename" : "xt/author/eol.t", "finder" : [ ":ExecFiles", ":InstallModules", ":TestFiles" ], "trailing_whitespace" : 1 } }, "name" : "Test::EOL", "version" : "0.19" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "changes_has_content.t", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Test::MinimumVersion", "config" : { "Dist::Zilla::Plugin::Test::MinimumVersion" : { "max_target_perl" : null } }, "name" : "Test::MinimumVersion", "version" : "2.000010" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "PodSyntaxTests", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable", "name" : "Test::Pod::Coverage::Configurable", "version" : "0.07" }, { "class" : "Dist::Zilla::Plugin::Test::PodSpelling", "config" : { "Dist::Zilla::Plugin::Test::PodSpelling" : { "directories" : [ "bin", "lib" ], "spell_cmd" : "aspell list", "stopwords" : [ "Accomazzi", "Alexandre", "Andreas", "Asplund", "Betts", "Bochner", "BooK", "Buenzli", "CGI", "CPAN", "Chamas", "Coppit", "Dalgleish", "Dubois", "Dunkin", "Duret", "Dvornik", "Eldridge", "Gertjan", "Graaff", "Greab", "Guenther", "Gurusamy", "Gustafsson", "Hakanson", "Harald", "Hedlund", "Hoblitt", "Hwa", "INOUE", "Joao", "Joerg", "KONISHI", "Kaminsky", "Kartik", "Katsuhiro", "Kebsch", "Keiichiro", "Kilzer", "Klar", "Koster", "Kronengold", "Krüger", "Kubb", "König", "Laker", "Langfeldt", "Langheinrich", "Liam", "Lindley", "Lotterer", "Lutz", "MacEachern", "Macdonald", "Mailto", "Marko", "Markus", "Martijn", "McCauley", "Melchner", "Moshe", "Murrell", "NNTP", "NTLM", "Nagano", "Newby", "Nicolai", "Nierstrasz", "Olly", "Oosten", "Panchenko", "Pimlott", "Pon", "Quaranta", "Radoslaw", "Radu", "Rai", "Rezic", "RobotUA", "Sarathy", "Schilli", "Schinder", "Shirazi", "Skyttä", "Slaven", "Spafford", "Stosberg", "Subbarao", "TCP", "Takanori", "Thoennes", "Thurn", "Tilly", "UA", "Ugai", "Unger", "UserAgent", "VanHeyningen", "Vandewege", "Ville", "WireShark", "Yee", "Yitzchak", "Yoshinari", "Zajac", "Zakharevich", "Zielinski", "Zoest", "afPuUsSedvhx", "de", "erik", "getprint", "getstore", "peterm", "shildreth" ], "wordlist" : "Pod::Wordlist" } }, "name" : "Test::PodSpelling", "version" : "2.007005" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." } }, "name" : "Git::Check", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::CheckStrictVersion", "name" : "CheckStrictVersion", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4" } }, "name" : "RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::CheckChangeLog", "name" : "CheckChangeLog", "version" : "0.05" }, { "class" : "Dist::Zilla::Plugin::CheckChangesHasContent", "name" : "CheckChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "TestRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "UploadToCPAN", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "Markdown_Readme", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "LICENSE", "META.json" ], "match" : [] } }, "name" : "CopyFilesFromRelease", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Git::VersionManager/pluginbundle version", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Git::VersionManager/CopyFilesFromRelease", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "LICENSE", "META.json", "README.md" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git::VersionManager/release snapshot", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v6.49", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git::VersionManager/Git::Tag", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Git::VersionManager/NextRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git::VersionManager/post-release commit", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." } }, "name" : "Git::Push", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "ConfirmRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.015" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.015" } }, "x_authority" : "cpan:LWWWP", "x_contributors" : [ "Adam Kennedy ", "Adam Sjogren ", "Alexey Tourbin ", "Alex Kapranoff ", "amire80 ", "Andreas J. Koenig ", "Andrew Grangaard ", "Anirvan Chatterjee ", "BGMNT ", "Bill Mann ", "Bron Gondwana ", "Bryan Cardillo ", "Chase Whitener ", "Christopher J. Madsen ", "Colin Newell ", "Daina Pettit ", "Daniel Hedlund ", "David E. Wheeler ", "DAVIDRW ", "David Standish ", "David Steinbrunner ", "Desmond Daignault ", "Doug Bell ", "Fabian Zeindler ", "Father Chrysostomos ", "Frank Maas ", "FWILES ", "Galen Huntington ", "Gavin Peters ", "Gerhard Poul ", "Gianni Ceccarelli ", "Gisle Aas ", "Graeme Thompson ", "Graham Knop ", "Gregory Oschwald ", "Hans-H. Froehlich ", "Ian Kilgore ", "Jacob J ", "Jakub Wilk ", "James Raspass ", "Jason A Fesler ", "jefflee ", "Jeremy Mates ", "Joe Atzberger ", "john9art ", "John Wittkoski ", "Jonathan Dahan ", "Julien Fiegehenn ", "Karen Etheridge ", "Katarina Durechova ", "leedo ", "Mark Fowler ", "Mark Stosberg ", "Martin H. Sluka ", "Matthew Horsfall ", "michael gong ", "Michael G. Schwern ", "Michiel Beijen ", "Mike Schilli ", "Moritz Onken ", "murphy ", "Naveed Massjouni ", "Nigel Gregoire ", "Nik LaBelle ", "Niko Tyni ", "Olaf Alders ", "Ondrej Hanak ", "Patrik Lundin ", "Peter Rabbitson ", "phrstbrn ", "Piotr Roszatycki ", "Robert Stone ", "Rolf Grossmann ", "Roman Galeev ", "ruff ", "sasao ", "Sean M. Burke ", "Sebastian Paaske Tørholm ", "Sergey Romanov ", "Shoichi Kaji ", "Slaven Rezic ", "Spiros Denaxas ", "Steffen Ullrich ", "Steve Hay ", "Takumi Akiyama ", "Theodore Robert Campbell Jr ", "Theo van Hoesel ", "Tim Couzins ", "Todd Lipcon ", "Tomasz Konojacki ", "Tom Hukins ", "Tony Finch ", "Toru Yamaguchi ", "turugina ", "uid39246 ", "Ville Skyttä ", "Vyacheslav Matyukhin ", "Yuri Karaban ", "Yury Zavarin ", "Zefram " ], "x_generated_by_perl" : "v5.26.1", "x_serialization_backend" : "Cpanel::JSON::XS version 4.04", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } PK!Bg ±±>perl5/x86_64-linux-thread-multi/.meta/Expect-1.38/install.jsonnuÏÃ6Ç${"provides":{"Expect":{"version":1.38,"file":"lib/Expect.pm"}},"pathname":"J/JA/JACOBY/Expect-1.38.tar.gz","name":"Expect","version":1.38,"dist":"Expect-1.38","target":"Expect"}PK!veÌ0]]=perl5/x86_64-linux-thread-multi/.meta/Expect-1.38/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "automate interactions with command line programs that expose a text terminal interface.", "author" : [ "Austin Schutz ", "Roland Giersig ", "Dave Jacoby " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.62, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Expect", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : {} }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.64" } }, "runtime" : { "requires" : { "Carp" : "0", "Errno" : "0", "Exporter" : "0", "Fcntl" : "0", "IO::Handle" : "0", "IO::Pty" : "1.11", "IO::Tty" : "1.11", "POSIX" : "0", "perl" : "5.006000" } }, "test" : { "requires" : { "File::Temp" : "0", "Test::More" : "1.00" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "http://github.com/jacoby/expect.pm.git", "web" : "http://github.com/jacoby/expect.pm" } }, "version" : "1.38", "x_serialization_backend" : "JSON::PP version 4.06" } PK!ëjŠ!óóCperl5/x86_64-linux-thread-multi/.meta/Alien-Build-2.33/install.jsonnuÏÃ6Ç${"provides":{"Alien::Build::Plugin::Core::Setup":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/Setup.pm"},"Alien::Build::Plugin::Extract::ArchiveZip":{"version":2.33,"file":"lib/Alien/Build/Plugin/Extract/ArchiveZip.pm"},"Alien::Build::Plugin::Core::Tail":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/Tail.pm"},"Alien::Build::Plugin::Fetch::CurlCommand":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/CurlCommand.pm"},"Alien::Build::Plugin::Decode::DirListing":{"version":2.33,"file":"lib/Alien/Build/Plugin/Decode/DirListing.pm"},"Alien::Build::Plugin::Build::MSYS":{"version":2.33,"file":"lib/Alien/Build/Plugin/Build/MSYS.pm"},"Test::Alien":{"version":2.33,"file":"lib/Test/Alien.pm"},"Alien::Build::Interpolate":{"version":2.33,"file":"lib/Alien/Build/Interpolate.pm"},"Alien::Build::Plugin::Extract::Negotiate":{"version":2.33,"file":"lib/Alien/Build/Plugin/Extract/Negotiate.pm"},"Alien::Build::Meta":{"version":2.33,"file":"lib/Alien/Build.pm"},"Alien::Build::Plugin::PkgConfig::LibPkgConf":{"version":2.33,"file":"lib/Alien/Build/Plugin/PkgConfig/LibPkgConf.pm"},"Alien::Build::Plugin::Gather::IsolateDynamic":{"version":2.33,"file":"lib/Alien/Build/Plugin/Gather/IsolateDynamic.pm"},"Test::Alien::Build":{"version":2.33,"file":"lib/Test/Alien/Build.pm"},"Alien::Build::Plugin::Probe::CBuilder":{"version":2.33,"file":"lib/Alien/Build/Plugin/Probe/CBuilder.pm"},"Alien::Build::Interpolate::Default":{"version":2.33,"file":"lib/Alien/Build/Interpolate/Default.pm"},"Alien::Build::Plugin::Fetch::LocalDir":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/LocalDir.pm"},"Alien::Build::Plugin::Probe::CommandLine":{"version":2.33,"file":"lib/Alien/Build/Plugin/Probe/CommandLine.pm"},"Alien::Build::Plugin::PkgConfig::PP":{"version":2.33,"file":"lib/Alien/Build/Plugin/PkgConfig/PP.pm"},"Alien::Build::Plugin::PkgConfig::Negotiate":{"version":2.33,"file":"lib/Alien/Build/Plugin/PkgConfig/Negotiate.pm"},"Alien::Build::MM":{"version":2.33,"file":"lib/Alien/Build/MM.pm"},"Alien::Build::Plugin::Core::Download":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/Download.pm"},"Alien::Build::TempDir":{"version":2.33,"file":"lib/Alien/Build.pm"},"Alien::Build::Plugin::PkgConfig::CommandLine":{"version":2.33,"file":"lib/Alien/Build/Plugin/PkgConfig/CommandLine.pm"},"Alien::Base::Wrapper":{"version":2.33,"file":"lib/Alien/Base/Wrapper.pm"},"Test::Alien::Synthetic":{"version":2.33,"file":"lib/Test/Alien/Synthetic.pm"},"Alien::Build::Helper":{"version":2.33,"file":"lib/Alien/Build/Interpolate.pm"},"Alien::Build::Interpolate::Helper":{"version":2.33,"file":"lib/Alien/Build/Interpolate.pm"},"Alien::Build":{"version":2.33,"file":"lib/Alien/Build.pm"},"Alien::Build::PluginMeta":{"version":2.33,"file":"lib/Alien/Build/Plugin.pm"},"Alien::Build::Plugin::Prefer::GoodVersion":{"version":2.33,"file":"lib/Alien/Build/Plugin/Prefer/GoodVersion.pm"},"Alien::Build::Plugin::Extract::CommandLine":{"version":2.33,"file":"lib/Alien/Build/Plugin/Extract/CommandLine.pm"},"Alien::Build::Plugin::Core::CleanInstall":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/CleanInstall.pm"},"Alien::Build::rc":{"version":2.33,"file":"lib/Alien/Build.pm"},"Alien::Build::Plugin":{"version":2.33,"file":"lib/Alien/Build/Plugin.pm"},"alienfile":{"version":2.33,"file":"lib/alienfile.pm"},"Alien::Build::Plugin::Fetch::LWP":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/LWP.pm"},"Alien::Base::PkgConfig":{"version":2.33,"file":"lib/Alien/Base/PkgConfig.pm"},"Alien::Base":{"version":2.33,"file":"lib/Alien/Base.pm"},"Alien::Build::Temp":{"version":2.33,"file":"lib/Alien/Build/Temp.pm"},"Test::Alien::CanPlatypus":{"version":2.33,"file":"lib/Test/Alien/CanPlatypus.pm"},"Alien::Build::Plugin::Decode::DirListingFtpcopy":{"version":2.33,"file":"lib/Alien/Build/Plugin/Decode/DirListingFtpcopy.pm"},"Alien::Build::Plugin::Test::Mock":{"version":2.33,"file":"lib/Alien/Build/Plugin/Test/Mock.pm"},"Alien::Build::Plugin::Decode::HTML":{"version":2.33,"file":"lib/Alien/Build/Plugin/Decode/HTML.pm"},"Alien::Build::Version::Basic":{"version":2.33,"file":"lib/Alien/Build/Version/Basic.pm"},"Alien::Build::Plugin::Decode::Mojo":{"version":2.33,"file":"lib/Alien/Build/Plugin/Decode/Mojo.pm"},"Alien::Build::Plugin::Fetch::NetFTP":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/NetFTP.pm"},"Alien::Build::Plugin::Core::Gather":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/Gather.pm"},"Alien::Build::Plugin::Build::CMake":{"version":2.33,"file":"lib/Alien/Build/Plugin/Build/CMake.pm"},"Alien::Build::Plugin::Prefer::SortVersions":{"version":2.33,"file":"lib/Alien/Build/Plugin/Prefer/SortVersions.pm"},"Alien::Build::Plugin::Core::Override":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/Override.pm"},"Alien::Build::Plugin::Build::SearchDep":{"version":2.33,"file":"lib/Alien/Build/Plugin/Build/SearchDep.pm"},"Alien::Role":{"version":2.33,"file":"lib/Alien/Role.pm"},"Alien::Build::Log::Abbreviate":{"version":2.33,"file":"lib/Alien/Build/Log/Abbreviate.pm"},"Alien::Build::Plugin::Core::FFI":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/FFI.pm"},"Test::Alien::CanCompile":{"version":2.33,"file":"lib/Test/Alien/CanCompile.pm"},"Alien::Build::Log":{"version":2.33,"file":"lib/Alien/Build/Log.pm"},"Alien::Build::Plugin::Prefer::BadVersion":{"version":2.33,"file":"lib/Alien/Build/Plugin/Prefer/BadVersion.pm"},"Alien::Build::Plugin::Core::Legacy":{"version":2.33,"file":"lib/Alien/Build/Plugin/Core/Legacy.pm"},"Alien::Build::Log::Default":{"version":2.33,"file":"lib/Alien/Build/Log/Default.pm"},"Test::Alien::Diag":{"version":2.33,"file":"lib/Test/Alien/Diag.pm"},"Alien::Build::Plugin::Probe::Vcpkg":{"version":2.33,"file":"lib/Alien/Build/Plugin/Probe/Vcpkg.pm"},"Alien::Build::CommandSequence":{"version":2.33,"file":"lib/Alien/Build/CommandSequence.pm"},"Alien::Build::Plugin::Build::Make":{"version":2.33,"file":"lib/Alien/Build/Plugin/Build/Make.pm"},"Alien::Build::Plugin::Fetch::Wget":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/Wget.pm"},"Alien::Build::Plugin::PkgConfig::MakeStatic":{"version":2.33,"file":"lib/Alien/Build/Plugin/PkgConfig/MakeStatic.pm"},"Alien::Build::Plugin::Build::Autoconf":{"version":2.33,"file":"lib/Alien/Build/Plugin/Build/Autoconf.pm"},"Test::Alien::Run":{"version":2.33,"file":"lib/Test/Alien/Run.pm"},"Alien::Build::Util":{"version":2.33,"file":"lib/Alien/Build/Util.pm"},"Alien::Build::Plugin::Build::Copy":{"version":2.33,"file":"lib/Alien/Build/Plugin/Build/Copy.pm"},"Alien::Build::Plugin::Fetch::Local":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/Local.pm"},"Alien::Build::Plugin::Extract::Directory":{"version":2.33,"file":"lib/Alien/Build/Plugin/Extract/Directory.pm"},"Alien::Build::Plugin::Download::Negotiate":{"version":2.33,"file":"lib/Alien/Build/Plugin/Download/Negotiate.pm"},"Alien::Build::Plugin::Fetch::HTTPTiny":{"version":2.33,"file":"lib/Alien/Build/Plugin/Fetch/HTTPTiny.pm"},"Alien::Build::Plugin::Extract::ArchiveTar":{"version":2.33,"file":"lib/Alien/Build/Plugin/Extract/ArchiveTar.pm"}},"target":"Alien::Base::Wrapper","version":2.33,"name":"Alien::Build","dist":"Alien-Build-2.33","pathname":"P/PL/PLICEASE/Alien-Build-2.33.tar.gz"}PK! XÙm½½Bperl5/x86_64-linux-thread-multi/.meta/Alien-Build-2.33/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Build external dependencies for use in CPAN", "author" : [ "Graham Ollis ", "Joel Berger " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.015, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Alien-Build", "no_index" : { "directory" : [ "corpus", "example", "maint" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "6.64" } }, "configure" : { "requires" : { "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.64", "ExtUtils::ParseXS" : "3.30", "File::Which" : "0" } }, "develop" : { "requires" : { "FindBin" : "0", "Perl::Critic" : "0", "Test2::Require::Module" : "0.000060", "Test2::Tools::PerlCritic" : "0", "Test2::V0" : "0.000060", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.98", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Spelling" : "0", "Test::Strict" : "0" } }, "runtime" : { "requires" : { "Capture::Tiny" : "0.17", "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.64", "ExtUtils::ParseXS" : "3.30", "FFI::CheckLib" : "0.11", "File::Which" : "1.10", "File::chdir" : "0", "JSON::PP" : "0", "List::Util" : "1.33", "Path::Tiny" : "0.077", "Test2::API" : "1.302096", "Text::ParseWords" : "3.26", "perl" : "5.008004" }, "suggests" : { "Archive::Tar" : "0" } }, "test" : { "requires" : { "Test2::API" : "1.302096", "Test2::V0" : "0.000060" }, "suggests" : { "Devel::Hide" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/PerlAlien/Alien-Build/issues" }, "homepage" : "https://metacpan.org/pod/Alien::Build", "repository" : { "type" : "git", "url" : "git://github.com/PerlAlien/Alien-Build.git", "web" : "https://github.com/PerlAlien/Alien-Build" }, "x_IRC" : "irc://irc.perl.org/#native" }, "version" : "2.33", "x_contributors" : [ "Graham Ollis ", "Diab Jerius (DJERIUS)", "Roy Storey (KIWIROY)", "Ilya Pavlov", "David Mertens (run4flat)", "Mark Nunberg (mordy, mnunberg)", "Christian Walde (Mithaldu)", "Brian Wightman (MidLifeXis)", "Zaki Mughal (zmughal)", "mohawk (mohawk2, ETJ)", "Vikas N Kumar (vikasnkumar)", "Flavio Poletti (polettix)", "Salvador Fandiño (salva)", "Gianni Ceccarelli (dakkar)", "Pavel Shaydo (zwon, trinitum)", "Kang-min Liu (劉康民, gugod)", "Nicholas Shipp (nshp)", "Juan Julián Merelo Guervós (JJ)", "Joel Berger (JBERGER)", "Petr Pisar (ppisar)", "Lance Wicks (LANCEW)", "Ahmad Fatoum (a3f, ATHREEF)", "José Joaquín Atria (JJATRIA)", "Duke Leto (LETO)", "Shoichi Kaji (SKAJI)", "Shawn Laffan (SLAFFAN)", "Paul Evans (leonerd, PEVANS)", "HÃ¥kon Hægland (hakonhagland, HAKONH)" ], "x_generated_by_perl" : "v5.32.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.19", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_use_unsafe_inc" : 0 } PK!�:ßc c Dperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0206/install.jsonnuÏÃ6Ç${"provides":{"XML::LibXML::PI":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Pattern":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::SAX":{"version":2.0206,"file":"lib/XML/LibXML/SAX.pm"},"XML::LibXML::XPathContext":{"version":2.0206,"file":"lib/XML/LibXML/XPathContext.pm"},"XML::LibXML::SAX::AttributeNode":{"version":2.0206,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::SAX::Generator":{"version":2.0206,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::XPathExpression":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::NodeList":{"version":2.0206,"file":"lib/XML/LibXML/NodeList.pm"},"XML::LibXML::Error":{"version":2.0206,"file":"lib/XML/LibXML/Error.pm"},"XML::LibXML::RegExp":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::_SAXParser":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::InputCallback":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Devel":{"version":2.0206,"file":"lib/XML/LibXML/Devel.pm"},"XML::LibXML::Boolean":{"version":2.0206,"file":"lib/XML/LibXML/Boolean.pm"},"XML::LibXML::AttributeHash":{"version":2.0206,"file":"lib/XML/LibXML/AttributeHash.pm"},"XML::LibXML":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Literal":{"version":2.0206,"file":"lib/XML/LibXML/Literal.pm"},"XML::LibXML::Reader":{"version":2.0206,"file":"lib/XML/LibXML/Reader.pm"},"XML::LibXML::SAX::Builder":{"version":2.0206,"file":"lib/XML/LibXML/SAX/Builder.pm"},"XML::LibXML::Schema":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Element":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Attr":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Node":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::CDATASection":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Number":{"version":2.0206,"file":"lib/XML/LibXML/Number.pm"},"XML::LibXML::Namespace":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::ErrNo":{"version":2.0206,"file":"lib/XML/LibXML/ErrNo.pm"},"XML::LibXML::SAX::Parser":{"version":2.0206,"file":"lib/XML/LibXML/SAX/Parser.pm"},"XML::LibXML::Dtd":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::NamedNodeMap":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Common":{"version":2.0206,"file":"lib/XML/LibXML/Common.pm"},"XML::LibXML::Comment":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Document":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::DocumentFragment":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::RelaxNG":{"version":2.0206,"file":"LibXML.pm"},"XML::LibXML::Text":{"version":2.0206,"file":"LibXML.pm"}},"target":"XML::LibXML","version":2.0206,"name":"XML::LibXML","dist":"XML-LibXML-2.0206","pathname":"S/SH/SHLOMIF/XML-LibXML-2.0206.tar.gz"}PK!CP°µÛ Û Cperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0206/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Interface to Gnome libxml2 xml parsing and DOM library", "author" : [ "Petr Pajas " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.44, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "dom", "html", "libxml", "object oriented", "oop", "parse", "parser", "parsing", "pullparser", "sax", "sgml", "xml", "xpath", "XPath", "xs" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-LibXML", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Alien::Base::Wrapper" : "0", "Alien::Libxml2" : "0.14", "Config" : "0", "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "DynaLoader" : "0", "Encode" : "0", "Exporter" : "5.57", "IO::Handle" : "0", "Scalar::Util" : "0", "Tie::Hash" : "0", "XML::NamespaceSupport" : "1.07", "XML::SAX" : "0.11", "XML::SAX::Base" : "0", "XML::SAX::DocumentLocator" : "0", "XML::SAX::Exception" : "0", "base" : "0", "constant" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "vars" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Config" : "0", "Errno" : "0", "IO::File" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "0", "Test::More" : "0", "locale" : "0", "utf8" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/shlomif/perl-XML-LibXML.git", "web" : "https://github.com/shlomif/perl-XML-LibXML" } }, "version" : "2.0206", "x_serialization_backend" : "JSON::PP version 4.04" } PK!|ùF�€€Operl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.143/install.jsonnuÏÃ6Ç${"version":"2.143","pathname":"R/RJ/RJBS/CPAN-Meta-Requirements-2.143.tar.gz","provides":{"CPAN::Meta::Requirements::Range":{"version":"2.143","file":"lib/CPAN/Meta/Requirements/Range.pm"},"CPAN::Meta::Requirements":{"file":"lib/CPAN/Meta/Requirements.pm","version":"2.143"}},"name":"CPAN::Meta::Requirements","target":"CPAN::Meta::Requirements","dist":"CPAN-Meta-Requirements-2.143"}PK!s*¹ó­­Nperl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.143/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "a set of version requirements for a CPAN dist", "author" : [ "David Golden ", "Ricardo Signes " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.030, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "CPAN-Meta-Requirements", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::Authority" : "0", "Dist::Zilla::Plugin::AutoPrereqs" : "0", "Dist::Zilla::Plugin::BumpVersionAfterRelease" : "0", "Dist::Zilla::Plugin::CPANFile" : "0", "Dist::Zilla::Plugin::CheckChangesHasContent" : "0", "Dist::Zilla::Plugin::CheckMetaResources" : "0", "Dist::Zilla::Plugin::CheckPrereqsIndexed" : "0", "Dist::Zilla::Plugin::ConfirmRelease" : "0", "Dist::Zilla::Plugin::CopyFilesFromBuild::Filtered" : "0", "Dist::Zilla::Plugin::ExecDir" : "0", "Dist::Zilla::Plugin::Git::Check" : "0", "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch" : "0", "Dist::Zilla::Plugin::Git::Commit" : "0", "Dist::Zilla::Plugin::Git::Contributors" : "0", "Dist::Zilla::Plugin::Git::GatherDir" : "0", "Dist::Zilla::Plugin::Git::Push" : "0", "Dist::Zilla::Plugin::Git::Tag" : "0", "Dist::Zilla::Plugin::GithubMeta" : "0", "Dist::Zilla::Plugin::InsertCopyright" : "0", "Dist::Zilla::Plugin::License" : "0", "Dist::Zilla::Plugin::MakeMaker" : "0", "Dist::Zilla::Plugin::MakeMaker::Highlander" : "0.003", "Dist::Zilla::Plugin::Manifest" : "0", "Dist::Zilla::Plugin::ManifestSkip" : "0", "Dist::Zilla::Plugin::MetaJSON" : "0", "Dist::Zilla::Plugin::MetaNoIndex" : "0", "Dist::Zilla::Plugin::MetaProvides::Package" : "0", "Dist::Zilla::Plugin::MetaTests" : "0", "Dist::Zilla::Plugin::MetaYAML" : "0", "Dist::Zilla::Plugin::MinimumPerl" : "0", "Dist::Zilla::Plugin::NextRelease" : "0", "Dist::Zilla::Plugin::OnlyCorePrereqs" : "0.014", "Dist::Zilla::Plugin::Pod2Readme" : "0", "Dist::Zilla::Plugin::PodCoverageTests" : "0", "Dist::Zilla::Plugin::PodSyntaxTests" : "0", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::Prereqs::AuthorDeps" : "0", "Dist::Zilla::Plugin::PromptIfStale" : "0", "Dist::Zilla::Plugin::PruneCruft" : "0", "Dist::Zilla::Plugin::RewriteVersion" : "0", "Dist::Zilla::Plugin::RunExtraTests" : "0", "Dist::Zilla::Plugin::ShareDir" : "0", "Dist::Zilla::Plugin::SurgicalPodWeaver" : "0", "Dist::Zilla::Plugin::Test::Compile" : "0", "Dist::Zilla::Plugin::Test::MinimumVersion" : "0", "Dist::Zilla::Plugin::Test::Perl::Critic" : "0", "Dist::Zilla::Plugin::Test::PodSpelling" : "0", "Dist::Zilla::Plugin::Test::Portability" : "0", "Dist::Zilla::Plugin::Test::ReportPrereqs" : "0", "Dist::Zilla::Plugin::Test::Version" : "0", "Dist::Zilla::Plugin::TestRelease" : "0", "Dist::Zilla::Plugin::UploadToCPAN" : "0", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Weaver::PluginBundle::DAGOLDEN" : "0", "Pod::Wordlist" : "0", "Software::License::Perl_5" : "0", "Test::CPAN::Meta" : "0", "Test::MinimumVersion" : "0", "Test::More" : "0", "Test::Perl::Critic" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1" } }, "runtime" : { "requires" : { "B" : "0", "Carp" : "0", "perl" : "5.010000", "strict" : "0", "version" : "0.88", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::More" : "0.88", "version" : "0.88" } } }, "provides" : { "CPAN::Meta::Requirements" : { "file" : "lib/CPAN/Meta/Requirements.pm", "version" : "2.143" }, "CPAN::Meta::Requirements::Range" : { "file" : "lib/CPAN/Meta/Requirements/Range.pm", "version" : "2.143" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements/issues" }, "homepage" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements", "repository" : { "type" : "git", "url" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements.git", "web" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements" } }, "version" : "2.143", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Ed J ", "Graham Knop ", "Karen Etheridge ", "Leon Timmermans ", "Paul Howarth ", "Ricardo Signes ", "robario ", "Tatsuhiko Miyagawa ", "Tatsuhiko Miyagawa " ], "x_generated_by_perl" : "v5.37.10", "x_serialization_backend" : "Cpanel::JSON::XS version 4.36", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } PK!5)ÀÏÏDperl5/x86_64-linux-thread-multi/.meta/Data-Dumper-2.173/install.jsonnuÏÃ6Ç${"provides":{"Data::Dumper":{"version":2.173,"file":"Dumper.pm"}},"target":"Data::Dumper","version":2.173,"name":"Data::Dumper","dist":"Data-Dumper-2.173","pathname":"X/XS/XSAWYERX/Data-Dumper-2.173.tar.gz"}PK!¬ßQÛ‡‡Cperl5/x86_64-linux-thread-multi/.meta/Data-Dumper-2.173/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "stringified perl data structures, suitable for both printing and C", "author" : [ "unknown" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Data-Dumper", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } } }, "release_status" : "stable", "version" : "2.173", "x_serialization_backend" : "JSON::PP version 2.27400_02" } PK!E—kc c Dperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0208/install.jsonnuÏÃ6Ç${"provides":{"XML::LibXML::PI":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Pattern":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::SAX":{"version":2.0208,"file":"lib/XML/LibXML/SAX.pm"},"XML::LibXML::XPathContext":{"version":2.0208,"file":"lib/XML/LibXML/XPathContext.pm"},"XML::LibXML::SAX::AttributeNode":{"version":2.0208,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::SAX::Generator":{"version":2.0208,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::XPathExpression":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::NodeList":{"version":2.0208,"file":"lib/XML/LibXML/NodeList.pm"},"XML::LibXML::Error":{"version":2.0208,"file":"lib/XML/LibXML/Error.pm"},"XML::LibXML::RegExp":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::_SAXParser":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::InputCallback":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Devel":{"version":2.0208,"file":"lib/XML/LibXML/Devel.pm"},"XML::LibXML::Boolean":{"version":2.0208,"file":"lib/XML/LibXML/Boolean.pm"},"XML::LibXML::AttributeHash":{"version":2.0208,"file":"lib/XML/LibXML/AttributeHash.pm"},"XML::LibXML":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Literal":{"version":2.0208,"file":"lib/XML/LibXML/Literal.pm"},"XML::LibXML::Reader":{"version":2.0208,"file":"lib/XML/LibXML/Reader.pm"},"XML::LibXML::SAX::Builder":{"version":2.0208,"file":"lib/XML/LibXML/SAX/Builder.pm"},"XML::LibXML::Schema":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Element":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Attr":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Node":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::CDATASection":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Number":{"version":2.0208,"file":"lib/XML/LibXML/Number.pm"},"XML::LibXML::Namespace":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::ErrNo":{"version":2.0208,"file":"lib/XML/LibXML/ErrNo.pm"},"XML::LibXML::SAX::Parser":{"version":2.0208,"file":"lib/XML/LibXML/SAX/Parser.pm"},"XML::LibXML::Dtd":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::NamedNodeMap":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Common":{"version":2.0208,"file":"lib/XML/LibXML/Common.pm"},"XML::LibXML::Comment":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Document":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::DocumentFragment":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::RelaxNG":{"version":2.0208,"file":"LibXML.pm"},"XML::LibXML::Text":{"version":2.0208,"file":"LibXML.pm"}},"target":"XML::LibXML","version":2.0208,"name":"XML::LibXML","dist":"XML-LibXML-2.0208","pathname":"S/SH/SHLOMIF/XML-LibXML-2.0208.tar.gz"}PK!SEXAÛ Û Cperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0208/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Interface to Gnome libxml2 xml parsing and DOM library", "author" : [ "Petr Pajas " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "dom", "html", "libxml", "object oriented", "oop", "parse", "parser", "parsing", "pullparser", "sax", "sgml", "xml", "xpath", "XPath", "xs" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-LibXML", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Alien::Base::Wrapper" : "0", "Alien::Libxml2" : "0.14", "Config" : "0", "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "DynaLoader" : "0", "Encode" : "0", "Exporter" : "5.57", "IO::Handle" : "0", "Scalar::Util" : "0", "Tie::Hash" : "0", "XML::NamespaceSupport" : "1.07", "XML::SAX" : "0.11", "XML::SAX::Base" : "0", "XML::SAX::DocumentLocator" : "0", "XML::SAX::Exception" : "0", "base" : "0", "constant" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "vars" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Config" : "0", "Errno" : "0", "IO::File" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "0", "Test::More" : "0", "locale" : "0", "utf8" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/shlomif/perl-XML-LibXML.git", "web" : "https://github.com/shlomif/perl-XML-LibXML" } }, "version" : "2.0208", "x_serialization_backend" : "JSON::PP version 4.06" } PK!¨Ò¥K††>perl5/x86_64-linux-thread-multi/.meta/Encode-3.07/install.jsonnuÏÃ6Ç${"provides":{"Encode::utf8":{"version":3.07,"file":"Encode.pm"},"Encode":{"version":3.07,"file":"Encode.pm"},"Encode::Config":{"version":2.05,"file":"lib/Encode/Config.pm"},"Encode::JP::H2Z":{"version":2.02,"file":"lib/Encode/JP/H2Z.pm"},"Encode::Byte":{"version":2.04,"file":"Byte/Byte.pm"},"Encode::CN::HZ":{"version":"2.10","file":"lib/Encode/CN/HZ.pm"},"Encode::KR::2022_KR":{"version":2.04,"file":"lib/Encode/KR/2022_KR.pm"},"encoding":{"version":"3.00","file":"encoding.pm"},"Encode::UTF_EBCDIC":{"version":3.07,"file":"Encode.pm"},"Encode::MIME::Name":{"version":1.03,"file":"lib/Encode/MIME/Name.pm"},"Encode::XS":{"version":3.07,"file":"Encode.pm"},"Encode::EBCDIC":{"version":2.02,"file":"EBCDIC/EBCDIC.pm"},"Encode::GSM0338":{"version":2.08,"file":"lib/Encode/GSM0338.pm"},"Encode::JP":{"version":2.04,"file":"JP/JP.pm"},"Encode::TW":{"version":2.03,"file":"TW/TW.pm"},"Encode::KR":{"version":2.03,"file":"KR/KR.pm"},"Encode::Symbol":{"version":2.02,"file":"Symbol/Symbol.pm"},"Encode::CN":{"version":2.03,"file":"CN/CN.pm"},"Encode::Unicode::UTF7":{"version":"2.10","file":"lib/Encode/Unicode/UTF7.pm"},"Encode::Unicode":{"version":2.18,"file":"Unicode/Unicode.pm"},"Encode::MIME::Header":{"version":2.28,"file":"lib/Encode/MIME/Header.pm"},"Encode::JP::JIS7":{"version":2.08,"file":"lib/Encode/JP/JIS7.pm"},"Encode::Encoding":{"version":2.08,"file":"lib/Encode/Encoding.pm"},"Encode::Encoder":{"version":2.03,"file":"lib/Encode/Encoder.pm"},"Encode::MIME::Header::ISO_2022_JP":{"version":1.09,"file":"lib/Encode/MIME/Header/ISO_2022_JP.pm"},"Encode::Internal":{"version":3.07,"file":"Encode.pm"},"Encode::Alias":{"version":2.24,"file":"lib/Encode/Alias.pm"},"Encode::CJKConstants":{"version":2.02,"file":"lib/Encode/CJKConstants.pm"},"Encode::Guess":{"version":2.08,"file":"lib/Encode/Guess.pm"}},"target":"Encode","version":3.07,"name":"Encode","dist":"Encode-3.07","pathname":"D/DA/DANKOGAI/Encode-3.07.tar.gz"}PK!T£;;=perl5/x86_64-linux-thread-multi/.meta/Encode-3.07/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "character encodings in Perl", "author" : [ "Dan Kogai " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.44, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Encode", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Exporter" : "5.57", "Storable" : "0", "parent" : "0.221" } }, "test" : { "requires" : { "Test::More" : "0.81_01" } } }, "release_status" : "stable", "resources" : { "repository" : { "url" : "https://github.com/dankogai/p5-encode" } }, "version" : "3.07", "x_contributors" : [ "Alex Davies ", "Alex Kapranoff ", "Alex Vandiver ", "Andreas J. Koenig ", "Andrew Pennebaker ", "Andy Grundman ", "Anton Tagunov ", "Autrijus Tang ", "Benjamin Goldberg ", "Bjoern Hoehrmann ", "Bjoern Jacke ", "bulk88 ", "Craig A. Berry ", "Curtis Jewell ", "Dan Kogai ", "Dave Evans ", "David Golden ", "David Steinbrunner ", "Deng Liu ", "Dominic Dunlop ", "drry", "Elizabeth Mattijsen ", "Flavio Poletti ", "Gerrit P. Haase ", "Gisle Aas ", "Graham Barr ", "Graham Knop ", "Graham Ollis ", "Gurusamy Sarathy ", "H.Merijn Brand ", "Hugo van der Sanden ", "chansen ", "Chris Nandor ", "Inaba Hiroto ", "Jarkko Hietaniemi ", "Jesse Vincent ", "Jungshik Shin ", "Karen Etheridge ", "Karl Williamson ", "Kenichi Ishigaki ", "KONNO Hiroharu ", "Laszlo Molnar ", "Makamaka ", "Mark-Jason Dominus ", "Masahiro Iuchi ", "MATSUNO Tokuhiro ", "Mattia Barbon ", "Michael G Schwern ", "Michael LaGrasta ", "Miron Cuperman ", "Moritz Lenz ", "MORIYAMA Masayuki ", "Nick Ing-Simmons ", "Nicholas Clark ", "Olivier Mengué ", "otsune", "Pali ", "Paul Marquess ", "Peter Prymmer ", "Peter Rabbitson ", "Philip Newton ", "Piotr Fusik ", "Rafael Garcia-Suarez ", "Randy Stauner ", "Reini Urban ", "Robin Barker ", "SADAHIRO Tomoyuki ", "Simon Cozens ", "Slaven Rezic ", "Spider Boardman ", "Steve Hay ", "Steve Peters ", "SUGAWARA Hajime ", "SUZUKI Norio ", "szr8 ", "Tatsuhiko Miyagawa ", "Tels ", "Tony Cook ", "Vadim Konovalov ", "Victor ", "Ville Skyttä ", "Vincent van Dam ", "Yitzchak Scott-Thoennes " ], "x_serialization_backend" : "JSON::PP version 4.04" } PK!îÜå6Iperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.100/install.jsonnuÏÃ6Ç${"provides":{"Template::Base":{"version":"3.100","file":"lib/Template/Base.pm"},"Template::Stash::Context":{"version":"3.100","file":"lib/Template/Stash/Context.pm"},"Template::Config":{"version":"3.100","file":"lib/Template/Config.pm"},"Template::Plugin::Date::Calc":{"version":"3.100","file":"lib/Template/Plugin/Date.pm"},"Template::View":{"version":"3.100","file":"lib/Template/View.pm"},"Template::Perl":{"version":"3.100","file":"lib/Template/Filters.pm"},"Template::Plugin::Procedural":{"version":"3.100","file":"lib/Template/Plugin/Procedural.pm"},"Template::Plugin::Table":{"version":"3.100","file":"lib/Template/Plugin/Table.pm"},"Template::Plugin::Filter":{"version":"3.100","file":"lib/Template/Plugin/Filter.pm"},"Template::Iterator":{"version":"3.100","file":"lib/Template/Iterator.pm"},"Template::Plugin::Pod":{"version":"3.100","file":"lib/Template/Plugin/Pod.pm"},"Template::Constants":{"version":"3.100","file":"lib/Template/Constants.pm"},"Template::VMethods":{"version":"3.100","file":"lib/Template/VMethods.pm"},"Template::Monad::Scalar":{"version":"3.100","file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::Datafile":{"version":"3.100","file":"lib/Template/Plugin/Datafile.pm"},"Template::Plugin::URL":{"version":"3.100","file":"lib/Template/Plugin/URL.pm"},"Template::Filters":{"version":"3.100","file":"lib/Template/Filters.pm"},"Template::Namespace::Constants":{"version":"3.100","file":"lib/Template/Namespace/Constants.pm"},"Template::Toolkit":{"version":"3.100","file":"lib/Template/Toolkit.pm"},"Template::Context":{"version":"3.100","file":"lib/Template/Context.pm"},"Template::Directive":{"version":"3.100","file":"lib/Template/Directive.pm"},"Template::Plugin":{"version":"3.100","file":"lib/Template/Plugin.pm"},"Template::TieString":{"version":"3.100","file":"lib/Template/Config.pm"},"Template::Plugin::Wrap":{"version":"3.100","file":"lib/Template/Plugin/Wrap.pm"},"Template::Parser":{"version":"3.100","file":"lib/Template/Parser.pm"},"Template::Grammar":{"version":"3.100","file":"lib/Template/Grammar.pm"},"Template::Plugin::HTML":{"version":"3.100","file":"lib/Template/Plugin/HTML.pm"},"Template::Plugin::Format":{"version":"3.100","file":"lib/Template/Plugin/Format.pm"},"Template::Plugin::Scalar":{"version":"3.100","file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::Directory":{"version":"3.100","file":"lib/Template/Plugin/Directory.pm"},"Template::Stash::XS":{"file":"lib/Template/Stash/XS.pm"},"Template::Plugin::Dumper":{"version":"3.100","file":"lib/Template/Plugin/Dumper.pm"},"Template::Plugins":{"version":"3.100","file":"lib/Template/Plugins.pm"},"Template::Plugin::Assert":{"version":"3.100","file":"lib/Template/Plugin/Assert.pm"},"Template::Provider":{"version":"3.100","file":"lib/Template/Provider.pm"},"Template::Stash":{"version":"3.100","file":"lib/Template/Stash.pm"},"Template::Plugin::Image":{"version":"3.100","file":"lib/Template/Plugin/Image.pm"},"Template::Plugin::Date::Manip":{"version":"3.100","file":"lib/Template/Plugin/Date.pm"},"Template::Exception":{"version":"3.100","file":"lib/Template/Exception.pm"},"Template::Plugin::String":{"version":"3.100","file":"lib/Template/Plugin/String.pm"},"Template::Document":{"version":"3.100","file":"lib/Template/Document.pm"},"Template::Plugin::Math":{"version":"3.100","file":"lib/Template/Plugin/Math.pm"},"Template::Service":{"version":"3.100","file":"lib/Template/Service.pm"},"Template::Test":{"version":"3.100","file":"lib/Template/Test.pm"},"Template::Monad::Assert":{"version":"3.100","file":"lib/Template/Plugin/Assert.pm"},"Template::Plugin::Iterator":{"version":"3.100","file":"lib/Template/Plugin/Iterator.pm"},"Template":{"version":"3.100","file":"lib/Template.pm"},"Template::Plugin::Date":{"version":"3.100","file":"lib/Template/Plugin/Date.pm"},"Template::Plugin::File":{"version":"3.100","file":"lib/Template/Plugin/File.pm"},"Template::Plugin::View":{"version":"3.100","file":"lib/Template/Plugin/View.pm"}},"target":"Template::Constants","version":"3.100","name":"Template","dist":"Template-Toolkit-3.100","pathname":"T/TO/TODDR/Template-Toolkit-3.100.tar.gz"}PK!`AѦ””Hperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.100/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "comprehensive template processing system", "author" : [ "Andy Wardley " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Template-Toolkit", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "AppConfig" : "1.56", "File::Spec" : "0.8", "File::Temp" : "0.12", "Scalar::Util" : "0" } }, "test" : { "requires" : { "Test::LeakTrace" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/abw/Template2/issues" }, "homepage" : "http://www.template-toolkit.org", "repository" : { "type" : "git", "url" : "https://github.com/abw/Template2.git", "web" : "https://github.com/abw/Template2" } }, "version" : "3.100" } PK!:hggZperl5/x86_64-linux-thread-multi/.meta/Alien-Build-Plugin-Download-GitLab-0.01/install.jsonnuÏÃ6Ç${"target":"Alien::Build::Plugin::Download::GitLab","pathname":"P/PL/PLICEASE/Alien-Build-Plugin-Download-GitLab-0.01.tar.gz","provides":{"Alien::Build::Plugin::Download::GitLab":{"version":0.01,"file":"lib/Alien/Build/Plugin/Download/GitLab.pm"}},"name":"Alien::Build::Plugin::Download::GitLab","version":0.01,"dist":"Alien-Build-Plugin-Download-GitLab-0.01"}PK!²,�¬®®Yperl5/x86_64-linux-thread-multi/.meta/Alien-Build-Plugin-Download-GitLab-0.01/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Alien::Build plugin to download from GitLab", "author" : [ "Graham Ollis " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.025, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Alien-Build-Plugin-Download-GitLab", "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "recommends" : { "Dist::Zilla::Plugin::Author::Plicease::Core" : "0", "Dist::Zilla::Plugin::Author::Plicease::Upload" : "0", "Dist::Zilla::PluginBundle::Author::Plicease" : "2.71", "Perl::Critic::Policy::BuiltinFunctions::ProhibitBooleanGrep" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitStringySplit" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidGrep" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidMap" : "0", "Perl::Critic::Policy::ClassHierarchies::ProhibitExplicitISA" : "0", "Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless" : "0", "Perl::Critic::Policy::CodeLayout::ProhibitHardTabs" : "0", "Perl::Critic::Policy::CodeLayout::ProhibitTrailingWhitespace" : "0", "Perl::Critic::Policy::CodeLayout::RequireConsistentNewlines" : "0", "Perl::Critic::Policy::Community::ArrayAssignAref" : "0", "Perl::Critic::Policy::Community::BarewordFilehandles" : "0", "Perl::Critic::Policy::Community::ConditionalDeclarations" : "0", "Perl::Critic::Policy::Community::ConditionalImplicitReturn" : "0", "Perl::Critic::Policy::Community::DeprecatedFeatures" : "0", "Perl::Critic::Policy::Community::DiscouragedModules" : "0", "Perl::Critic::Policy::Community::DollarAB" : "0", "Perl::Critic::Policy::Community::Each" : "0", "Perl::Critic::Policy::Community::EmptyReturn" : "0", "Perl::Critic::Policy::Community::IndirectObjectNotation" : "0", "Perl::Critic::Policy::Community::LexicalForeachIterator" : "0", "Perl::Critic::Policy::Community::LoopOnHash" : "0", "Perl::Critic::Policy::Community::ModPerl" : "0", "Perl::Critic::Policy::Community::OpenArgs" : "0", "Perl::Critic::Policy::Community::OverloadOptions" : "0", "Perl::Critic::Policy::Community::POSIXImports" : "0", "Perl::Critic::Policy::Community::PackageMatchesFilename" : "0", "Perl::Critic::Policy::Community::PreferredAlternatives" : "0", "Perl::Critic::Policy::Community::StrictWarnings" : "0", "Perl::Critic::Policy::Community::Threads" : "0", "Perl::Critic::Policy::Community::Wantarray" : "0", "Perl::Critic::Policy::Community::WarningsSwitch" : "0", "Perl::Critic::Policy::Community::WhileDiamondDefaultAssignment" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitLabelsWithSpecialBlockNames" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitMutatingListFunctions" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitUnreachableCode" : "0", "Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles" : "0", "Perl::Critic::Policy::InputOutput::ProhibitJoinedReadline" : "0", "Perl::Critic::Policy::InputOutput::ProhibitTwoArgOpen" : "0", "Perl::Critic::Policy::Miscellanea::ProhibitFormats" : "0", "Perl::Critic::Policy::Miscellanea::ProhibitUselessNoCritic" : "0", "Perl::Critic::Policy::Modules::ProhibitConditionalUseStatements" : "0", "Perl::Critic::Policy::Modules::RequireNoMatchVarsWithUseEnglish" : "0", "Perl::Critic::Policy::Objects::ProhibitIndirectSyntax" : "0", "Perl::Critic::Policy::RegularExpressions::ProhibitUselessTopic" : "0", "Perl::Critic::Policy::Subroutines::ProhibitNestedSubs" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitLeadingZeros" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitMixedBooleanOperators" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitSpecialLiteralHeredocTerminator" : "0", "Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator" : "0", "Perl::Critic::Policy::Variables::ProhibitPerl4PackageNames" : "0", "Perl::Critic::Policy::Variables::ProhibitUnusedVariables" : "0", "Software::License::Perl_5" : "0" }, "requires" : { "File::Spec" : "0", "FindBin" : "0", "Perl::Critic" : "0", "Test2::Require::Module" : "0.000121", "Test2::Tools::PerlCritic" : "0", "Test2::V0" : "0.000121", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.98", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Pod::Spelling::CommonMistakes" : "0", "Test::Spelling" : "0", "Test::Strict" : "0", "YAML" : "0" } }, "runtime" : { "requires" : { "Alien::Build::Plugin" : "0", "JSON::PP" : "0", "Path::Tiny" : "0", "URI" : "0", "URI::Escape" : "0", "perl" : "5.008004" } }, "test" : { "requires" : { "Test2::V0" : "0.000121" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/PerlAlien/Alien-Build-Plugin-Download-GitLab/issues" }, "homepage" : "https://metacpan.org/pod/Alien::Build::Plugin::Download::GitLab", "repository" : { "type" : "git", "url" : "git://github.com/PerlAlien/Alien-Build-Plugin-Download-GitLab.git", "web" : "https://github.com/PerlAlien/Alien-Build-Plugin-Download-GitLab" }, "x_IRC" : "irc://irc.perl.org/#native" }, "version" : "0.01", "x_generated_by_perl" : "v5.35.10", "x_serialization_backend" : "Cpanel::JSON::XS version 4.30", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_use_unsafe_inc" : 0 } PK!ð¯ÐÐBperl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.088/install.jsonnuÏÃ6Ç${"version":"0.088","name":"HTTP::Tiny","provides":{"HTTP::Tiny":{"version":"0.088","file":"lib/HTTP/Tiny.pm"}},"pathname":"D/DA/DAGOLDEN/HTTP-Tiny-0.088.tar.gz","target":"HTTP::Tiny","dist":"HTTP-Tiny-0.088"}PK!p)þ˜ÄÄAperl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.088/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "A small, simple, correct HTTP/1.1 client", "author" : [ "Christian Hansen ", "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.030, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "HTTP-Tiny", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::ReleaseStatus::FromVersion" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.072", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Perl::Critic::Policy::Lax::ProhibitStringyEval::ExceptForRequire" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Software::License::Perl_5" : "0", "Test::CPAN::Meta" : "0", "Test::MinimumVersion" : "0", "Test::More" : "0", "Test::Perl::Critic" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1", "perl" : "5.006" } }, "runtime" : { "recommends" : { "HTTP::CookieJar" : "0.001", "IO::Socket::IP" : "0.32", "IO::Socket::SSL" : "1.42", "Mozilla::CA" : "20160104", "Net::SSLeay" : "1.49" }, "requires" : { "Carp" : "0", "Fcntl" : "0", "IO::Socket" : "0", "MIME::Base64" : "0", "Socket" : "0", "Time::Local" : "0", "bytes" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" }, "suggests" : { "IO::Socket::SSL" : "1.56" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "Data::Dumper" : "0", "Exporter" : "0", "ExtUtils::MakeMaker" : "0", "File::Basename" : "0", "File::Spec" : "0", "File::Temp" : "0", "IO::Dir" : "0", "IO::File" : "0", "IO::Socket::INET" : "0", "IPC::Cmd" : "0", "Test::More" : "0.96", "lib" : "0", "open" : "0" } } }, "provides" : { "HTTP::Tiny" : { "file" : "lib/HTTP/Tiny.pm", "version" : "0.088" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/Perl-Toolchain-Gang/HTTP-Tiny/issues" }, "homepage" : "https://github.com/Perl-Toolchain-Gang/HTTP-Tiny", "repository" : { "type" : "git", "url" : "https://github.com/Perl-Toolchain-Gang/HTTP-Tiny.git", "web" : "https://github.com/Perl-Toolchain-Gang/HTTP-Tiny" } }, "version" : "0.088", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Alan Gardner ", "Alessandro Ghedini ", "A. Sinan Unur ", "Brad Gilbert ", "brian m. carlson ", "Chris Nehren ", "Chris Weyl ", "Claes Jakobsson ", "Clinton Gormley ", "Craig A. Berry ", "Craig Berry ", "David Golden ", "David Mitchell ", "Dean Pearce ", "Edward Zborowski ", "Felipe Gasper ", "Graham Knop ", "Greg Kennedy ", "James E Keenan ", "James Raspass ", "Jeremy Mates ", "Jess Robinson ", "Karen Etheridge ", "Lukas Eklund ", "Martin J. Evans ", "Martin-Louis Bright ", "Matthew Horsfall ", "Michael R. Davis ", "Mike Doherty ", "Nicolas Rochelemagne ", "Olaf Alders ", "Olivier Mengué ", "Petr PísaÅ™ ", "sanjay-cpu ", "Serguei Trouchelle ", "Shoichi Kaji ", "SkyMarshal ", "Sören Kornetzki ", "Steve Grazzini ", "Stig Palmquist ", "Syohei YOSHIDA ", "Tatsuhiko Miyagawa ", "Tom Hukins ", "Tony Cook ", "Xavier Guimard " ], "x_generated_by_perl" : "v5.36.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.29", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } PK!¶Œ7ññGperl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-YAML-0.018/install.jsonnuÏÃ6Ç${"provides":{"CPAN::Meta::YAML":{"version":"0.018","file":"lib/CPAN/Meta/YAML.pm"}},"target":"CPAN::Meta::YAML","version":"0.018","name":"CPAN::Meta::YAML","dist":"CPAN-Meta-YAML-0.018","pathname":"D/DA/DAGOLDEN/CPAN-Meta-YAML-0.018.tar.gz"}PK!&A䉉Fperl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-YAML-0.018/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Read and write a subset of YAML for CPAN Meta files", "author" : [ "Adam Kennedy ", "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.042, CPAN::Meta::Converter version 2.150001, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "CPAN-Meta-YAML", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::AppendExternalData" : "0", "Dist::Zilla::Plugin::Authority" : "0", "Dist::Zilla::Plugin::AutoPrereqs" : "0", "Dist::Zilla::Plugin::CheckChangesHasContent" : "0", "Dist::Zilla::Plugin::CheckMetaResources" : "0", "Dist::Zilla::Plugin::CheckPrereqsIndexed" : "0", "Dist::Zilla::Plugin::ConfirmRelease" : "0", "Dist::Zilla::Plugin::Doppelgaenger" : "0.007", "Dist::Zilla::Plugin::Encoding" : "0", "Dist::Zilla::Plugin::ExecDir" : "0", "Dist::Zilla::Plugin::Git::Check" : "0", "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch" : "0", "Dist::Zilla::Plugin::Git::Commit" : "0", "Dist::Zilla::Plugin::Git::Contributors" : "0", "Dist::Zilla::Plugin::Git::GatherDir" : "0", "Dist::Zilla::Plugin::Git::NextVersion" : "0", "Dist::Zilla::Plugin::Git::Push" : "0", "Dist::Zilla::Plugin::Git::Tag" : "0", "Dist::Zilla::Plugin::GithubMeta" : "0", "Dist::Zilla::Plugin::License" : "0", "Dist::Zilla::Plugin::MakeMaker" : "0", "Dist::Zilla::Plugin::MakeMaker::Highlander" : "0.003", "Dist::Zilla::Plugin::Manifest" : "0", "Dist::Zilla::Plugin::ManifestSkip" : "0", "Dist::Zilla::Plugin::MetaJSON" : "0", "Dist::Zilla::Plugin::MetaNoIndex" : "0", "Dist::Zilla::Plugin::MetaProvides::Package" : "0", "Dist::Zilla::Plugin::MetaResources" : "0", "Dist::Zilla::Plugin::MetaTests" : "0", "Dist::Zilla::Plugin::MetaYAML" : "0", "Dist::Zilla::Plugin::MinimumPerl" : "0", "Dist::Zilla::Plugin::NextRelease" : "0", "Dist::Zilla::Plugin::PkgVersion" : "0", "Dist::Zilla::Plugin::Pod2Readme" : "0", "Dist::Zilla::Plugin::PodSyntaxTests" : "0", "Dist::Zilla::Plugin::PodWeaver" : "0", "Dist::Zilla::Plugin::Prereqs::AuthorDeps" : "0", "Dist::Zilla::Plugin::PromptIfStale" : "0", "Dist::Zilla::Plugin::PruneCruft" : "0", "Dist::Zilla::Plugin::PruneFiles" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::Plugin::RunExtraTests" : "0", "Dist::Zilla::Plugin::ShareDir" : "0", "Dist::Zilla::Plugin::Test::Compile" : "0", "Dist::Zilla::Plugin::Test::ReportPrereqs" : "0", "Dist::Zilla::Plugin::Test::Version" : "0", "Dist::Zilla::Plugin::TestRelease" : "0", "Dist::Zilla::Plugin::UploadToCPAN" : "0", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Software::License::Perl_5" : "0", "Test::CPAN::Meta" : "0", "Test::More" : "0", "Test::Pod" : "1.41", "Test::Version" : "1", "blib" : "1.01" } }, "runtime" : { "requires" : { "B" : "0", "Carp" : "0", "Exporter" : "0", "Fcntl" : "0", "Scalar::Util" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Basename" : "0", "File::Find" : "0", "File::Spec" : "0", "File::Spec::Functions" : "0", "File::Temp" : "0.19", "IO::Dir" : "0", "JSON::PP" : "0", "Test::More" : "0.88", "base" : "0", "lib" : "0", "utf8" : "0", "vars" : "0" } } }, "provides" : { "CPAN::Meta::YAML" : { "file" : "lib/CPAN/Meta/YAML.pm", "version" : "0.018" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/Perl-Toolchain-Gang/YAML-Tiny/issues" }, "homepage" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-YAML", "repository" : { "type" : "git", "url" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-YAML.git", "web" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-YAML" } }, "version" : "0.018", "x_authority" : "cpan:DAGOLDEN" } PK!¶C!´è è <perl5/x86_64-linux-thread-multi/.meta/CPAN-2.28/install.jsonnuÏÃ6Ç${"provides":{"CPAN::Index":{"version":2.12,"file":"lib/CPAN/Index.pm"},"CPAN::Plugin":{"version":0.97,"file":"lib/CPAN/Plugin.pm"},"CPAN::Mirrored::By":{"version":2.27,"file":"lib/CPAN/Mirrors.pm"},"CPAN::HTTP::Client":{"version":1.9601,"file":"lib/CPAN/HTTP/Client.pm"},"CPAN::FTP::netrc":{"version":1.01,"file":"lib/CPAN/FTP/netrc.pm"},"CPAN::Version":{"version":5.5003,"file":"lib/CPAN/Version.pm"},"CPAN::Admin":{"version":5.501,"file":"lib/CPAN/Admin.pm"},"CPAN::Plugin::Specfile":{"version":0.02,"file":"lib/CPAN/Plugin/Specfile.pm"},"CPAN::Distroprefs::Result::Error":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::InfoObj":{"version":5.5,"file":"lib/CPAN/InfoObj.pm"},"CPAN::Exception::RecursiveDependency::na":{"version":5.5001,"file":"lib/CPAN/Exception/RecursiveDependency.pm"},"CPAN::HandleConfig":{"version":5.5011,"file":"lib/CPAN/HandleConfig.pm"},"CPAN::Exception::yaml_process_error":{"version":5.5,"file":"lib/CPAN/Exception/yaml_process_error.pm"},"CPAN::Nox":{"version":5.5001,"file":"lib/CPAN/Nox.pm"},"CPAN::Exception::RecursiveDependency":{"version":5.5001,"file":"lib/CPAN/Exception/RecursiveDependency.pm"},"CPAN::Distroprefs::Result::Warning":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Distroprefs::Pref":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Debug":{"version":5.5001,"file":"lib/CPAN/Debug.pm"},"CPAN::Distroprefs::Result::Success":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Shell":{"version":5.5009,"file":"lib/CPAN/Shell.pm"},"CPAN::Queue::Item":{"version":5.5003,"file":"lib/CPAN/Queue.pm"},"CPAN::CacheMgr":{"version":5.5002,"file":"lib/CPAN/CacheMgr.pm"},"CPAN::Eval":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Distroprefs":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Distribution":{"version":2.27,"file":"lib/CPAN/Distribution.pm"},"CPAN::Complete":{"version":5.5001,"file":"lib/CPAN/Complete.pm"},"CPAN::FirstTime":{"version":5.5315,"file":"lib/CPAN/FirstTime.pm"},"App::Cpan":{"version":1.676,"file":"lib/App/Cpan.pm"},"CPAN::Author":{"version":5.5002,"file":"lib/CPAN/Author.pm"},"CPAN::URL":{"version":5.5,"file":"lib/CPAN/URL.pm"},"CPAN::Kwalify":{"version":"5.50","file":"lib/CPAN/Kwalify.pm"},"CPAN::LWP::UserAgent":{"version":1.9601,"file":"lib/CPAN/LWP/UserAgent.pm"},"CPAN::Bundle":{"version":5.5005,"file":"lib/CPAN/Bundle.pm"},"CPAN::FTP":{"version":5.5013,"file":"lib/CPAN/FTP.pm"},"CPAN::HTTP::Credentials":{"version":1.9601,"file":"lib/CPAN/HTTP/Credentials.pm"},"CPAN::Distroprefs::Result::Fatal":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Distrostatus":{"version":5.5,"file":"lib/CPAN/Distrostatus.pm"},"CPAN::Module":{"version":5.5003,"file":"lib/CPAN/Module.pm"},"CPAN::Distroprefs::Result":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Exception::blocked_urllist":{"version":1.001,"file":"lib/CPAN/Exception/blocked_urllist.pm"},"CPAN::Tarzip":{"version":5.5013,"file":"lib/CPAN/Tarzip.pm"},"CPAN::Mirrors":{"version":2.27,"file":"lib/CPAN/Mirrors.pm"},"CPAN::Distroprefs::Iterator":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::DeferredCode":{"version":"5.50","file":"lib/CPAN/DeferredCode.pm"},"CPAN::Prompt":{"version":5.5,"file":"lib/CPAN/Prompt.pm"},"CPAN::Exception::yaml_not_installed":{"version":5.5,"file":"lib/CPAN/Exception/yaml_not_installed.pm"},"CPAN::Queue":{"version":5.5003,"file":"lib/CPAN/Queue.pm"},"CPAN":{"version":2.28,"file":"lib/CPAN.pm"}},"target":"CPAN","version":2.28,"name":"CPAN","dist":"CPAN-2.28","pathname":"A/AN/ANDK/CPAN-2.28.tar.gz"}PK!÷TBòF F ;perl5/x86_64-linux-thread-multi/.meta/CPAN-2.28/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "query, download and build perl modules from CPAN sites", "author" : [ "Andreas Koenig " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "CPAN", "module", "module installation" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "CPAN", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Archive::Tar" : "0", "CPAN::Meta" : "0", "CPAN::Meta::Requirements" : "2.121", "CPAN::Meta::YAML" : "0", "Compress::Zlib" : "0", "Data::Dumper" : "0", "Digest::MD5" : "0", "Digest::SHA" : "0", "Exporter" : "0", "Exporter::Heavy" : "0", "ExtUtils::CBuilder" : "0", "File::Copy" : "0", "File::Spec" : "0", "File::Temp" : "0", "HTTP::Tiny" : "0", "IO::Compress::Base" : "0", "IO::Zlib" : "0", "JSON::PP" : "0", "LWP::UserAgent" : "0", "MIME::Base64" : "0", "Module::Build" : "0", "Net::FTP" : "0", "Net::Ping" : "0", "Parse::CPAN::Meta" : "0", "Pod::Perldoc" : "0", "Pod::Perldoc::ToMan" : "0", "Scalar::Util" : "0", "Socket" : "0", "Term::ReadKey" : "0", "Test::Harness" : "2.62", "Test::More" : "0", "Text::ParseWords" : "0", "Text::Wrap" : "0", "perl" : "5.006002" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/andk/cpanpm" } }, "version" : "2.28", "x_serialization_backend" : "JSON::PP version 2.97001" } PK!º"@6Eperl5/x86_64-linux-thread-multi/.meta/local-lib-2.000024/install.jsonnuÏÃ6Ç${"provides":{"lib::core::only":{"file":"lib/lib/core/only.pm"},"local::lib":{"version":2.000024,"file":"lib/local/lib.pm"}},"target":"local::lib","version":2.000024,"name":"local::lib","dist":"local-lib-2.000024","pathname":"H/HA/HAARG/local-lib-2.000024.tar.gz"}PK!Á ô³Dperl5/x86_64-linux-thread-multi/.meta/local-lib-2.000024/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "create and use a local lib/ for perl modules with PERL5LIB", "author" : [ "mst - Matt S. Trout (cpan:MSTROUT) " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150005, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "local-lib", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : {} }, "configure" : { "requires" : {} }, "develop" : { "requires" : { "Capture::Tiny" : "0", "Module::Build" : "0.36", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::More" : "0.8101", "Test::NoTabs" : "0", "Test::Pod" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } }, "test" : { "requires" : { "Test::More" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-local-lib@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=local-lib" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "git://github.com/Perl-Toolchain-Gang/local-lib", "web" : "https://github.com/Perl-Toolchain-Gang/local-lib" }, "x_IRC" : "irc://irc.perl.org/#local-lib" }, "version" : "2.000024", "x_serialization_backend" : "JSON::PP version 2.94" } PK!êòZW>perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.20/install.jsonnuÏÃ6Ç${"dist":"IO-Tty-1.20","target":"IO::Tty","pathname":"T/TO/TODDR/IO-Tty-1.20.tar.gz","provides":{"IO::Pty":{"file":"Pty.pm","version":"1.20"},"IO::Tty":{"version":"1.20","file":"Tty.pm"},"IO::Tty::Constant":{"version":"1.20","file":"Tty/Constant.pm"}},"name":"IO::Tty","version":"1.20"}PK!ÚlMhh=perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.20/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Pseudo ttys and constants", "author" : [ "Roland Giersig " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "IO-Tty", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/IO-Tty/issues" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "https://github.com/toddr/IO-Tty" } }, "version" : "1.20", "x_serialization_backend" : "JSON::PP version 4.07" } PK!ò¢,ssAperl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.45/install.jsonnuÏÃ6Ç${"dist":"YAML-Syck-1.45","version":"1.45","provides":{"YAML::Syck":{"version":"1.45","file":"lib/YAML/Syck.pm"},"YAML::Loader::Syck":{"file":"lib/YAML/Loader/Syck.pm"},"YAML::Dumper::Syck":{"file":"lib/YAML/Dumper/Syck.pm"},"JSON::Syck":{"version":"1.45","file":"lib/JSON/Syck.pm"}},"target":"YAML::Syck","pathname":"T/TO/TODDR/YAML-Syck-1.45.tar.gz","name":"YAML::Syck"}PK!ú¡ææ@perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.45/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Fast, lightweight YAML loader and dumper", "author" : [ "Todd Rinaldo " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "YAML-Syck", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } } }, "provides" : { "JSON::Syck" : { "file" : "lib/JSON/Syck.pm", "version" : "1.45" }, "YAML::Dumper::Syck" : { "file" : "lib/YAML/Dumper/Syck.pm" }, "YAML::Loader::Syck" : { "file" : "lib/YAML/Loader/Syck.pm" }, "YAML::Syck" : { "file" : "lib/YAML/Syck.pm", "version" : "1.45" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/YAML-Syck/issues" }, "homepage" : "https://github.com/toddr/YAML-Syck", "license" : [ "https://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "https://github.com/toddr/YAML-Syck.git", "web" : "https://github.com/toddr/YAML-Syck" } }, "version" : "1.45", "x_serialization_backend" : "JSON::PP version 4.16" } PK!»”¨‘||Aperl5/x86_64-linux-thread-multi/.meta/version-0.9932/install.jsonnuÏÃ6Ç${"dist":"version-0.9932","target":"version","version":0.9932,"provides":{"version::vxs":{"version":0.9932,"file":"vutil/lib/version/vxs.pm"},"version::regex":{"file":"lib/version/regex.pm","version":0.9932},"version":{"file":"lib/version.pm","version":0.9932},"version::vpp":{"file":"vperl/vpp.pm","version":0.9932}},"pathname":"L/LE/LEONT/version-0.9932.tar.gz","name":"version"}PK!"utDññ@perl5/x86_64-linux-thread-multi/.meta/version-0.9932/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Structured version objects", "author" : [ "John Peacock " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.70, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "version", "no_index" : { "directory" : [ "t", "inc" ], "package" : [ "charstar" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006002" } }, "test" : { "requires" : { "File::Temp" : "0.13", "Test::More" : "0.45", "base" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-version@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=version" }, "repository" : { "type" : "git", "url" : "git://github.com/Perl/version.pm.git", "web" : "https://github.com/Perl/version.pm" } }, "version" : "0.9932", "x_serialization_backend" : "JSON::PP version 4.16" } PK!&B†mmAperl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.36/install.jsonnuÏÃ6Ç${"dist":"YAML-Syck-1.36","pathname":"T/TO/TODDR/YAML-Syck-1.36.tar.gz","provides":{"YAML::Loader::Syck":{"file":"lib/YAML/Loader/Syck.pm"},"YAML::Syck":{"version":1.36,"file":"lib/YAML/Syck.pm"},"JSON::Syck":{"version":1.36,"file":"lib/JSON/Syck.pm"},"YAML::Dumper::Syck":{"file":"lib/YAML/Dumper/Syck.pm"}},"name":"YAML::Syck","version":1.36,"target":"YAML::Syck"}PK!VL  @perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.36/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Fast, lightweight YAML loader and dumper", "author" : [ "Todd Rinaldo " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "YAML-Syck", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/YAML-Syck/issues" }, "homepage" : "http://github.com/toddr/YAML-Syck", "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "http://github.com/toddr/YAML-Syck" } }, "version" : "1.36", "x_serialization_backend" : "JSON::PP version 4.16" } PK!5J×õ``Iperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.010/install.jsonnuÏÃ6Ç${"provides":{"Template::Base":{"version":"3.010","file":"lib/Template/Base.pm"},"Template::Stash::Context":{"version":"3.010","file":"lib/Template/Stash/Context.pm"},"Template::Config":{"version":"3.010","file":"lib/Template/Config.pm"},"Template::Plugin::Date::Calc":{"version":"3.010","file":"lib/Template/Plugin/Date.pm"},"Template::View":{"version":"3.010","file":"lib/Template/View.pm"},"Template::Perl":{"version":"3.010","file":"lib/Template/Filters.pm"},"Template::Plugin::Procedural":{"version":"3.010","file":"lib/Template/Plugin/Procedural.pm"},"Template::Plugin::Table":{"version":"3.010","file":"lib/Template/Plugin/Table.pm"},"Template::Plugin::Filter":{"version":"3.010","file":"lib/Template/Plugin/Filter.pm"},"Template::Iterator":{"version":"3.010","file":"lib/Template/Iterator.pm"},"Template::Plugin::Pod":{"version":"3.010","file":"lib/Template/Plugin/Pod.pm"},"Template::Constants":{"version":"3.010","file":"lib/Template/Constants.pm"},"Template::VMethods":{"version":"3.010","file":"lib/Template/VMethods.pm"},"Template::Monad::Scalar":{"version":"3.010","file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::Datafile":{"version":"3.010","file":"lib/Template/Plugin/Datafile.pm"},"Template::Plugin::URL":{"version":"3.010","file":"lib/Template/Plugin/URL.pm"},"Template::Filters":{"version":"3.010","file":"lib/Template/Filters.pm"},"Template::Namespace::Constants":{"version":"3.010","file":"lib/Template/Namespace/Constants.pm"},"Template::Toolkit":{"version":"3.010","file":"lib/Template/Toolkit.pm"},"Template::Context":{"version":"3.010","file":"lib/Template/Context.pm"},"Template::Directive":{"version":"3.010","file":"lib/Template/Directive.pm"},"Template::Plugin":{"version":"3.010","file":"lib/Template/Plugin.pm"},"Template::TieString":{"version":"3.010","file":"lib/Template/Config.pm"},"Template::Plugin::Wrap":{"version":"3.010","file":"lib/Template/Plugin/Wrap.pm"},"Template::Parser":{"version":"3.010","file":"lib/Template/Parser.pm"},"Template::Grammar":{"version":"3.010","file":"lib/Template/Grammar.pm"},"Template::Plugin::HTML":{"version":"3.010","file":"lib/Template/Plugin/HTML.pm"},"Template::Plugin::Format":{"version":"3.010","file":"lib/Template/Plugin/Format.pm"},"Template::Plugin::Scalar":{"version":"3.010","file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::Directory":{"version":"3.010","file":"lib/Template/Plugin/Directory.pm"},"Template::Stash::XS":{"file":"lib/Template/Stash/XS.pm"},"Template::Plugin::Dumper":{"version":"3.010","file":"lib/Template/Plugin/Dumper.pm"},"Template::Plugins":{"version":"3.010","file":"lib/Template/Plugins.pm"},"Template::Plugin::Assert":{"version":"3.010","file":"lib/Template/Plugin/Assert.pm"},"Template::Provider":{"version":"3.010","file":"lib/Template/Provider.pm"},"Template::Stash":{"version":"3.010","file":"lib/Template/Stash.pm"},"Template::Plugin::Image":{"version":"3.010","file":"lib/Template/Plugin/Image.pm"},"Template::Plugin::Date::Manip":{"version":"3.010","file":"lib/Template/Plugin/Date.pm"},"Template::Exception":{"version":"3.010","file":"lib/Template/Exception.pm"},"Template::Plugin::String":{"version":"3.010","file":"lib/Template/Plugin/String.pm"},"Template::Document":{"version":"3.010","file":"lib/Template/Document.pm"},"Template::Plugin::Math":{"version":"3.010","file":"lib/Template/Plugin/Math.pm"},"Template::Service":{"version":"3.010","file":"lib/Template/Service.pm"},"Template::Test":{"version":"3.010","file":"lib/Template/Test.pm"},"Template::Monad::Assert":{"version":"3.010","file":"lib/Template/Plugin/Assert.pm"},"Template::Plugin::Iterator":{"version":"3.010","file":"lib/Template/Plugin/Iterator.pm"},"Template":{"version":"3.010","file":"lib/Template.pm"},"Template::Plugin::CGI":{"version":"3.010","file":"lib/Template/Plugin/CGI.pm"},"Template::Plugin::Date":{"version":"3.010","file":"lib/Template/Plugin/Date.pm"},"Template::Plugin::File":{"version":"3.010","file":"lib/Template/Plugin/File.pm"},"Template::Plugin::View":{"version":"3.010","file":"lib/Template/Plugin/View.pm"}},"target":"Template::Constants","version":"3.010","name":"Template","dist":"Template-Toolkit-3.010","pathname":"A/AT/ATOOMIC/Template-Toolkit-3.010.tar.gz"}PK!åÖ—§°°Hperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.010/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "comprehensive template processing system", "author" : [ "Andy Wardley " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Template-Toolkit", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "AppConfig" : "1.56", "File::Spec" : "0.8", "File::Temp" : "0.12", "Scalar::Util" : "0" } }, "test" : { "requires" : { "CGI" : "4.11", "Test::LeakTrace" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/abw/Template2/issues" }, "homepage" : "http://www.template-toolkit.org", "repository" : { "type" : "git", "url" : "https://github.com/abw/Template2.git", "web" : "https://github.com/abw/Template2" } }, "version" : "3.010" } PK!¬Ã[µAperl5/x86_64-linux-thread-multi/.meta/HTML-Tree-5.07/install.jsonnuÏÃ6Ç${"provides":{"HTML::Element::traverse":{"version":5.07,"file":"lib/HTML/Element/traverse.pm"},"HTML::Element":{"version":5.07,"file":"lib/HTML/Element.pm"},"HTML::TreeBuilder":{"version":5.07,"file":"lib/HTML/TreeBuilder.pm"},"HTML::Parse":{"version":5.07,"file":"lib/HTML/Parse.pm"},"HTML::Tree":{"version":5.07,"file":"lib/HTML/Tree.pm"},"HTML::AsSubs":{"version":5.07,"file":"lib/HTML/AsSubs.pm"}},"target":"HTML::TreeBuilder","version":5.07,"name":"HTML::Tree","dist":"HTML-Tree-5.07","pathname":"K/KE/KENTNL/HTML-Tree-5.07.tar.gz"}PK!²)h]ÎBÎB@perl5/x86_64-linux-thread-multi/.meta/HTML-Tree-5.07/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Work with HTML in a DOM-like tree structure", "author" : [ "Christopher J. Madsen ", "Jeff Fearn " ], "dynamic_config" : 0, "generated_by" : "Module::Build version 0.4005, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "HTML-Tree", "no_index" : { "directory" : [ "inc", "t" ] }, "prereqs" : { "build" : { "requires" : { "Encode" : "0", "Module::Build" : "0.2808", "Test::Fatal" : "0", "Test::More" : "0", "base" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.2808" } }, "runtime" : { "recommends" : { "HTML::FormatText" : "0", "LWP::UserAgent" : "5.815" }, "requires" : { "Carp" : "0", "Exporter" : "0", "HTML::Entities" : "0", "HTML::Parser" : "3.46", "HTML::Tagset" : "3.02", "Scalar::Util" : "0", "integer" : "0", "perl" : "5.008" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "git://github.com/kentfredric/HTML-Tree.git" } }, "version" : "5.07", "x_Dist_Zilla" : { "perl" : { "version" : "5.026000" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : "0" } }, "name" : "Git::GatherDir", "version" : "2.041" }, { "class" : "Dist::Zilla::Plugin::ManifestSkip", "name" : "ManifestSkip", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "MetaJSON", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "MetaYAML", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "MetaConfig", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "License", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::MatchManifest", "name" : "MatchManifest", "version" : "4.02" }, { "class" : "Dist::Zilla::Plugin::CheckChangesHasContent", "name" : "CheckChangesHasContent", "version" : "0.010" }, { "class" : "Dist::Zilla::Plugin::Test::PrereqsFromMeta", "name" : "Test::PrereqsFromMeta", "version" : "4.23" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "PodSyntaxTests", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::PodCoverageTests", "name" : "PodCoverageTests", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::ModuleBuild::Custom", "name" : "ModuleBuild::Custom", "version" : "4.26" }, { "class" : "Dist::Zilla::Plugin::RecommendedPrereqs", "name" : "RecommendedPrereqs", "version" : "4.21" }, { "class" : "Dist::Zilla::Plugin::CheckPrereqsIndexed", "name" : "CheckPrereqsIndexed", "version" : "0.020" }, { "class" : "Dist::Zilla::Plugin::OurPkgVersion", "name" : "OurPkgVersion", "version" : "0.10" }, { "class" : "Dist::Zilla::Plugin::TemplateCJM", "name" : "TemplateCJM", "version" : "5.001" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ "FilesToWeave" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "Over ATTRIBUTES", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "Over METHODS", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "HOW WE REPRESENT TREES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "BASIC METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "STRUCTURE-MODIFYING METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "Over STRUCTURE-MODIFYING METHODS", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "DUMPING METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "SECONDARY STRUCTURAL METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "Over SECONDARY STRUCTURAL METHODS", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "CLASS METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "INTERNAL METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "Over INTERNAL METHODS", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "SUBROUTINES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Template", "name" : "AUTHOR", "version" : "0.04" }, { "class" : "Pod::Weaver::Section::Template", "name" : "COPYRIGHT AND LICENSE", "version" : "0.04" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "COPYRIGHT", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Region", "name" : "postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::EnsureUniqueSections", "name" : "-EnsureUniqueSections", "version" : "0.163250" } ] } }, "name" : "PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::FileFinder::Filter", "name" : "FilesToWeave", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::Repository", "name" : "Repository", "version" : "0.20" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "NextRelease", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::Git::NextVersion", "config" : { "Dist::Zilla::Plugin::Git::NextVersion" : { "first_version" : "0.001", "version_by_branch" : "0", "version_regexp" : "(?^u:^(\\d+\\.[\\d_]+)(?:-TRIAL)?$)" }, "Dist::Zilla::Role::Git::Repo" : { "git --version" : "2.13.1", "repo_root" : "." } }, "name" : "Git::NextVersion", "version" : "2.041" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git --version" : "2.13.1", "repo_root" : "." } }, "name" : "@Git/Check", "version" : "2.041" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "Updated Changes for %{MMMM d, yyyy}d%{ trial}t release of %v" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git --version" : "2.13.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git/Commit", "version" : "2.041" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : "0", "tag" : "5.07", "tag_format" : "%v%t", "tag_message" : "Tagged %N %v%{ (trial release)}t" }, "Dist::Zilla::Role::Git::Repo" : { "git --version" : "2.13.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git/Tag", "version" : "2.041" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "github master" ], "remotes_must_exist" : "1" }, "Dist::Zilla::Role::Git::Repo" : { "git --version" : "2.13.1", "repo_root" : "." } }, "name" : "@Git/Push", "version" : "2.041" }, { "class" : "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch", "config" : { "Dist::Zilla::Role::Git::Repo" : { "git --version" : "2.13.1", "repo_root" : "." } }, "name" : "GitBranch", "version" : "0.014" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "name" : "RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "TestRelease", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "UploadToCPAN", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::ArchiveRelease", "name" : "ArchiveRelease", "version" : "4.26" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "ConfirmRelease", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "AutoPrereqs", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "MetaNoIndex", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "4.300039" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "4.300039" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : "0" }, "version" : "4.300039" } } } PK!§‘Á/ÃÃ@perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.31/install.jsonnuÏÃ6Ç${"name":"Try::Tiny","provides":{"Try::Tiny":{"file":"lib/Try/Tiny.pm","version":"0.31"}},"pathname":"E/ET/ETHER/Try-Tiny-0.31.tar.gz","version":"0.31","target":"Try::Tiny","dist":"Try-Tiny-0.31"}PK!Cx;;B½B½?perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.31/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Minimal try/catch with proper preservation of $@", "author" : [ "יובל קוג'מן (Yuval Kogman) ", "Jesse Luehrs " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.024, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Try-Tiny", "no_index" : { "directory" : [ "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "recommends" : { "Dist::Zilla::PluginBundle::Author::ETHER" : "0.161", "Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007" }, "requires" : { "Capture::Tiny" : "0.12", "Encode" : "0", "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Sub::Name" : "0.08", "Sub::Util" : "0", "Test::CPAN::Changes" : "0.19", "Test::CPAN::Meta" : "0", "Test::EOL" : "0", "Test::Kwalitee" : "1.21", "Test::MinimumVersion" : "0", "Test::Mojibake" : "0", "Test::More" : "0.96", "Test::NoTabs" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Pod::No404s" : "0", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12" } }, "runtime" : { "requires" : { "Carp" : "0", "Exporter" : "5.57", "constant" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" }, "suggests" : { "Sub::Name" : "0.08", "Sub::Util" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::More" : "0", "if" : "0" }, "suggests" : { "CPAN::Meta::Check" : "0.011", "CPAN::Meta::Requirements" : "0", "Capture::Tiny" : "0.12" } }, "x_Dist_Zilla" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::Authority" : "1.009", "Dist::Zilla::Plugin::AutoMetaResources" : "0", "Dist::Zilla::Plugin::AutoPrereqs" : "5.038", "Dist::Zilla::Plugin::Breaks" : "0", "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : "0.004", "Dist::Zilla::Plugin::CheckIssues" : "0", "Dist::Zilla::Plugin::CheckMetaResources" : "0", "Dist::Zilla::Plugin::CheckPrereqsIndexed" : "0.019", "Dist::Zilla::Plugin::CheckSelfDependency" : "0", "Dist::Zilla::Plugin::CheckStrictVersion" : "0", "Dist::Zilla::Plugin::ConfirmRelease" : "0", "Dist::Zilla::Plugin::CopyFilesFromRelease" : "0", "Dist::Zilla::Plugin::EnsureLatestPerl" : "0", "Dist::Zilla::Plugin::FileFinder::ByName" : "0", "Dist::Zilla::Plugin::FileFinder::Filter" : "0", "Dist::Zilla::Plugin::GenerateFile::FromShareDir" : "0", "Dist::Zilla::Plugin::Git::Check" : "0", "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch" : "0.004", "Dist::Zilla::Plugin::Git::CheckFor::MergeConflicts" : "0", "Dist::Zilla::Plugin::Git::Commit" : "2.020", "Dist::Zilla::Plugin::Git::Contributors" : "0.029", "Dist::Zilla::Plugin::Git::Describe" : "0.004", "Dist::Zilla::Plugin::Git::GatherDir" : "2.016", "Dist::Zilla::Plugin::Git::Push" : "0", "Dist::Zilla::Plugin::Git::Remote::Check" : "0", "Dist::Zilla::Plugin::Git::Tag" : "0", "Dist::Zilla::Plugin::GitHub::Update" : "0.40", "Dist::Zilla::Plugin::GithubMeta" : "0.54", "Dist::Zilla::Plugin::InstallGuide" : "1.200005", "Dist::Zilla::Plugin::Keywords" : "0.004", "Dist::Zilla::Plugin::License" : "5.038", "Dist::Zilla::Plugin::MakeMaker" : "0", "Dist::Zilla::Plugin::Manifest" : "0", "Dist::Zilla::Plugin::MetaConfig" : "0", "Dist::Zilla::Plugin::MetaJSON" : "0", "Dist::Zilla::Plugin::MetaNoIndex" : "0", "Dist::Zilla::Plugin::MetaProvides::Package" : "1.15000002", "Dist::Zilla::Plugin::MetaTests" : "0", "Dist::Zilla::Plugin::MetaYAML" : "0", "Dist::Zilla::Plugin::MinimumPerl" : "1.006", "Dist::Zilla::Plugin::MojibakeTests" : "0.8", "Dist::Zilla::Plugin::NextRelease" : "5.033", "Dist::Zilla::Plugin::OnlyCorePrereqs" : "0", "Dist::Zilla::Plugin::PodCoverageTests" : "5.040", "Dist::Zilla::Plugin::PodSyntaxTests" : "5.040", "Dist::Zilla::Plugin::PodWeaver" : "4.008", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::Prereqs::AuthorDeps" : "0.006", "Dist::Zilla::Plugin::Prereqs::Soften" : "0", "Dist::Zilla::Plugin::PromptIfStale" : "0", "Dist::Zilla::Plugin::Readme" : "0", "Dist::Zilla::Plugin::ReadmeAnyFromPod" : "0.142180", "Dist::Zilla::Plugin::RewriteVersion::Transitional" : "0.006", "Dist::Zilla::Plugin::Run::AfterBuild" : "0.041", "Dist::Zilla::Plugin::Run::AfterRelease" : "0.038", "Dist::Zilla::Plugin::RunExtraTests" : "0.024", "Dist::Zilla::Plugin::StaticInstall" : "0.005", "Dist::Zilla::Plugin::Substitute" : "0", "Dist::Zilla::Plugin::Test::CPAN::Changes" : "0.012", "Dist::Zilla::Plugin::Test::ChangesHasContent" : "0", "Dist::Zilla::Plugin::Test::CheckBreaks" : "0.018", "Dist::Zilla::Plugin::Test::Compile" : "2.039", "Dist::Zilla::Plugin::Test::EOL" : "0.17", "Dist::Zilla::Plugin::Test::Kwalitee" : "2.10", "Dist::Zilla::Plugin::Test::MinimumVersion" : "2.000010", "Dist::Zilla::Plugin::Test::NoTabs" : "0.08", "Dist::Zilla::Plugin::Test::Pod::No404s" : "1.003", "Dist::Zilla::Plugin::Test::PodSpelling" : "2.006003", "Dist::Zilla::Plugin::Test::Portability" : "2.000007", "Dist::Zilla::Plugin::Test::ReportPrereqs" : "0.022", "Dist::Zilla::Plugin::TestRelease" : "0", "Dist::Zilla::Plugin::UploadToCPAN" : "0", "Dist::Zilla::Plugin::UseUnsafeInc" : "0", "Dist::Zilla::PluginBundle::Author::ETHER" : "0.136", "Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007", "Software::License::MIT" : "0" } } }, "provides" : { "Try::Tiny" : { "file" : "lib/Try/Tiny.pm", "version" : "0.31" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-Try-Tiny@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=Try-Tiny" }, "homepage" : "https://github.com/p5sagit/Try-Tiny", "repository" : { "type" : "git", "url" : "https://github.com/p5sagit/Try-Tiny.git", "web" : "https://github.com/p5sagit/Try-Tiny" } }, "version" : "0.31", "x_Dist_Zilla" : { "perl" : { "version" : "5.035006" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::FileFinder::Filter", "name" : "all_files_but_using_5.10_features", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Author::ETHER/pluginbundle version", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::Author::ETHER" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::ETHER/stale modules, build", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::FileFinder::ByName", "name" : "@Author::ETHER/Examples", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "CONTRIBUTING", "INSTALL", "LICENCE", "README.pod" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@Author::ETHER/Git::GatherDir", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::ETHER/MetaYAML", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::ETHER/MetaJSON", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Readme", "name" : "@Author::ETHER/Readme", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::ETHER/Manifest", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::ETHER/License", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::GenerateFile::FromShareDir", "config" : { "Dist::Zilla::Plugin::GenerateFile::FromShareDir" : { "destination_filename" : "CONTRIBUTING", "dist" : "Dist-Zilla-PluginBundle-Author-ETHER", "encoding" : "UTF-8", "has_xs" : 0, "location" : "build", "source_filename" : "CONTRIBUTING" }, "Dist::Zilla::Role::RepoFileInjector" : { "allow_overwrite" : 1, "repo_root" : ".", "version" : "0.009" } }, "name" : "@Author::ETHER/generate CONTRIBUTING", "version" : "0.015" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.006" } }, "name" : "@Author::ETHER/InstallGuide", "version" : "1.200014" }, { "class" : "Dist::Zilla::Plugin::Test::Compile", "config" : { "Dist::Zilla::Plugin::Test::Compile" : { "bail_out_on_fail" : 1, "fail_on_warning" : "author", "fake_home" : 0, "filename" : "xt/author/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "develop", "script_finder" : [ ":PerlExecFiles", "@Author::ETHER/Examples" ], "skips" : [], "switch" : [] } }, "name" : "@Author::ETHER/Test::Compile", "version" : "2.058" }, { "class" : "Dist::Zilla::Plugin::Test::NoTabs", "config" : { "Dist::Zilla::Plugin::Test::NoTabs" : { "filename" : "xt/author/no-tabs.t", "finder" : [ ":InstallModules", ":ExecFiles", "@Author::ETHER/Examples", ":TestFiles", ":ExtraTestFiles" ] } }, "name" : "@Author::ETHER/Test::NoTabs", "version" : "0.15" }, { "class" : "Dist::Zilla::Plugin::Test::EOL", "config" : { "Dist::Zilla::Plugin::Test::EOL" : { "filename" : "xt/author/eol.t", "finder" : [ ":ExecFiles", ":ExtraTestFiles", ":InstallModules", ":TestFiles", "@Author::ETHER/Examples" ], "trailing_whitespace" : 1 } }, "name" : "@Author::ETHER/Test::EOL", "version" : "0.19" }, { "class" : "Dist::Zilla::Plugin::MetaTests", "name" : "@Author::ETHER/MetaTests", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Test::CPAN::Changes", "config" : { "Dist::Zilla::Plugin::Test::CPAN::Changes" : { "changelog" : "Changes" } }, "name" : "@Author::ETHER/Test::CPAN::Changes", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "@Author::ETHER/Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Test::MinimumVersion", "config" : { "Dist::Zilla::Plugin::Test::MinimumVersion" : { "max_target_perl" : "5.006" } }, "name" : "@Author::ETHER/Test::MinimumVersion", "version" : "2.000010" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::ETHER/PodSyntaxTests", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::PodCoverageTests", "name" : "@Author::ETHER/PodCoverageTests", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Test::PodSpelling", "config" : { "Dist::Zilla::Plugin::Test::PodSpelling" : { "directories" : [ "examples", "lib", "script", "t", "xt" ], "spell_cmd" : "", "stopwords" : [ "irc" ], "wordlist" : "Pod::Wordlist" } }, "name" : "@Author::ETHER/Test::PodSpelling", "version" : "2.007005" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::No404s", "name" : "@Author::ETHER/Test::Pod::No404s", "version" : "1.004" }, { "class" : "Dist::Zilla::Plugin::Test::Kwalitee", "config" : { "Dist::Zilla::Plugin::Test::Kwalitee" : { "filename" : "xt/author/kwalitee.t", "skiptest" : [] } }, "name" : "@Author::ETHER/Test::Kwalitee", "version" : "2.12" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "@Author::ETHER/MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Author::ETHER/Test::ReportPrereqs", "version" : "0.028" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "@Author::ETHER/Test::Portability", "version" : "2.001000" }, { "class" : "Dist::Zilla::Plugin::Git::Describe", "name" : "@Author::ETHER/Git::Describe", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "config_plugins" : [ "@Author::ETHER" ], "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@Author::ETHER/EnsurePod5", "version" : "4.018" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@Author::ETHER/H1Nester", "version" : "4.018" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Author::ETHER/SingleEncoding", "version" : "4.018" }, { "class" : "Pod::Weaver::Plugin::Transformer", "name" : "@Author::ETHER/List", "version" : "4.018" }, { "class" : "Pod::Weaver::Plugin::Transformer", "name" : "@Author::ETHER/Verbatim", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/header", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Author::ETHER/Name", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Author::ETHER/Version", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/prelude", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "TYPES", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Author::ETHER/Leftovers", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/postlude", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::GenerateSection", "name" : "@Author::ETHER/generate SUPPORT", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "@Author::ETHER/allow override SUPPORT", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Author::ETHER/Authors", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "@Author::ETHER/allow override AUTHOR", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Contributors", "name" : "@Author::ETHER/Contributors", "version" : "0.009" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Author::ETHER/Legal", "version" : "4.018" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/footer", "version" : "4.018" } ] } }, "name" : "@Author::ETHER/PodWeaver", "version" : "4.009" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@Author::ETHER/GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::AutoMetaResources", "name" : "@Author::ETHER/AutoMetaResources", "version" : "1.21" }, { "class" : "Dist::Zilla::Plugin::Authority", "name" : "@Author::ETHER/Authority", "version" : "1.009" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Author::ETHER/MetaNoIndex", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Package", "config" : { "Dist::Zilla::Plugin::MetaProvides::Package" : { "finder" : [ ":InstallModules" ], "finder_objects" : [ { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.024" } ], "include_underscores" : 0 }, "Dist::Zilla::Role::MetaProvider::Provider" : { "$Dist::Zilla::Role::MetaProvider::Provider::VERSION" : "2.002004", "inherit_missing" : 0, "inherit_version" : 0, "meta_noindex" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.006" } }, "name" : "@Author::ETHER/MetaProvides::Package", "version" : "2.004003" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::ETHER/MetaConfig", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Keywords", "config" : { "Dist::Zilla::Plugin::Keywords" : { "keywords" : [] } }, "name" : "@Author::ETHER/Keywords", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::UseUnsafeInc", "config" : { "Dist::Zilla::Plugin::UseUnsafeInc" : { "dot_in_INC" : 0 } }, "name" : "@Author::ETHER/UseUnsafeInc", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "@Author::ETHER/AutoPrereqs", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Prereqs::AuthorDeps", "name" : "@Author::ETHER/Prereqs::AuthorDeps", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::MinimumPerl", "name" : "@Author::ETHER/MinimumPerl", "version" : "1.006" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 9 } }, "name" : "@Author::ETHER/MakeMaker", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.31.1", "include_authors" : 0, "include_releaser" : 1, "order_by" : "commits", "paths" : [] } }, "name" : "@Author::ETHER/Git::Contributors", "version" : "0.036" }, { "class" : "Dist::Zilla::Plugin::StaticInstall", "config" : { "Dist::Zilla::Plugin::StaticInstall" : { "dry_run" : 1, "mode" : "auto" } }, "name" : "@Author::ETHER/StaticInstall", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 9 } }, "name" : "@Author::ETHER/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::CheckSelfDependency", "config" : { "Dist::Zilla::Plugin::CheckSelfDependency" : { "finder" : [ ":InstallModules" ] }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.006" } }, "name" : "@Author::ETHER/CheckSelfDependency", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Run::AfterBuild", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "fatal_errors" : 1, "quiet" : 1, "run" : [ "bash -c \"test -e .ackrc && grep -q -- '--ignore-dir=.latest' .ackrc || echo '--ignore-dir=.latest' >> .ackrc; if [[ `dirname '%d'` != .build ]]; then test -e .ackrc && grep -q -- '--ignore-dir=%d' .ackrc || echo '--ignore-dir=%d' >> .ackrc; fi\"" ], "version" : "0.048" } }, "name" : "@Author::ETHER/.ackrc", "version" : "0.048" }, { "class" : "Dist::Zilla::Plugin::Run::AfterBuild", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "eval" : [ "if ('%d' =~ /^%n-[.[:xdigit:]]+$/) { unlink '.latest'; symlink '%d', '.latest'; }" ], "fatal_errors" : 0, "quiet" : 1, "version" : "0.048" } }, "name" : "@Author::ETHER/.latest", "version" : "0.048" }, { "class" : "Dist::Zilla::Plugin::CheckStrictVersion", "name" : "@Author::ETHER/CheckStrictVersion", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::CheckMetaResources", "name" : "@Author::ETHER/CheckMetaResources", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::EnsureLatestPerl", "config" : { "Dist::Zilla::Plugin::EnsureLatestPerl" : { "Module::CoreList" : "5.20211120" } }, "name" : "@Author::ETHER/EnsureLatestPerl", "version" : "0.008" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 1, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::ETHER/stale modules, release", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." } }, "name" : "@Author::ETHER/initial check", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::Git::CheckFor::MergeConflicts", "config" : { "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." } }, "name" : "@Author::ETHER/Git::CheckFor::MergeConflicts", "version" : "0.014" }, { "class" : "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch", "config" : { "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." } }, "name" : "@Author::ETHER/Git::CheckFor::CorrectBranch", "version" : "0.014" }, { "class" : "Dist::Zilla::Plugin::Git::Remote::Check", "name" : "@Author::ETHER/Git::Remote::Check", "version" : "0.1.2" }, { "class" : "Dist::Zilla::Plugin::CheckPrereqsIndexed", "name" : "@Author::ETHER/CheckPrereqsIndexed", "version" : "0.021" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Author::ETHER/TestRelease", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." } }, "name" : "@Author::ETHER/after tests", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::CheckIssues", "name" : "@Author::ETHER/CheckIssues", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Author::ETHER/UploadToCPAN", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "CONTRIBUTING", "INSTALL", "LICENCE", "LICENSE", "ppport.h" ], "match" : [] } }, "name" : "@Author::ETHER/copy generated files", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "@Author::ETHER/ReadmeAnyFromPod", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Author::ETHER/@Git::VersionManager/pluginbundle version", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 1, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Author::ETHER/@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Author::ETHER/@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Author::ETHER/@Git::VersionManager/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [ "." ], "commit_msg" : "%N-%v%t%n%n%c", "signoff" : 0 }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "CONTRIBUTING", "Changes", "INSTALL", "LICENCE", "README.pod" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::ETHER/@Git::VersionManager/release snapshot", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v0.31", "tag_format" : "v%V", "tag_message" : "v%v%t" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::ETHER/@Git::VersionManager/Git::Tag", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":InstallModules" ], "global" : 1, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Author::ETHER/@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Author::ETHER/@Git::VersionManager/NextRelease", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release", "signoff" : 0 }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::ETHER/@Git::VersionManager/post-release commit", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "x_Dist_Zilla", "type" : "requires" } }, "name" : "@Author::ETHER/@Git::VersionManager/prereqs for @Git::VersionManager", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.31.1", "repo_root" : "." } }, "name" : "@Author::ETHER/Git::Push", "version" : "2.048" }, { "class" : "Dist::Zilla::Plugin::GitHub::Update", "config" : { "Dist::Zilla::Plugin::GitHub::Update" : { "metacpan" : 1 } }, "name" : "@Author::ETHER/GitHub::Update", "version" : "0.48" }, { "class" : "Dist::Zilla::Plugin::Run::AfterRelease", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "fatal_errors" : 0, "quiet" : 0, "run" : [ "REDACTED" ], "version" : "0.048" } }, "name" : "@Author::ETHER/install release", "version" : "0.048" }, { "class" : "Dist::Zilla::Plugin::Run::AfterRelease", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "eval" : [ "print \"release complete!\\xa\"" ], "fatal_errors" : 1, "quiet" : 1, "version" : "0.048" } }, "name" : "@Author::ETHER/release complete", "version" : "0.048" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::ETHER/ConfirmRelease", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "x_Dist_Zilla", "type" : "requires" } }, "name" : "@Author::ETHER/prereqs for @Author::ETHER", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "Substitute", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Prereqs::Soften", "config" : { "Dist::Zilla::Plugin::Prereqs::Soften" : { "copy_to" : [ "develop.requires" ], "modules" : [ "Capture::Tiny", "Sub::Name", "Sub::Util" ], "modules_from_features" : null, "to_relationship" : "suggests" } }, "name" : "Prereqs::Soften", "version" : "0.006003" }, { "class" : "Dist::Zilla::Plugin::OnlyCorePrereqs", "config" : { "Dist::Zilla::Plugin::OnlyCorePrereqs" : { "also_disallow" : [], "check_dual_life_versions" : "0", "deprecated_ok" : 0, "phases" : [ "configure", "build", "runtime", "test" ], "skips" : [], "starting_version" : "to be determined from perl prereq" } }, "name" : "OnlyCorePrereqs", "version" : "0.024" }, { "class" : "Dist::Zilla::Plugin::Breaks", "name" : "Breaks", "version" : "0.004" }, { "class" : "Dist::Zilla::Plugin::Test::CheckBreaks", "config" : { "Dist::Zilla::Plugin::Test::CheckBreaks" : { "conflicts_module" : [], "no_forced_deps" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.006" } }, "name" : "Test::CheckBreaks", "version" : "0.019" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.024" }, { "class" : "Dist::Zilla::Plugin::VerifyPhases", "name" : "@Author::ETHER/PHASE VERIFICATION", "version" : "0.016" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.024" } }, "x_authority" : "cpan:NUFFIN", "x_breaks" : { "Try::Tiny::Except" : "<= 0.01" }, "x_contributors" : [ "Karen Etheridge ", "Peter Rabbitson ", "Ricardo Signes ", "Mark Fowler ", "Graham Knop ", "Aristotle Pagaltzis ", "Dagfinn Ilmari MannsÃ¥ker ", "Lukas Mai ", "Alex ", "anaxagoras ", "Andrew Yates ", "awalker ", "chromatic ", "cm-perl ", "David Lowe ", "Glenn Fowler ", "Hans Dieter Pearcey ", "Jens Berthold ", "Jonathan Yu ", "Marc Mims ", "Mark Stosberg ", "Pali ", "Paul Howarth ", "Rudolf Leermakers " ], "x_generated_by_perl" : "v5.35.6", "x_serialization_backend" : "Cpanel::JSON::XS version 4.27", "x_spdx_expression" : "MIT", "x_use_unsafe_inc" : 0 } PK!”JjGÚÚDperl5/x86_64-linux-thread-multi/.meta/FFI-CheckLib-0.27/install.jsonnuÏÃ6Ç${"provides":{"FFI::CheckLib":{"version":0.27,"file":"lib/FFI/CheckLib.pm"}},"target":"FFI::CheckLib","version":0.27,"name":"FFI::CheckLib","dist":"FFI-CheckLib-0.27","pathname":"P/PL/PLICEASE/FFI-CheckLib-0.27.tar.gz"}PK!¤€«³ ³ Cperl5/x86_64-linux-thread-multi/.meta/FFI-CheckLib-0.27/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Check that a library is available for FFI", "author" : [ "Graham Ollis " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.014, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "FFI-CheckLib", "no_index" : { "directory" : [ "corpus" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "FindBin" : "0", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.98", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Pod::Spelling::CommonMistakes" : "0", "Test::Spelling" : "0", "Test::Strict" : "0", "YAML" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } }, "test" : { "requires" : { "Test2::API" : "1.302015", "Test2::Require::EnvVar" : "0.000060", "Test2::Require::Module" : "0.000060", "Test2::V0" : "0.000060" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/Perl5-FFI/FFI-CheckLib/issues" }, "homepage" : "https://metacpan.org/pod/FFI::CheckLib", "repository" : { "type" : "git", "url" : "git://github.com/Perl5-FFI/FFI-CheckLib.git", "web" : "https://github.com/Perl5-FFI/FFI-CheckLib" }, "x_IRC" : "irc://irc.perl.org/#native" }, "version" : "0.27", "x_contributors" : [ "Graham Ollis ", "Bakkiaraj Murugesan (bakkiaraj)", "Dan Book (grinnz, DBOOK)", "Ilya Pavlov (Ilya, ILUX)", "Shawn Laffan (SLAFFAN)", "Petr Pisar (ppisar)" ], "x_generated_by_perl" : "v5.30.0", "x_serialization_backend" : "JSON::XS version 4.02", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_use_unsafe_inc" : 0 } PK!äðý˜Eperl5/x86_64-linux-thread-multi/.meta/local-lib-2.000029/install.jsonnuÏÃ6Ç${"dist":"local-lib-2.000029","target":"local::lib","name":"local::lib","provides":{"lib::core::only":{"file":"lib/lib/core/only.pm"},"local::lib":{"file":"lib/local/lib.pm","version":2.000029}},"pathname":"H/HA/HAARG/local-lib-2.000029.tar.gz","version":2.000029}PK!ˆÕBDperl5/x86_64-linux-thread-multi/.meta/local-lib-2.000029/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "create and use a local lib/ for perl modules with PERL5LIB", "author" : [ "mst - Matt S. Trout (cpan:MSTROUT) " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "local-lib", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : {} }, "configure" : { "requires" : {} }, "develop" : { "requires" : { "Capture::Tiny" : "0", "Module::Build" : "0.36", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::More" : "0.8101", "Test::NoTabs" : "0", "Test::Pod" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } }, "test" : { "requires" : { "Test::More" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-local-lib@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=local-lib" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "git://github.com/Perl-Toolchain-Gang/local-lib", "web" : "https://github.com/Perl-Toolchain-Gang/local-lib" }, "x_IRC" : "irc://irc.perl.org/#local-lib" }, "version" : "2.000029", "x_serialization_backend" : "JSON::PP version 4.07" } PK!h†žÉ>perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.14/install.jsonnuÏÃ6Ç${"provides":{"IO::Tty::Constant":{"version":1.14,"file":"Tty/Constant.pm"},"IO::Pty":{"version":1.14,"file":"Pty.pm"},"IO::Tty":{"version":1.14,"file":"Tty.pm"}},"target":"IO::Tty","version":1.14,"name":"IO::Tty","dist":"IO-Tty-1.14","pathname":"T/TO/TODDR/IO-Tty-1.14.tar.gz"}PK!‹¤+ÈÈ=perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.14/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Pseudo ttys and constants", "author" : [ "Roland Giersig " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "IO-Tty", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "url" : "https://github.com/toddr/IO-Tty" } }, "version" : "1.14", "x_serialization_backend" : "JSON::PP version 4.02" } PK!õÍ«ªª>perl5/x86_64-linux-thread-multi/.meta/Net-IP-1.26/install.jsonnuÏÃ6Ç${"provides":{"Net::IP":{"version":1.26,"file":"IP.pm"}},"target":"Net::IP","version":1.26,"name":"Net::IP","dist":"Net-IP-1.26","pathname":"M/MA/MANU/Net-IP-1.26.tar.gz"}PK!J8aa=perl5/x86_64-linux-thread-multi/.meta/Net-IP-1.26/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Perl extension for manipulating IPv4/IPv6 addresses", "author" : [ "Manuel Valente " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 6.57_05, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Net-IP", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : {} } }, "release_status" : "stable", "version" : "1.26" } PK!¥»�||Aperl5/x86_64-linux-thread-multi/.meta/version-0.9928/install.jsonnuÏÃ6Ç${"provides":{"version::regex":{"version":0.9928,"file":"lib/version/regex.pm"},"version::vxs":{"version":0.9928,"file":"vutil/lib/version/vxs.pm"},"version":{"version":0.9928,"file":"lib/version.pm"},"version::vpp":{"version":0.9928,"file":"vperl/vpp.pm"}},"target":"version","version":0.9928,"name":"version","dist":"version-0.9928","pathname":"L/LE/LEONT/version-0.9928.tar.gz"}PK!Ë�›ññ@perl5/x86_64-linux-thread-multi/.meta/version-0.9928/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Structured version objects", "author" : [ "John Peacock " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.44, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "version", "no_index" : { "directory" : [ "t", "inc" ], "package" : [ "charstar" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006002" } }, "test" : { "requires" : { "File::Temp" : "0.13", "Test::More" : "0.45", "base" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-version@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=version" }, "repository" : { "type" : "git", "url" : "git://github.com/Perl/version.pm.git", "web" : "https://github.com/Perl/version.pm" } }, "version" : "0.9928", "x_serialization_backend" : "JSON::PP version 4.04" } PK!ðª¤ssAperl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.46/install.jsonnuÏÃ6Ç${"target":"YAML::Syck","provides":{"YAML::Dumper::Syck":{"file":"lib/YAML/Dumper/Syck.pm"},"YAML::Syck":{"version":"1.46","file":"lib/YAML/Syck.pm"},"JSON::Syck":{"file":"lib/JSON/Syck.pm","version":"1.46"},"YAML::Loader::Syck":{"file":"lib/YAML/Loader/Syck.pm"}},"version":"1.46","name":"YAML::Syck","dist":"YAML-Syck-1.46","pathname":"T/TO/TODDR/YAML-Syck-1.46.tar.gz"}PK!úpææ@perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.46/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Fast, lightweight YAML loader and dumper", "author" : [ "Todd Rinaldo " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "YAML-Syck", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } } }, "provides" : { "JSON::Syck" : { "file" : "lib/JSON/Syck.pm", "version" : "1.46" }, "YAML::Dumper::Syck" : { "file" : "lib/YAML/Dumper/Syck.pm" }, "YAML::Loader::Syck" : { "file" : "lib/YAML/Loader/Syck.pm" }, "YAML::Syck" : { "file" : "lib/YAML/Syck.pm", "version" : "1.46" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/YAML-Syck/issues" }, "homepage" : "https://github.com/toddr/YAML-Syck", "license" : [ "https://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "https://github.com/toddr/YAML-Syck.git", "web" : "https://github.com/toddr/YAML-Syck" } }, "version" : "1.46", "x_serialization_backend" : "JSON::PP version 4.16" } PK!„ìâb b Jperl5/x86_64-linux-thread-multi/.meta/ExtUtils-MakeMaker-7.50/install.jsonnuÏÃ6Ç${"provides":{"MY":{"version":"7.50","file":"lib/ExtUtils/MakeMaker.pm"},"ExtUtils::MM_MacOS":{"version":"7.50","file":"lib/ExtUtils/MM_MacOS.pm"},"ExtUtils::Command":{"version":"7.50","file":"lib/ExtUtils/Command.pm"},"ExtUtils::MM":{"version":"7.50","file":"lib/ExtUtils/MM.pm"},"MM":{"version":"7.50","file":"lib/ExtUtils/MM.pm"},"ExtUtils::MM_UWIN":{"version":"7.50","file":"lib/ExtUtils/MM_UWIN.pm"},"ExtUtils::MM_NW5":{"version":"7.50","file":"lib/ExtUtils/MM_NW5.pm"},"ExtUtils::Mksymlists":{"version":"7.50","file":"lib/ExtUtils/Mksymlists.pm"},"ExtUtils::MM_QNX":{"version":"7.50","file":"lib/ExtUtils/MM_QNX.pm"},"ExtUtils::MakeMaker::Config":{"version":"7.50","file":"lib/ExtUtils/MakeMaker/Config.pm"},"ExtUtils::MakeMaker::version::regex":{"version":"7.50","file":"lib/ExtUtils/MakeMaker/version/regex.pm"},"ExtUtils::MM_Unix":{"version":"7.50","file":"lib/ExtUtils/MM_Unix.pm"},"ExtUtils::MM_Darwin":{"version":"7.50","file":"lib/ExtUtils/MM_Darwin.pm"},"ExtUtils::MM_OS390":{"version":"7.50","file":"lib/ExtUtils/MM_OS390.pm"},"ExtUtils::MakeMaker":{"version":"7.50","file":"lib/ExtUtils/MakeMaker.pm"},"ExtUtils::MM_Win32":{"version":"7.50","file":"lib/ExtUtils/MM_Win32.pm"},"ExtUtils::MM_VOS":{"version":"7.50","file":"lib/ExtUtils/MM_VOS.pm"},"ExtUtils::testlib":{"version":"7.50","file":"lib/ExtUtils/testlib.pm"},"ExtUtils::MakeMaker::version":{"version":"7.50","file":"lib/ExtUtils/MakeMaker/version.pm"},"ExtUtils::Command::MM":{"version":"7.50","file":"lib/ExtUtils/Command/MM.pm"},"ExtUtils::MM_BeOS":{"version":"7.50","file":"lib/ExtUtils/MM_BeOS.pm"},"ExtUtils::MM_Any":{"version":"7.50","file":"lib/ExtUtils/MM_Any.pm"},"ExtUtils::MakeMaker::version::vpp":{"version":"7.50","file":"lib/ExtUtils/MakeMaker/version/vpp.pm"},"ExtUtils::MM_VMS":{"version":"7.50","file":"lib/ExtUtils/MM_VMS.pm"},"ExtUtils::MY":{"version":"7.50","file":"lib/ExtUtils/MY.pm"},"ExtUtils::MM_Cygwin":{"version":"7.50","file":"lib/ExtUtils/MM_Cygwin.pm"},"ExtUtils::MM_DOS":{"version":"7.50","file":"lib/ExtUtils/MM_DOS.pm"},"ExtUtils::MakeMaker::_version":{"version":"7.50","file":"lib/ExtUtils/MM_Unix.pm"},"ExtUtils::Liblist::Kid":{"version":"7.50","file":"lib/ExtUtils/Liblist/Kid.pm"},"ExtUtils::MM_OS2":{"version":"7.50","file":"lib/ExtUtils/MM_OS2.pm"},"ExtUtils::MakeMaker::Locale":{"version":"7.50","file":"lib/ExtUtils/MakeMaker/Locale.pm"},"ExtUtils::MM_Win95":{"version":"7.50","file":"lib/ExtUtils/MM_Win95.pm"},"ExtUtils::MakeMaker::charstar":{"version":"7.50","file":"lib/ExtUtils/MakeMaker/version/vpp.pm"},"ExtUtils::MM_AIX":{"version":"7.50","file":"lib/ExtUtils/MM_AIX.pm"},"ExtUtils::Liblist":{"version":"7.50","file":"lib/ExtUtils/Liblist.pm"},"ExtUtils::Mkbootstrap":{"version":"7.50","file":"lib/ExtUtils/Mkbootstrap.pm"}},"target":"ExtUtils::MakeMaker","version":"7.50","name":"ExtUtils::MakeMaker","dist":"ExtUtils-MakeMaker-7.50","pathname":"B/BI/BINGOS/ExtUtils-MakeMaker-7.50.tar.gz"}PK!†½æ€Iperl5/x86_64-linux-thread-multi/.meta/ExtUtils-MakeMaker-7.50/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Create a module Makefile", "author" : [ "Michael G Schwern " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.50, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "ExtUtils-MakeMaker", "no_index" : { "directory" : [ "t", "inc", "bundled", "my" ], "package" : [ "DynaLoader", "in", "version" ] }, "prereqs" : { "build" : { "requires" : {} }, "configure" : { "requires" : {} }, "runtime" : { "requires" : { "Data::Dumper" : "0", "Encode" : "0", "File::Basename" : "0", "File::Spec" : "0.8", "Pod::Man" : "0", "perl" : "5.006" } }, "test" : { "requires" : {} } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "http://rt.cpan.org/NoAuth/Bugs.html?Dist=ExtUtils-MakeMaker" }, "homepage" : "https://metacpan.org/release/ExtUtils-MakeMaker", "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "http://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker" }, "x_MailingList" : "makemaker@perl.org" }, "version" : "7.50" } PK!Q ‡‡Cperl5/x86_64-linux-thread-multi/.meta/IO-Stringy-2.113/install.jsonnuÏÃ6Ç${"provides":{"IO::WrapTie":{"version":"2.113","file":"lib/IO/WrapTie.pm"},"IO::Stringy":{"version":"2.113","file":"lib/IO/Stringy.pm"},"IO::Scalar":{"version":"2.113","file":"lib/IO/Scalar.pm"},"IO::ScalarArray":{"version":"2.113","file":"lib/IO/ScalarArray.pm"},"IO::InnerFile":{"version":"2.113","file":"lib/IO/InnerFile.pm"},"IO::Wrap":{"version":"2.113","file":"lib/IO/Wrap.pm"},"IO::Lines":{"version":"2.113","file":"lib/IO/Lines.pm"},"IO::AtomicFile":{"version":"2.113","file":"lib/IO/AtomicFile.pm"}},"target":"IO::Scalar","version":"2.113","name":"IO::Stringy","dist":"IO-Stringy-2.113","pathname":"C/CA/CAPOEIRAB/IO-Stringy-2.113.tar.gz"}PK!%ý,ŸïLïLBperl5/x86_64-linux-thread-multi/.meta/IO-Stringy-2.113/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "I/O on in-core objects like strings and arrays", "author" : [ "Erik Dorfman " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "IO-Stringy", "no_index" : { "directory" : [ "eg", "examples", "inc", "share", "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Dist::Zilla" : "0", "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Test::CPAN::Changes" : "0.4", "Test::CheckManifest" : "1.29", "Test::Kwalitee" : "1.22", "Test::More" : "0.88", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Pod::Spelling::CommonMistakes" : "1.000", "Test::Spelling" : "0.12", "Test::TrailingSpace" : "0", "Test::Version" : "1" } }, "runtime" : { "requires" : { "Carp" : "0", "Exporter" : "5.57", "File::Spec" : "0", "FileHandle" : "0", "IO::File" : "0", "IO::Handle" : "0", "Symbol" : "0", "overload" : "0", "parent" : "0", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Basename" : "0", "File::Spec" : "0", "File::Temp" : "0", "FileHandle" : "0", "IO::File" : "0", "IO::Handle" : "0", "Symbol" : "0", "Test::More" : "0.88", "Test::Tester" : "0", "strict" : "0", "warnings" : "0" } } }, "provides" : { "IO::AtomicFile" : { "file" : "lib/IO/AtomicFile.pm", "version" : "2.113" }, "IO::InnerFile" : { "file" : "lib/IO/InnerFile.pm", "version" : "2.113" }, "IO::Lines" : { "file" : "lib/IO/Lines.pm", "version" : "2.113" }, "IO::Scalar" : { "file" : "lib/IO/Scalar.pm", "version" : "2.113" }, "IO::ScalarArray" : { "file" : "lib/IO/ScalarArray.pm", "version" : "2.113" }, "IO::Stringy" : { "file" : "lib/IO/Stringy.pm", "version" : "2.113" }, "IO::Wrap" : { "file" : "lib/IO/Wrap.pm", "version" : "2.113" }, "IO::WrapTie" : { "file" : "lib/IO/WrapTie.pm", "version" : "2.113" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/genio/IO-Stringy/issues" }, "homepage" : "https://github.com/genio/IO-Stringy", "repository" : { "type" : "git", "url" : "https://github.com/genio/IO-Stringy.git", "web" : "https://github.com/genio/IO-Stringy" } }, "version" : "2.113", "x_Dist_Zilla" : { "perl" : { "version" : "5.030000" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "LICENSE", "META.json", "Makefile.PL", "README.md", "t/00-report-prereqs.t" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "Git::GatherDir", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Starter/MetaYAML", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Starter/MetaJSON", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Starter/License", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Pod2Readme", "name" : "@Starter/Pod2Readme", "version" : "0.004" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Starter/PodSyntaxTests", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Starter/Test::ReportPrereqs", "version" : "0.027" }, { "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" : "xt/author/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "develop", "script_finder" : [ ":PerlExecFiles" ], "skips" : [], "switch" : [] } }, "name" : "@Starter/Test::Compile", "version" : "2.058" }, { "class" : "Dist::Zilla::Plugin::MakeMaker::Awesome", "config" : { "Dist::Zilla::Plugin::MakeMaker" : { "make_path" : "gmake", "version" : "6.012" }, "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1, "version" : "6.012" } }, "name" : "@Starter/MakeMaker::Awesome", "version" : "0.48" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Starter/Manifest", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@Starter/PruneCruft", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::ManifestSkip", "name" : "@Starter/ManifestSkip", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 1 } }, "name" : "@Starter/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 1, "skip_version_provider" : 0 } }, "name" : "@Starter/RewriteVersion", "version" : "0.018" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Starter/NextRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 } }, "name" : "@Starter/BumpVersionAfterRelease", "version" : "0.018" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Starter/TestRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Starter/ConfirmRelease", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Starter/UploadToCPAN", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Starter/MetaConfig", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Starter/MetaNoIndex", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Package", "config" : { "Dist::Zilla::Plugin::MetaProvides::Package" : { "finder_objects" : [ { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "@Starter/MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.012" } ], "include_underscores" : 0 }, "Dist::Zilla::Role::MetaProvider::Provider" : { "$Dist::Zilla::Role::MetaProvider::Provider::VERSION" : "2.002004", "inherit_missing" : 1, "inherit_version" : 1, "meta_noindex" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000036", "version" : "0.006" } }, "name" : "@Starter/MetaProvides::Package", "version" : "2.004003" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@Starter/ShareDir", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@Starter/ExecDir", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "Markdown_Readme", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::Prereqs::FromCPANfile", "name" : "Prereqs::FromCPANfile", "version" : "0.08" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.16.1.windows.1", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.16.1.windows.1", "repo_root" : "." } }, "name" : "@Git/Check", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.16.1.windows.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git/Commit", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v2.113", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.16.1.windows.1", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Git/Tag", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.16.1.windows.1", "repo_root" : "." } }, "name" : "@Git/Push", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::CheckChangeLog", "name" : "CheckChangeLog", "version" : "0.05" }, { "class" : "Dist::Zilla::Plugin::CheckChangesHasContent", "name" : "CheckChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Test::Kwalitee", "config" : { "Dist::Zilla::Plugin::Test::Kwalitee" : { "filename" : "xt/release/kwalitee.t", "skiptest" : [ "no_symlinks" ] } }, "name" : "Test::Kwalitee", "version" : "2.12" }, { "class" : "Dist::Zilla::Plugin::Test::Version", "name" : "Test::Version", "version" : "1.09" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable", "name" : "Test::Pod::Coverage::Configurable", "version" : "0.07" }, { "class" : "Dist::Zilla::Plugin::Test::PodSpelling", "config" : { "Dist::Zilla::Plugin::Test::PodSpelling" : { "directories" : [ "bin", "lib" ], "spell_cmd" : "", "stopwords" : [ "BUF", "Doru", "FOO", "Foo", "NBYTES", "POS", "SCALARREF", "SLAVECLASS", "ZeeGee", "aref", "dfs", "getline", "getlines", "getpos", "ing", "reblessed", "setpos", "sref", "tieable", "wraphandle" ], "wordlist" : "Pod::Wordlist" } }, "name" : "Test::PodSpelling", "version" : "2.007005" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromBuild", "name" : "CopyFilesFromBuild", "version" : "0.170880" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.012" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "@Starter/MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.012" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.012" } }, "x_contributors" : [ "Chase Whitener ", "Dianne Skoll " ], "x_generated_by_perl" : "v5.30.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.11" } PK!ÙØýÕÕEperl5/x86_64-linux-thread-multi/.meta/XML-SAX-Expat-0.51/install.jsonnuÏÃ6Ç${"provides":{"XML::SAX::Expat":{"version":0.51,"file":"Expat.pm"}},"target":"XML::SAX::Expat","version":0.51,"name":"XML::SAX::Expat","dist":"XML-SAX-Expat-0.51","pathname":"B/BJ/BJOERN/XML-SAX-Expat-0.51.tar.gz"}PK!Z-ñkkDperl5/x86_64-linux-thread-multi/.meta/XML-SAX-Expat-0.51/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "SAX Driver for Expat", "author" : [ "Robin Berjon" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 6.6302, CPAN::Meta::Converter version 2.132830, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-SAX-Expat", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "XML::NamespaceSupport" : "0.03", "XML::Parser" : "2.27", "XML::SAX" : "0.03", "XML::SAX::Base" : "1.00" } } }, "release_status" : "stable", "resources" : { "repository" : { "url" : "https://github.com/hoehrmann/XML-SAX-Expat" } }, "version" : "0.51" } PK!—ZÁèÉÉCperl5/x86_64-linux-thread-multi/.meta/Alien-Build-2.83/install.jsonnuÏÃ6Ç${"version":2.83,"name":"Alien::Build","dist":"Alien-Build-2.83","target":"Alien::Build::MM","pathname":"P/PL/PLICEASE/Alien-Build-2.83.tar.gz","provides":{"Alien::Build::Plugin::PkgConfig::Negotiate":{"version":2.83,"file":"lib/Alien/Build/Plugin/PkgConfig/Negotiate.pm"},"Alien::Build::Plugin::Fetch::CurlCommand":{"version":2.83,"file":"lib/Alien/Build/Plugin/Fetch/CurlCommand.pm"},"Alien::Build::Plugin::Digest::SHAPP":{"version":2.83,"file":"lib/Alien/Build/Plugin/Digest/SHAPP.pm"},"Alien::Build::Plugin::Build::Autoconf":{"version":2.83,"file":"lib/Alien/Build/Plugin/Build/Autoconf.pm"},"Alien::Util":{"version":2.83,"file":"lib/Alien/Util.pm"},"Alien::Build::Plugin::Decode::Mojo":{"version":2.83,"file":"lib/Alien/Build/Plugin/Decode/Mojo.pm"},"Alien::Build::Plugin::Build::SearchDep":{"file":"lib/Alien/Build/Plugin/Build/SearchDep.pm","version":2.83},"Alien::Build::Plugin::Extract::Negotiate":{"version":2.83,"file":"lib/Alien/Build/Plugin/Extract/Negotiate.pm"},"Alien::Build::Log":{"version":2.83,"file":"lib/Alien/Build/Log.pm"},"Alien::Build::Plugin::Core::Tail":{"file":"lib/Alien/Build/Plugin/Core/Tail.pm","version":2.83},"Alien::Build::Plugin::Extract::ArchiveTar":{"version":2.83,"file":"lib/Alien/Build/Plugin/Extract/ArchiveTar.pm"},"Alien::Build::Log::Abbreviate":{"file":"lib/Alien/Build/Log/Abbreviate.pm","version":2.83},"Alien::Build::Plugin":{"file":"lib/Alien/Build/Plugin.pm","version":2.83},"Alien::Build::Plugin::Prefer::SortVersions":{"version":2.83,"file":"lib/Alien/Build/Plugin/Prefer/SortVersions.pm"},"Alien::Build::MM":{"file":"lib/Alien/Build/MM.pm","version":2.83},"Alien::Build::Plugin::Build::MSYS":{"version":2.83,"file":"lib/Alien/Build/Plugin/Build/MSYS.pm"},"Alien::Build::Plugin::PkgConfig::CommandLine":{"version":2.83,"file":"lib/Alien/Build/Plugin/PkgConfig/CommandLine.pm"},"Alien::Build::CommandSequence":{"version":2.83,"file":"lib/Alien/Build/CommandSequence.pm"},"Alien::Build::Plugin::Digest::Negotiate":{"file":"lib/Alien/Build/Plugin/Digest/Negotiate.pm","version":2.83},"Alien::Build::Util":{"version":2.83,"file":"lib/Alien/Build/Util.pm"},"Alien::Build::Plugin::Decode::HTML":{"version":2.83,"file":"lib/Alien/Build/Plugin/Decode/HTML.pm"},"Alien::Build::Meta":{"version":2.83,"file":"lib/Alien/Build.pm"},"Alien::Build::Plugin::Extract::Directory":{"version":2.83,"file":"lib/Alien/Build/Plugin/Extract/Directory.pm"},"Alien::Build::Plugin::Decode::DirListing":{"version":2.83,"file":"lib/Alien/Build/Plugin/Decode/DirListing.pm"},"Alien::Base::PkgConfig":{"file":"lib/Alien/Base/PkgConfig.pm","version":2.83},"Alien::Build::Plugin::PkgConfig::PP":{"file":"lib/Alien/Build/Plugin/PkgConfig/PP.pm","version":2.83},"Alien::Build::Plugin::PkgConfig::MakeStatic":{"version":2.83,"file":"lib/Alien/Build/Plugin/PkgConfig/MakeStatic.pm"},"Alien::Build::Plugin::Build::Copy":{"version":2.83,"file":"lib/Alien/Build/Plugin/Build/Copy.pm"},"Alien::Build::TempDir":{"version":2.83,"file":"lib/Alien/Build.pm"},"Alien::Build::Plugin::Fetch::LWP":{"version":2.83,"file":"lib/Alien/Build/Plugin/Fetch/LWP.pm"},"Alien::Build::Plugin::Digest::SHA":{"file":"lib/Alien/Build/Plugin/Digest/SHA.pm","version":2.83},"Alien::Build::Plugin::Core::Setup":{"version":2.83,"file":"lib/Alien/Build/Plugin/Core/Setup.pm"},"Alien::Build::Plugin::Prefer::BadVersion":{"version":2.83,"file":"lib/Alien/Build/Plugin/Prefer/BadVersion.pm"},"Alien::Build::Plugin::Decode::DirListingFtpcopy":{"file":"lib/Alien/Build/Plugin/Decode/DirListingFtpcopy.pm","version":2.83},"Alien::Build::Plugin::Probe::Vcpkg":{"version":2.83,"file":"lib/Alien/Build/Plugin/Probe/Vcpkg.pm"},"Alien::Build::Plugin::Extract::ArchiveZip":{"file":"lib/Alien/Build/Plugin/Extract/ArchiveZip.pm","version":2.83},"Alien::Build::Plugin::Test::Mock":{"file":"lib/Alien/Build/Plugin/Test/Mock.pm","version":2.83},"Alien::Build::Log::Default":{"file":"lib/Alien/Build/Log/Default.pm","version":2.83},"Alien::Build::Helper":{"version":2.83,"file":"lib/Alien/Build/Interpolate.pm"},"Test::Alien::Build":{"version":2.83,"file":"lib/Test/Alien/Build.pm"},"Alien::Build::Plugin::Build::Make":{"version":2.83,"file":"lib/Alien/Build/Plugin/Build/Make.pm"},"Alien::Build::Plugin::Gather::IsolateDynamic":{"version":2.83,"file":"lib/Alien/Build/Plugin/Gather/IsolateDynamic.pm"},"Alien::Build::Version::Basic":{"file":"lib/Alien/Build/Version/Basic.pm","version":2.83},"Alien::Build::Plugin::Probe::CBuilder":{"file":"lib/Alien/Build/Plugin/Probe/CBuilder.pm","version":2.83},"Alien::Base::Wrapper":{"version":2.83,"file":"lib/Alien/Base/Wrapper.pm"},"Test::Alien::CanCompile":{"version":2.83,"file":"lib/Test/Alien/CanCompile.pm"},"Alien::Build::Plugin::Core::Legacy":{"version":2.83,"file":"lib/Alien/Build/Plugin/Core/Legacy.pm"},"Alien::Build::Plugin::Fetch::HTTPTiny":{"version":2.83,"file":"lib/Alien/Build/Plugin/Fetch/HTTPTiny.pm"},"Test::Alien::Synthetic":{"file":"lib/Test/Alien/Synthetic.pm","version":2.83},"Alien::Role":{"version":2.83,"file":"lib/Alien/Role.pm"},"Test::Alien":{"file":"lib/Test/Alien.pm","version":2.83},"Alien::Build::Plugin::Core::Gather":{"version":2.83,"file":"lib/Alien/Build/Plugin/Core/Gather.pm"},"Alien::Build::Plugin::Build::CMake":{"file":"lib/Alien/Build/Plugin/Build/CMake.pm","version":2.83},"Alien::Build::Plugin::Extract::CommandLine":{"version":2.83,"file":"lib/Alien/Build/Plugin/Extract/CommandLine.pm"},"Alien::Build::Temp":{"file":"lib/Alien/Build/Temp.pm","version":2.83},"Test::Alien::CanPlatypus":{"version":2.83,"file":"lib/Test/Alien/CanPlatypus.pm"},"Alien::Build::Plugin::Fetch::Local":{"version":2.83,"file":"lib/Alien/Build/Plugin/Fetch/Local.pm"},"Alien::Base":{"version":2.83,"file":"lib/Alien/Base.pm"},"Test::Alien::Run":{"file":"lib/Test/Alien/Run.pm","version":2.83},"Alien::Build::Plugin::Download::Negotiate":{"file":"lib/Alien/Build/Plugin/Download/Negotiate.pm","version":2.83},"Alien::Build::Plugin::Fetch::NetFTP":{"file":"lib/Alien/Build/Plugin/Fetch/NetFTP.pm","version":2.83},"Alien::Build::Plugin::Core::Download":{"version":2.83,"file":"lib/Alien/Build/Plugin/Core/Download.pm"},"Alien::Build::Interpolate::Helper":{"file":"lib/Alien/Build/Interpolate.pm","version":2.83},"Alien::Build::Interpolate":{"file":"lib/Alien/Build/Interpolate.pm","version":2.83},"Alien::Build::Plugin::Fetch::LocalDir":{"file":"lib/Alien/Build/Plugin/Fetch/LocalDir.pm","version":2.83},"Alien::Build::PluginMeta":{"version":2.83,"file":"lib/Alien/Build/Plugin.pm"},"Test::Alien::Diag":{"version":2.83,"file":"lib/Test/Alien/Diag.pm"},"Alien::Build::Plugin::Core::FFI":{"version":2.83,"file":"lib/Alien/Build/Plugin/Core/FFI.pm"},"Alien::Build::rc":{"file":"lib/Alien/Build.pm","version":2.83},"Alien::Build::Plugin::Probe::CommandLine":{"version":2.83,"file":"lib/Alien/Build/Plugin/Probe/CommandLine.pm"},"Alien::Build::Plugin::Core::CleanInstall":{"file":"lib/Alien/Build/Plugin/Core/CleanInstall.pm","version":2.83},"Alien::Build::Interpolate::Default":{"version":2.83,"file":"lib/Alien/Build/Interpolate/Default.pm"},"Alien::Build::Plugin::Core::Override":{"version":2.83,"file":"lib/Alien/Build/Plugin/Core/Override.pm"},"Alien::Build::Plugin::Extract::File":{"file":"lib/Alien/Build/Plugin/Extract/File.pm","version":2.83},"Alien::Build::Plugin::Fetch::Wget":{"file":"lib/Alien/Build/Plugin/Fetch/Wget.pm","version":2.83},"alienfile":{"version":2.83,"file":"lib/alienfile.pm"},"Alien::Build::Plugin::PkgConfig::LibPkgConf":{"file":"lib/Alien/Build/Plugin/PkgConfig/LibPkgConf.pm","version":2.83},"Alien::Build::Plugin::Prefer::GoodVersion":{"version":2.83,"file":"lib/Alien/Build/Plugin/Prefer/GoodVersion.pm"},"Alien::Build":{"file":"lib/Alien/Build.pm","version":2.83}}}PK!) E–"–"Bperl5/x86_64-linux-thread-multi/.meta/Alien-Build-2.83/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Build external dependencies for use in CPAN", "author" : [ "Graham Ollis ", "Joel Berger " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.025, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Alien-Build", "no_index" : { "directory" : [ "corpus", "example", "maint" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "6.64" } }, "configure" : { "requires" : { "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.64", "ExtUtils::ParseXS" : "3.30", "File::Which" : "0" } }, "develop" : { "recommends" : { "Dist::Zilla::Plugin::Author::Plicease::Thanks" : "0", "Dist::Zilla::Plugin::Author::Plicease::Upload" : "0", "Dist::Zilla::Plugin::DynamicPrereqs" : "0", "Dist::Zilla::Plugin::GatherFile" : "0", "Dist::Zilla::Plugin::MetaNoIndex" : "0", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::PruneFiles" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::PluginBundle::Author::Plicease" : "2.75", "Perl::Critic::Policy::BuiltinFunctions::ProhibitBooleanGrep" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitStringySplit" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidGrep" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidMap" : "0", "Perl::Critic::Policy::ClassHierarchies::ProhibitExplicitISA" : "0", "Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless" : "0", "Perl::Critic::Policy::CodeLayout::ProhibitHardTabs" : "0", "Perl::Critic::Policy::CodeLayout::ProhibitTrailingWhitespace" : "0", "Perl::Critic::Policy::CodeLayout::RequireConsistentNewlines" : "0", "Perl::Critic::Policy::Community::ArrayAssignAref" : "0", "Perl::Critic::Policy::Community::BarewordFilehandles" : "0", "Perl::Critic::Policy::Community::ConditionalDeclarations" : "0", "Perl::Critic::Policy::Community::ConditionalImplicitReturn" : "0", "Perl::Critic::Policy::Community::DeprecatedFeatures" : "0", "Perl::Critic::Policy::Community::DiscouragedModules" : "0", "Perl::Critic::Policy::Community::DollarAB" : "0", "Perl::Critic::Policy::Community::Each" : "0", "Perl::Critic::Policy::Community::EmptyReturn" : "0", "Perl::Critic::Policy::Community::IndirectObjectNotation" : "0", "Perl::Critic::Policy::Community::LexicalForeachIterator" : "0", "Perl::Critic::Policy::Community::LoopOnHash" : "0", "Perl::Critic::Policy::Community::ModPerl" : "0", "Perl::Critic::Policy::Community::OpenArgs" : "0", "Perl::Critic::Policy::Community::OverloadOptions" : "0", "Perl::Critic::Policy::Community::POSIXImports" : "0", "Perl::Critic::Policy::Community::PackageMatchesFilename" : "0", "Perl::Critic::Policy::Community::PreferredAlternatives" : "0", "Perl::Critic::Policy::Community::StrictWarnings" : "0", "Perl::Critic::Policy::Community::Threads" : "0", "Perl::Critic::Policy::Community::Wantarray" : "0", "Perl::Critic::Policy::Community::WarningsSwitch" : "0", "Perl::Critic::Policy::Community::WhileDiamondDefaultAssignment" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitLabelsWithSpecialBlockNames" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitMutatingListFunctions" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitUnreachableCode" : "0", "Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles" : "0", "Perl::Critic::Policy::InputOutput::ProhibitJoinedReadline" : "0", "Perl::Critic::Policy::InputOutput::ProhibitTwoArgOpen" : "0", "Perl::Critic::Policy::Miscellanea::ProhibitFormats" : "0", "Perl::Critic::Policy::Miscellanea::ProhibitUselessNoCritic" : "0", "Perl::Critic::Policy::Modules::ProhibitConditionalUseStatements" : "0", "Perl::Critic::Policy::Modules::RequireNoMatchVarsWithUseEnglish" : "0", "Perl::Critic::Policy::Objects::ProhibitIndirectSyntax" : "0", "Perl::Critic::Policy::RegularExpressions::ProhibitUselessTopic" : "0", "Perl::Critic::Policy::Subroutines::ProhibitNestedSubs" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitLeadingZeros" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitMixedBooleanOperators" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitSpecialLiteralHeredocTerminator" : "0", "Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator" : "0", "Perl::Critic::Policy::Variables::ProhibitPerl4PackageNames" : "0", "Perl::Critic::Policy::Variables::ProhibitUnusedVariables" : "0", "Software::License::Perl_5" : "0" }, "requires" : { "FindBin" : "0", "Perl::Critic" : "0", "Test2::Require::EnvVar" : "0.000121", "Test2::Require::Module" : "0.000121", "Test2::Tools::PerlCritic" : "0", "Test2::V0" : "0.000121", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.98", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Pod::LinkCheck::Lite" : "0", "Test::Spelling" : "0" } }, "runtime" : { "requires" : { "Capture::Tiny" : "0.17", "Digest::SHA" : "0", "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.64", "ExtUtils::ParseXS" : "3.30", "FFI::CheckLib" : "0.11", "File::Which" : "1.10", "File::chdir" : "0", "JSON::PP" : "0", "List::Util" : "1.33", "Path::Tiny" : "0.077", "Test2::API" : "1.302096", "Text::ParseWords" : "3.26", "parent" : "0", "perl" : "5.008004" }, "suggests" : { "Archive::Tar" : "0" } }, "test" : { "requires" : { "Test2::API" : "1.302096", "Test2::V0" : "0.000121" }, "suggests" : { "Devel::Hide" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/PerlAlien/Alien-Build/issues" }, "homepage" : "https://metacpan.org/pod/Alien::Build", "repository" : { "type" : "git", "url" : "git://github.com/PerlAlien/Alien-Build.git", "web" : "https://github.com/PerlAlien/Alien-Build" }, "x_IRC" : "irc://irc.perl.org/#native" }, "version" : "2.83", "x_contributors" : [ "Graham Ollis ", "Diab Jerius (DJERIUS)", "Roy Storey (KIWIROY)", "Ilya Pavlov", "David Mertens (run4flat)", "Mark Nunberg (mordy, mnunberg)", "Christian Walde (Mithaldu)", "Brian Wightman (MidLifeXis)", "Zaki Mughal (zmughal)", "mohawk (mohawk2, ETJ)", "Vikas N Kumar (vikasnkumar)", "Flavio Poletti (polettix)", "Salvador Fandiño (salva)", "Gianni Ceccarelli (dakkar)", "Pavel Shaydo (zwon, trinitum)", "Kang-min Liu (劉康民, gugod)", "Nicholas Shipp (nshp)", "Juan Julián Merelo Guervós (JJ)", "Joel Berger (JBERGER)", "Petr PísaÅ™ (ppisar)", "Lance Wicks (LANCEW)", "Ahmad Fatoum (a3f, ATHREEF)", "José Joaquín Atria (JJATRIA)", "Duke Leto (LETO)", "Shoichi Kaji (SKAJI)", "Shawn Laffan (SLAFFAN)", "Paul Evans (leonerd, PEVANS)", "HÃ¥kon Hægland (hakonhagland, HAKONH)", "nick nauwelaerts (INPHOBIA)", "Florian Weimer" ], "x_generated_by_perl" : "v5.37.4", "x_serialization_backend" : "Cpanel::JSON::XS version 4.32", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_use_unsafe_inc" : 0 } PK!P&ýk44Dperl5/x86_64-linux-thread-multi/.meta/HTTP-Message-6.26/install.jsonnuÏÃ6Ç${"provides":{"HTTP::Headers::Util":{"version":6.26,"file":"lib/HTTP/Headers/Util.pm"},"HTTP::Config":{"version":6.26,"file":"lib/HTTP/Config.pm"},"HTTP::Headers::ETag":{"version":6.26,"file":"lib/HTTP/Headers/ETag.pm"},"HTTP::Status":{"version":6.26,"file":"lib/HTTP/Status.pm"},"HTTP::Message":{"version":6.26,"file":"lib/HTTP/Message.pm"},"HTTP::Request::Common":{"version":6.26,"file":"lib/HTTP/Request/Common.pm"},"HTTP::Headers::Auth":{"version":6.26,"file":"lib/HTTP/Headers/Auth.pm"},"HTTP::Response":{"version":6.26,"file":"lib/HTTP/Response.pm"},"HTTP::Headers":{"version":6.26,"file":"lib/HTTP/Headers.pm"},"HTTP::Request":{"version":6.26,"file":"lib/HTTP/Request.pm"}},"target":"HTTP::Status","version":6.26,"name":"HTTP::Message","dist":"HTTP-Message-6.26","pathname":"O/OA/OALDERS/HTTP-Message-6.26.tar.gz"}PK!>F¥xxCperl5/x86_64-linux-thread-multi/.meta/HTTP-Message-6.26/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "HTTP style message (base class)", "author" : [ "Gisle Aas " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.015, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "HTTP-Message", "no_index" : { "directory" : [ "examples", "t", "xt" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0", "perl" : "5.006" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "requires" : { "Clone" : "0", "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Test::CPAN::Changes" : "0.19", "Test::Mojibake" : "0", "Test::More" : "0.96", "Test::Pod" : "1.41", "Test::Portability::Files" : "0", "Test::Version" : "1", "perl" : "5.006" } }, "runtime" : { "requires" : { "Carp" : "0", "Compress::Raw::Zlib" : "0", "Encode" : "3.01", "Encode::Locale" : "1", "Exporter" : "5.57", "HTTP::Date" : "6", "IO::Compress::Bzip2" : "2.021", "IO::Compress::Deflate" : "0", "IO::Compress::Gzip" : "0", "IO::HTML" : "0", "IO::Uncompress::Bunzip2" : "2.021", "IO::Uncompress::Gunzip" : "0", "IO::Uncompress::Inflate" : "0", "IO::Uncompress::RawInflate" : "0", "LWP::MediaTypes" : "6", "MIME::Base64" : "2.1", "MIME::QuotedPrint" : "0", "URI" : "1.10", "base" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" }, "suggests" : { "Clone" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "PerlIO::encoding" : "0", "Test::More" : "0.88", "Time::Local" : "0", "Try::Tiny" : "0", "lib" : "0", "overload" : "0", "perl" : "5.008001" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/libwww-perl/HTTP-Message/issues" }, "homepage" : "https://github.com/libwww-perl/HTTP-Message", "repository" : { "type" : "git", "url" : "https://github.com/libwww-perl/HTTP-Message.git", "web" : "https://github.com/libwww-perl/HTTP-Message" }, "x_IRC" : "irc://irc.perl.org/#lwp", "x_MailingList" : "mailto:libwww@perl.org" }, "version" : "6.26", "x_Dist_Zilla" : { "perl" : { "version" : "5.030002" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "MetaResources", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "requires" } }, "name" : "Prereqs", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::Author::OALDERS" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, build", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 1, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, release", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::OALDERS::TidyAll", "name" : "@Author::OALDERS/OALDERS::TidyAll", "version" : "0.000028" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "@Author::OALDERS/AutoPrereqs", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::CheckChangesHasContent", "name" : "@Author::OALDERS/CheckChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4" } }, "name" : "@Author::OALDERS/MakeMaker", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::CPANFile", "name" : "@Author::OALDERS/CPANFile", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ContributorsFile", "name" : "@Author::OALDERS/ContributorsFile", "version" : "0.3.0" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::OALDERS/MetaJSON", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::OALDERS/MetaYAML", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::OALDERS/Manifest", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Author::OALDERS/MetaNoIndex", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::OALDERS/MetaConfig", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "@Author::OALDERS/MetaResources", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::OALDERS/License", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000036", "version" : "0.006" } }, "name" : "@Author::OALDERS/InstallGuide", "version" : "1.200013" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@Author::OALDERS/ExecDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "@Author::OALDERS/MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::OALDERS/PodSyntaxTests", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::CPAN::Changes", "config" : { "Dist::Zilla::Plugin::Test::CPAN::Changes" : { "changelog" : "Changes" } }, "name" : "@Author::OALDERS/Test::CPAN::Changes", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "@Author::OALDERS/Test::Portability", "version" : "2.001000" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Author::OALDERS/TestRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Author::OALDERS/Test::ReportPrereqs", "version" : "0.028" }, { "class" : "Dist::Zilla::Plugin::Test::Version", "name" : "@Author::OALDERS/Test::Version", "version" : "1.09" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4" } }, "name" : "@Author::OALDERS/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::MinimumPerl", "name" : "@Author::OALDERS/MinimumPerl", "version" : "1.006" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Default/SingleEncoding", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Default/Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Default/Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Default/Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Default/Authors", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Default/Legal", "version" : "4.015" } ] } }, "name" : "@Author::OALDERS/PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@Author::OALDERS/PruneCruft", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromBuild", "name" : "@Author::OALDERS/CopyFilesFromBuild", "version" : "0.170880" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@Author::OALDERS/GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@Author::OALDERS/Git::GatherDir", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Install" ], "match" : [] } }, "name" : "@Author::OALDERS/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Check", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.28.0", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "@Author::OALDERS/Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "@Author::OALDERS/ReadmeMdInBuild", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::StaticInstall", "config" : { "Dist::Zilla::Plugin::StaticInstall" : { "dry_run" : 0, "mode" : "on" } }, "name" : "@Author::OALDERS/StaticInstall", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@Author::OALDERS/ShareDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::TravisCI::StatusBadge", "name" : "@Author::OALDERS/TravisCI::StatusBadge", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CheckIssues", "name" : "@Author::OALDERS/CheckIssues", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::OALDERS/ConfirmRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Author::OALDERS/UploadToCPAN", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Author::OALDERS/@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Author::OALDERS/@Git::VersionManager/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/release snapshot", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v6.26", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/Git::Tag", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Author::OALDERS/@Git::VersionManager/NextRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/post-release commit", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Push", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Prereqs::Soften", "config" : { "Dist::Zilla::Plugin::Prereqs::Soften" : { "copy_to" : [ "develop.requires" ], "modules" : [ "Clone" ], "modules_from_features" : null, "to_relationship" : "suggests" } }, "name" : "Prereqs::Soften", "version" : "0.006003" }, { "class" : "Dist::Zilla::Plugin::Test::Compile", "config" : { "Dist::Zilla::Plugin::Test::Compile" : { "bail_out_on_fail" : "1", "fail_on_warning" : "author", "fake_home" : 0, "filename" : "xt/author/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "develop", "script_finder" : [ ":PerlExecFiles" ], "skips" : [], "switch" : [] } }, "name" : "Test::Compile", "version" : "2.058" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "Substitute", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.015" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.015" } }, "x_contributors" : [ "Adam Kennedy ", "Adam Sjogren ", "Alexey Tourbin ", "Alex Kapranoff ", "amire80 ", "Andreas J. Koenig ", "Bill Mann ", "Brendan Byrd ", "Bron Gondwana ", "Chase Whitener ", "Christopher J. Madsen ", "chromatic ", "Dan Book ", "Daniel Hedlund ", "David E. Wheeler ", "DAVIDRW ", "David Steinbrunner ", "Dorian Taylor ", "Father Chrysostomos ", "Felipe Gasper ", "FWILES ", "Gavin Peters ", "Gisle Aas ", "Graeme Thompson ", "Graham Knop ", "Hans-H. Froehlich ", "Ian Kilgore ", "Jacob J ", "Jakub Wilk ", "jefflee ", "Jerome Eteve ", "john9art ", "jonasbn ", "Karen Etheridge ", "Lars Dɪᴇᴄᴋá´�á´¡ 迪拉斯 ", "Mark Overmeer ", "Mark Stosberg ", "Martin H. Sluka ", "Matthew Chae ", "Michael Schout ", "Mickey Nasriachi ", "Mike Schilli ", "murphy ", "Olaf Alders ", "Olivier Mengué ", "Ondrej Hanak ", "openstrike ", "Peter Rabbitson ", "phrstbrn ", "Robert Rothenberg ", "Robert Rothenberg ", "Robert Stone ", "Rolf Grossmann ", "ruff ", "sasao ", "Saturday Walkers Club ", "Sean M. Burke ", "Slaven Rezic ", "Spiros Denaxas ", "Steve Hay ", "Tatsuhiko Miyagawa ", "Tatsuhiko Miyagawa ", "Theo van Hoesel ", "Tigran ", "Tobias Leich ", "Todd Lipcon ", "tokuhirom ", "Tom Hukins ", "Tony Finch ", "Toru Yamaguchi ", "uid39246 ", "Ville Skyttä ", "William Storey ", "Yuri Karaban ", "Zakariyya Mughal ", "Zefram " ], "x_generated_by_perl" : "v5.30.2", "x_serialization_backend" : "JSON::PP version 2.97001", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_static_install" : 1 } PK!¦ùÐÐBperl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.076/install.jsonnuÏÃ6Ç${"provides":{"HTTP::Tiny":{"version":"0.076","file":"lib/HTTP/Tiny.pm"}},"target":"HTTP::Tiny","version":"0.076","name":"HTTP::Tiny","dist":"HTTP-Tiny-0.076","pathname":"D/DA/DAGOLDEN/HTTP-Tiny-0.076.tar.gz"}PK!B}�“øøAperl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.076/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "A small, simple, correct HTTP/1.1 client", "author" : [ "Christian Hansen ", "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "HTTP-Tiny", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::ReleaseStatus::FromVersion" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.072", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Perl::Critic::Policy::Lax::ProhibitStringyEval::ExceptForRequire" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Software::License::Perl_5" : "0", "Test::CPAN::Meta" : "0", "Test::MinimumVersion" : "0", "Test::More" : "0", "Test::Perl::Critic" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1", "perl" : "5.006" } }, "runtime" : { "recommends" : { "HTTP::CookieJar" : "0.001", "IO::Socket::IP" : "0.32", "IO::Socket::SSL" : "1.42", "Mozilla::CA" : "20160104", "Net::SSLeay" : "1.49" }, "requires" : { "Carp" : "0", "Fcntl" : "0", "IO::Socket" : "0", "MIME::Base64" : "0", "Socket" : "0", "Time::Local" : "0", "bytes" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" }, "suggests" : { "IO::Socket::SSL" : "1.56" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "Data::Dumper" : "0", "Exporter" : "0", "ExtUtils::MakeMaker" : "0", "File::Basename" : "0", "File::Spec" : "0", "File::Temp" : "0", "IO::Dir" : "0", "IO::File" : "0", "IO::Socket::INET" : "0", "IPC::Cmd" : "0", "Test::More" : "0.96", "lib" : "0", "open" : "0" } } }, "provides" : { "HTTP::Tiny" : { "file" : "lib/HTTP/Tiny.pm", "version" : "0.076" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/chansen/p5-http-tiny/issues" }, "homepage" : "https://github.com/chansen/p5-http-tiny", "repository" : { "type" : "git", "url" : "https://github.com/chansen/p5-http-tiny.git", "web" : "https://github.com/chansen/p5-http-tiny" } }, "version" : "0.076", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Alan Gardner ", "Alessandro Ghedini ", "A. Sinan Unur ", "Brad Gilbert ", "brian m. carlson ", "Chris Nehren ", "Chris Weyl ", "Claes Jakobsson ", "Clinton Gormley ", "Craig A. Berry ", "Craig Berry ", "David Golden ", "David Mitchell ", "Dean Pearce ", "Edward Zborowski ", "Felipe Gasper ", "James Raspass ", "Jeremy Mates ", "Jess Robinson ", "Karen Etheridge ", "Lukas Eklund ", "Martin J. Evans ", "Martin-Louis Bright ", "Mike Doherty ", "Nicolas Rochelemagne ", "Olaf Alders ", "Olivier Mengué ", "Petr PísaÅ™ ", "Serguei Trouchelle ", "Shoichi Kaji ", "SkyMarshal ", "Sören Kornetzki ", "Steve Grazzini ", "Syohei YOSHIDA ", "Tatsuhiko Miyagawa ", "Tom Hukins ", "Tony Cook " ], "x_generated_by_perl" : "v5.28.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.04" } PK!DªÐ§ààEperl5/x86_64-linux-thread-multi/.meta/Alien-Libxml2-0.19/install.jsonnuÏÃ6Ç${"dist":"Alien-Libxml2-0.19","version":0.19,"name":"Alien::Libxml2","provides":{"Alien::Libxml2":{"version":0.19,"file":"lib/Alien/Libxml2.pm"}},"pathname":"P/PL/PLICEASE/Alien-Libxml2-0.19.tar.gz","target":"Alien::Libxml2"}PK! ,HÁÚÚDperl5/x86_64-linux-thread-multi/.meta/Alien-Libxml2-0.19/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Install the C libxml2 library on your system", "author" : [ "Graham Ollis " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.025, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Alien-Libxml2", "prereqs" : { "build" : { "requires" : { "Alien::Build" : "2.37", "Alien::Build::MM" : "0.32", "ExtUtils::MakeMaker" : "6.52" } }, "configure" : { "requires" : { "Alien::Build" : "2.37", "Alien::Build::MM" : "2.37", "Alien::Build::Plugin::Build::SearchDep" : "0.35", "Alien::Build::Plugin::Download::GitLab" : "0", "Alien::Build::Plugin::Prefer::BadVersion" : "1.05", "Alien::Build::Plugin::Probe::Vcpkg" : "0", "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.52" } }, "develop" : { "recommends" : { "Alien::Build::Plugin::Probe::Vcpkg" : "0", "Dist::Zilla::Plugin::AlienBase::Doc" : "0", "Dist::Zilla::Plugin::AlienBuild" : "0.11", "Dist::Zilla::Plugin::Author::Plicease::Thanks" : "0", "Dist::Zilla::Plugin::Author::Plicease::Upload" : "0", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::PruneFiles" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::PluginBundle::Author::Plicease" : "2.69", "Perl::Critic::Policy::BuiltinFunctions::ProhibitBooleanGrep" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitStringySplit" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidGrep" : "0", "Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidMap" : "0", "Perl::Critic::Policy::ClassHierarchies::ProhibitExplicitISA" : "0", "Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless" : "0", "Perl::Critic::Policy::CodeLayout::ProhibitHardTabs" : "0", "Perl::Critic::Policy::CodeLayout::ProhibitTrailingWhitespace" : "0", "Perl::Critic::Policy::CodeLayout::RequireConsistentNewlines" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitLabelsWithSpecialBlockNames" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitMutatingListFunctions" : "0", "Perl::Critic::Policy::ControlStructures::ProhibitUnreachableCode" : "0", "Perl::Critic::Policy::Freenode::ArrayAssignAref" : "0", "Perl::Critic::Policy::Freenode::BarewordFilehandles" : "0", "Perl::Critic::Policy::Freenode::ConditionalDeclarations" : "0", "Perl::Critic::Policy::Freenode::ConditionalImplicitReturn" : "0", "Perl::Critic::Policy::Freenode::DeprecatedFeatures" : "0", "Perl::Critic::Policy::Freenode::DiscouragedModules" : "0", "Perl::Critic::Policy::Freenode::DollarAB" : "0", "Perl::Critic::Policy::Freenode::Each" : "0", "Perl::Critic::Policy::Freenode::EmptyReturn" : "0", "Perl::Critic::Policy::Freenode::IndirectObjectNotation" : "0", "Perl::Critic::Policy::Freenode::LexicalForeachIterator" : "0", "Perl::Critic::Policy::Freenode::LoopOnHash" : "0", "Perl::Critic::Policy::Freenode::ModPerl" : "0", "Perl::Critic::Policy::Freenode::OpenArgs" : "0", "Perl::Critic::Policy::Freenode::OverloadOptions" : "0", "Perl::Critic::Policy::Freenode::POSIXImports" : "0", "Perl::Critic::Policy::Freenode::PackageMatchesFilename" : "0", "Perl::Critic::Policy::Freenode::PreferredAlternatives" : "0", "Perl::Critic::Policy::Freenode::StrictWarnings" : "0", "Perl::Critic::Policy::Freenode::Threads" : "0", "Perl::Critic::Policy::Freenode::Wantarray" : "0", "Perl::Critic::Policy::Freenode::WarningsSwitch" : "0", "Perl::Critic::Policy::Freenode::WhileDiamondDefaultAssignment" : "0", "Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles" : "0", "Perl::Critic::Policy::InputOutput::ProhibitJoinedReadline" : "0", "Perl::Critic::Policy::InputOutput::ProhibitTwoArgOpen" : "0", "Perl::Critic::Policy::Miscellanea::ProhibitFormats" : "0", "Perl::Critic::Policy::Miscellanea::ProhibitUselessNoCritic" : "0", "Perl::Critic::Policy::Modules::ProhibitConditionalUseStatements" : "0", "Perl::Critic::Policy::Modules::RequireNoMatchVarsWithUseEnglish" : "0", "Perl::Critic::Policy::Objects::ProhibitIndirectSyntax" : "0", "Perl::Critic::Policy::RegularExpressions::ProhibitUselessTopic" : "0", "Perl::Critic::Policy::Subroutines::ProhibitNestedSubs" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitLeadingZeros" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitMixedBooleanOperators" : "0", "Perl::Critic::Policy::ValuesAndExpressions::ProhibitSpecialLiteralHeredocTerminator" : "0", "Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator" : "0", "Perl::Critic::Policy::Variables::ProhibitPerl4PackageNames" : "0", "Perl::Critic::Policy::Variables::ProhibitUnusedVariables" : "0", "Software::License::Perl_5" : "0" }, "requires" : { "File::Spec" : "0", "FindBin" : "0", "Perl::Critic" : "0", "Test2::Require::Module" : "0.000121", "Test2::Tools::PerlCritic" : "0", "Test2::V0" : "0.000121", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.98", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Pod::Spelling::CommonMistakes" : "0", "Test::Spelling" : "0", "Test::Strict" : "0", "YAML" : "0" } }, "runtime" : { "requires" : { "Alien::Base" : "2.37", "Alien::Build" : "0.25", "perl" : "5.006" } }, "test" : { "requires" : { "Test2::V0" : "0.000121", "Test::Alien" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/PerlAlien/Alien-Libxml2/issues" }, "homepage" : "https://metacpan.org/pod/Alien::Libxml2", "repository" : { "type" : "git", "url" : "git://github.com/PerlAlien/Alien-Libxml2.git", "web" : "https://github.com/PerlAlien/Alien-Libxml2" }, "x_IRC" : "irc://irc.perl.org/#native" }, "version" : "0.19", "x_alienfile" : { "generated_by" : "Dist::Zilla::Plugin::AlienBuild version 0.32", "requires" : { "share" : { "Config" : "0", "HTTP::Tiny" : "0.044", "IO::Socket::SSL" : "1.56", "Mozilla::CA" : "0", "Net::SSLeay" : "1.49", "URI" : "0" }, "system" : {} } }, "x_contributors" : [ "Graham Ollis ", "Shlomi Fish (shlomif)" ], "x_generated_by_perl" : "v5.36.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.30", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_use_unsafe_inc" : 0 } PK!Z÷X†ààEperl5/x86_64-linux-thread-multi/.meta/Alien-Libxml2-0.16/install.jsonnuÏÃ6Ç${"provides":{"Alien::Libxml2":{"version":0.16,"file":"lib/Alien/Libxml2.pm"}},"target":"Alien::Libxml2","version":0.16,"name":"Alien::Libxml2","dist":"Alien-Libxml2-0.16","pathname":"P/PL/PLICEASE/Alien-Libxml2-0.16.tar.gz"}PK!w=. . Dperl5/x86_64-linux-thread-multi/.meta/Alien-Libxml2-0.16/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Install the C libxml2 library on your system", "author" : [ "Graham Ollis " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.014, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Alien-Libxml2", "prereqs" : { "build" : { "requires" : { "Alien::Build" : "0.32", "Alien::Build::MM" : "0.32", "ExtUtils::MakeMaker" : "6.52" } }, "configure" : { "requires" : { "Alien::Build" : "2.12", "Alien::Build::MM" : "2.12", "Alien::Build::Plugin::Build::SearchDep" : "0.35", "Alien::Build::Plugin::Prefer::BadVersion" : "1.05", "Alien::Build::Plugin::Probe::Vcpkg" : "0", "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.52" } }, "develop" : { "requires" : { "File::Spec" : "0", "FindBin" : "0", "Test::CPAN::Changes" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.98", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Pod::Spelling::CommonMistakes" : "0", "Test::Spelling" : "0", "Test::Strict" : "0", "YAML" : "0" } }, "runtime" : { "requires" : { "Alien::Base" : "2.12", "Alien::Build" : "0.25", "perl" : "5.006" } }, "test" : { "requires" : { "Test2::V0" : "0.000060", "Test::Alien" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/Perl5-Alien/Alien-Libxml2/issues" }, "homepage" : "https://metacpan.org/pod/Alien::Libxml2", "repository" : { "type" : "git", "url" : "git://github.com/Perl5-Alien/Alien-Libxml2.git", "web" : "https://github.com/Perl5-Alien/Alien-Libxml2" }, "x_IRC" : "irc://irc.perl.org/#native" }, "version" : "0.16", "x_alienfile" : { "generated_by" : "Dist::Zilla::Plugin::AlienBuild version 0.30", "requires" : { "share" : { "Archive::Tar" : "0", "Config" : "0", "HTTP::Tiny" : "0.044", "IO::Zlib" : "0", "Mojo::DOM58" : "1.00", "Sort::Versions" : "0", "URI" : "0", "URI::Escape" : "0" }, "system" : {} } }, "x_contributors" : [ "Graham Ollis ", "Shlomi Fish (shlomif)" ], "x_generated_by_perl" : "v5.31.10", "x_serialization_backend" : "Cpanel::JSON::XS version 4.19", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_use_unsafe_inc" : 0 } PK!¹…^zssAperl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.47/install.jsonnuÏÃ6Ç${"pathname":"T/TO/TODDR/YAML-Syck-1.47.tar.gz","dist":"YAML-Syck-1.47","target":"YAML::Syck","provides":{"JSON::Syck":{"file":"lib/JSON/Syck.pm","version":"1.47"},"YAML::Dumper::Syck":{"file":"lib/YAML/Dumper/Syck.pm"},"YAML::Loader::Syck":{"file":"lib/YAML/Loader/Syck.pm"},"YAML::Syck":{"version":"1.47","file":"lib/YAML/Syck.pm"}},"version":"1.47","name":"YAML::Syck"}PK!o¹�Ýææ@perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.47/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Fast, lightweight YAML loader and dumper", "author" : [ "Todd Rinaldo " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "YAML-Syck", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } } }, "provides" : { "JSON::Syck" : { "file" : "lib/JSON/Syck.pm", "version" : "1.47" }, "YAML::Dumper::Syck" : { "file" : "lib/YAML/Dumper/Syck.pm" }, "YAML::Loader::Syck" : { "file" : "lib/YAML/Loader/Syck.pm" }, "YAML::Syck" : { "file" : "lib/YAML/Syck.pm", "version" : "1.47" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/toddr/YAML-Syck/issues" }, "homepage" : "https://github.com/toddr/YAML-Syck", "license" : [ "https://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "https://github.com/toddr/YAML-Syck.git", "web" : "https://github.com/toddr/YAML-Syck" } }, "version" : "1.47", "x_serialization_backend" : "JSON::PP version 4.16" } PK! u®¤FFIperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.106/install.jsonnuÏÃ6Ç${"dist":"Template-Toolkit-3.106","version":3.106,"provides":{"Template::Plugin::String":{"version":3.106,"file":"lib/Template/Plugin/String.pm"},"Template::Plugin::List":{"file":"lib/Template/Plugin/List.pm","version":3.106},"Template::App::ttree":{"file":"lib/Template/App/ttree.pm","version":3.106},"Template":{"version":3.106,"file":"lib/Template.pm"},"Template::Directive":{"version":3.106,"file":"lib/Template/Directive.pm"},"Template::Plugin::View":{"file":"lib/Template/Plugin/View.pm","version":3.106},"Template::Plugin::Iterator":{"file":"lib/Template/Plugin/Iterator.pm","version":3.106},"Template::Stash::XS":{"file":"lib/Template/Stash/XS.pm"},"Template::Plugin::Format":{"file":"lib/Template/Plugin/Format.pm","version":3.106},"Template::Plugin::Datafile":{"file":"lib/Template/Plugin/Datafile.pm","version":3.106},"Template::Monad::Assert":{"version":3.106,"file":"lib/Template/Plugin/Assert.pm"},"Template::Plugin::URL":{"version":3.106,"file":"lib/Template/Plugin/URL.pm"},"Template::Namespace::Constants":{"file":"lib/Template/Namespace/Constants.pm","version":3.106},"Template::Filters":{"file":"lib/Template/Filters.pm","version":3.106},"Template::Plugin::Assert":{"file":"lib/Template/Plugin/Assert.pm","version":3.106},"Template::Plugin::Date::Manip":{"version":3.106,"file":"lib/Template/Plugin/Date.pm"},"Template::Constants":{"file":"lib/Template/Constants.pm","version":3.106},"Template::Exception":{"version":3.106,"file":"lib/Template/Exception.pm"},"Template::Parser":{"version":3.106,"file":"lib/Template/Parser.pm"},"Template::Plugin::Table":{"file":"lib/Template/Plugin/Table.pm","version":3.106},"Template::Toolkit":{"file":"lib/Template/Toolkit.pm","version":3.106},"Template::Monad::Scalar":{"version":3.106,"file":"lib/Template/Plugin/Scalar.pm"},"Template::Provider":{"version":3.106,"file":"lib/Template/Provider.pm"},"Template::Grammar":{"version":3.106,"file":"lib/Template/Grammar.pm"},"Template::VMethods":{"file":"lib/Template/VMethods.pm","version":3.106},"Template::Plugin::Image":{"file":"lib/Template/Plugin/Image.pm","version":3.106},"Template::Iterator":{"file":"lib/Template/Iterator.pm","version":3.106},"Template::Document":{"version":3.106,"file":"lib/Template/Document.pm"},"Template::Plugin::Scalar":{"file":"lib/Template/Plugin/Scalar.pm","version":3.106},"Template::Plugin::File":{"version":3.106,"file":"lib/Template/Plugin/File.pm"},"Template::Plugin::Pod":{"version":3.106,"file":"lib/Template/Plugin/Pod.pm"},"Template::Stash::Context":{"file":"lib/Template/Stash/Context.pm","version":3.106},"Template::Plugin::Date::Calc":{"file":"lib/Template/Plugin/Date.pm","version":3.106},"Template::Perl":{"version":3.106,"file":"lib/Template/Filters.pm"},"Template::View":{"file":"lib/Template/View.pm","version":3.106},"Template::Config":{"version":3.106,"file":"lib/Template/Config.pm"},"Template::Test":{"file":"lib/Template/Test.pm","version":3.106},"Template::Plugin":{"file":"lib/Template/Plugin.pm","version":3.106},"Template::Plugin::HTML":{"file":"lib/Template/Plugin/HTML.pm","version":3.106},"Template::Stash":{"version":3.106,"file":"lib/Template/Stash.pm"},"Template::Plugin::Wrap":{"file":"lib/Template/Plugin/Wrap.pm","version":3.106},"Template::Plugin::Dumper":{"version":3.106,"file":"lib/Template/Plugin/Dumper.pm"},"Template::Context":{"file":"lib/Template/Context.pm","version":3.106},"Template::Plugins":{"version":3.106,"file":"lib/Template/Plugins.pm"},"Template::Base":{"version":3.106,"file":"lib/Template/Base.pm"},"Template::Plugin::Procedural":{"file":"lib/Template/Plugin/Procedural.pm","version":3.106},"Template::Plugin::Date":{"version":3.106,"file":"lib/Template/Plugin/Date.pm"},"Template::Service":{"version":3.106,"file":"lib/Template/Service.pm"},"Template::Plugin::Directory":{"version":3.106,"file":"lib/Template/Plugin/Directory.pm"},"Template::TieString":{"version":3.106,"file":"lib/Template/Config.pm"},"Template::Plugin::Filter":{"file":"lib/Template/Plugin/Filter.pm","version":3.106},"Template::Plugin::Math":{"version":3.106,"file":"lib/Template/Plugin/Math.pm"}},"name":"Template","pathname":"T/TO/TODDR/Template-Toolkit-3.106.tar.gz","target":"Template::Constants"}PK!ÜàáHperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.106/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "comprehensive template processing system", "author" : [ "Andy Wardley " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Template-Toolkit", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.48" } }, "runtime" : { "requires" : { "AppConfig" : "1.56", "File::Spec" : "0.8", "File::Temp" : "0.12", "Scalar::Util" : "0", "perl" : "5.010" } }, "test" : { "requires" : { "Test::LeakTrace" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/abw/Template2/issues" }, "homepage" : "http://www.template-toolkit.org", "repository" : { "type" : "git", "url" : "https://github.com/abw/Template2.git", "web" : "https://github.com/abw/Template2" } }, "version" : "3.106", "x_serialization_backend" : "JSON::PP version 4.16" } PK!·ÃÁÞÞDperl5/x86_64-linux-thread-multi/.meta/Capture-Tiny-0.48/install.jsonnuÏÃ6Ç${"provides":{"Capture::Tiny":{"version":"0.48","file":"lib/Capture/Tiny.pm"}},"target":"Capture::Tiny","version":"0.48","name":"Capture::Tiny","dist":"Capture-Tiny-0.48","pathname":"D/DA/DAGOLDEN/Capture-Tiny-0.48.tar.gz"}PK!][¥Ò† † Cperl5/x86_64-linux-thread-multi/.meta/Capture-Tiny-0.48/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Capture STDOUT and STDERR from Perl, XS or external programs", "author" : [ "David Golden " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "apache_2_0" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Capture-Tiny", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::OSPrereqs" : "0", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::ReleaseStatus::FromVersion" : "0", "Dist::Zilla::Plugin::RemovePrereqs" : "0", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.072", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Software::License::Apache_2_0" : "0", "Test::CPAN::Meta" : "0", "Test::MinimumVersion" : "0", "Test::More" : "0", "Test::Perl::Critic" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12", "Test::Version" : "1" } }, "runtime" : { "requires" : { "Carp" : "0", "Exporter" : "0", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "Scalar::Util" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "IO::File" : "0", "Test::More" : "0.62", "lib" : "0" } } }, "provides" : { "Capture::Tiny" : { "file" : "lib/Capture/Tiny.pm", "version" : "0.48" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/dagolden/Capture-Tiny/issues" }, "homepage" : "https://github.com/dagolden/Capture-Tiny", "repository" : { "type" : "git", "url" : "https://github.com/dagolden/Capture-Tiny.git", "web" : "https://github.com/dagolden/Capture-Tiny" } }, "version" : "0.48", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Dagfinn Ilmari MannsÃ¥ker ", "David E. Wheeler ", "fecundf ", "Graham Knop ", "Peter Rabbitson " ], "x_generated_by_perl" : "v5.26.1", "x_serialization_backend" : "Cpanel::JSON::XS version 3.0239" } PK!þ¾RÜc c Dperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0209/install.jsonnuÏÃ6Ç${"provides":{"XML::LibXML::PI":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Pattern":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::SAX":{"version":2.0209,"file":"lib/XML/LibXML/SAX.pm"},"XML::LibXML::XPathContext":{"version":2.0209,"file":"lib/XML/LibXML/XPathContext.pm"},"XML::LibXML::SAX::AttributeNode":{"version":2.0209,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::SAX::Generator":{"version":2.0209,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::XPathExpression":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::NodeList":{"version":2.0209,"file":"lib/XML/LibXML/NodeList.pm"},"XML::LibXML::Error":{"version":2.0209,"file":"lib/XML/LibXML/Error.pm"},"XML::LibXML::RegExp":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::_SAXParser":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::InputCallback":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Devel":{"version":2.0209,"file":"lib/XML/LibXML/Devel.pm"},"XML::LibXML::Boolean":{"version":2.0209,"file":"lib/XML/LibXML/Boolean.pm"},"XML::LibXML::AttributeHash":{"version":2.0209,"file":"lib/XML/LibXML/AttributeHash.pm"},"XML::LibXML":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Literal":{"version":2.0209,"file":"lib/XML/LibXML/Literal.pm"},"XML::LibXML::Reader":{"version":2.0209,"file":"lib/XML/LibXML/Reader.pm"},"XML::LibXML::SAX::Builder":{"version":2.0209,"file":"lib/XML/LibXML/SAX/Builder.pm"},"XML::LibXML::Schema":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Element":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Attr":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Node":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::CDATASection":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Number":{"version":2.0209,"file":"lib/XML/LibXML/Number.pm"},"XML::LibXML::Namespace":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::ErrNo":{"version":2.0209,"file":"lib/XML/LibXML/ErrNo.pm"},"XML::LibXML::SAX::Parser":{"version":2.0209,"file":"lib/XML/LibXML/SAX/Parser.pm"},"XML::LibXML::Dtd":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::NamedNodeMap":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Common":{"version":2.0209,"file":"lib/XML/LibXML/Common.pm"},"XML::LibXML::Comment":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Document":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::DocumentFragment":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::RelaxNG":{"version":2.0209,"file":"LibXML.pm"},"XML::LibXML::Text":{"version":2.0209,"file":"LibXML.pm"}},"target":"XML::LibXML","version":2.0209,"name":"XML::LibXML","dist":"XML-LibXML-2.0209","pathname":"S/SH/SHLOMIF/XML-LibXML-2.0209.tar.gz"}PK!Î…JŠÛ Û Cperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0209/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Interface to Gnome libxml2 xml parsing and DOM library", "author" : [ "Petr Pajas " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.70, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "dom", "html", "libxml", "object oriented", "oop", "parse", "parser", "parsing", "pullparser", "sax", "sgml", "xml", "xpath", "XPath", "xs" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-LibXML", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Alien::Base::Wrapper" : "0", "Alien::Libxml2" : "0.14", "Config" : "0", "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "DynaLoader" : "0", "Encode" : "0", "Exporter" : "5.57", "IO::Handle" : "0", "Scalar::Util" : "0", "Tie::Hash" : "0", "XML::NamespaceSupport" : "1.07", "XML::SAX" : "0.11", "XML::SAX::Base" : "0", "XML::SAX::DocumentLocator" : "0", "XML::SAX::Exception" : "0", "base" : "0", "constant" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "vars" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Config" : "0", "Errno" : "0", "IO::File" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "0", "Test::More" : "0", "locale" : "0", "utf8" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/shlomif/perl-XML-LibXML.git", "web" : "https://github.com/shlomif/perl-XML-LibXML" } }, "version" : "2.0209", "x_serialization_backend" : "JSON::PP version 4.16" } PK!¬†Ýu!!Operl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.140/install.jsonnuÏÃ6Ç${"provides":{"CPAN::Meta::Requirements":{"version":"2.140","file":"lib/CPAN/Meta/Requirements.pm"}},"target":"CPAN::Meta::Requirements","version":"2.140","name":"CPAN::Meta::Requirements","dist":"CPAN-Meta-Requirements-2.140","pathname":"D/DA/DAGOLDEN/CPAN-Meta-Requirements-2.140.tar.gz"}PK!keTuNperl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.140/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "a set of version requirements for a CPAN dist", "author" : [ "David Golden ", "Ricardo Signes " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.042, CPAN::Meta::Converter version 2.150001, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "CPAN-Meta-Requirements", "no_index" : { "directory" : [ "corpus", "examples", "t", "xt" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::Authority" : "0", "Dist::Zilla::Plugin::AutoPrereqs" : "0", "Dist::Zilla::Plugin::BumpVersionAfterRelease" : "0", "Dist::Zilla::Plugin::CPANFile" : "0", "Dist::Zilla::Plugin::CheckChangesHasContent" : "0", "Dist::Zilla::Plugin::CheckMetaResources" : "0", "Dist::Zilla::Plugin::CheckPrereqsIndexed" : "0", "Dist::Zilla::Plugin::ConfirmRelease" : "0", "Dist::Zilla::Plugin::CopyFilesFromBuild::Filtered" : "0", "Dist::Zilla::Plugin::ExecDir" : "0", "Dist::Zilla::Plugin::Git::Check" : "0", "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch" : "0", "Dist::Zilla::Plugin::Git::Commit" : "0", "Dist::Zilla::Plugin::Git::Contributors" : "0", "Dist::Zilla::Plugin::Git::GatherDir" : "0", "Dist::Zilla::Plugin::Git::Push" : "0", "Dist::Zilla::Plugin::Git::Tag" : "0", "Dist::Zilla::Plugin::GithubMeta" : "0", "Dist::Zilla::Plugin::InsertCopyright" : "0", "Dist::Zilla::Plugin::License" : "0", "Dist::Zilla::Plugin::MakeMaker" : "0", "Dist::Zilla::Plugin::MakeMaker::Highlander" : "0.003", "Dist::Zilla::Plugin::Manifest" : "0", "Dist::Zilla::Plugin::ManifestSkip" : "0", "Dist::Zilla::Plugin::MetaJSON" : "0", "Dist::Zilla::Plugin::MetaNoIndex" : "0", "Dist::Zilla::Plugin::MetaProvides::Package" : "0", "Dist::Zilla::Plugin::MetaTests" : "0", "Dist::Zilla::Plugin::MetaYAML" : "0", "Dist::Zilla::Plugin::MinimumPerl" : "0", "Dist::Zilla::Plugin::NextRelease" : "0", "Dist::Zilla::Plugin::OnlyCorePrereqs" : "0.014", "Dist::Zilla::Plugin::Pod2Readme" : "0", "Dist::Zilla::Plugin::PodCoverageTests" : "0", "Dist::Zilla::Plugin::PodSyntaxTests" : "0", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::Prereqs::AuthorDeps" : "0", "Dist::Zilla::Plugin::PromptIfStale" : "0", "Dist::Zilla::Plugin::PruneCruft" : "0", "Dist::Zilla::Plugin::RewriteVersion" : "0", "Dist::Zilla::Plugin::RunExtraTests" : "0", "Dist::Zilla::Plugin::ShareDir" : "0", "Dist::Zilla::Plugin::SurgicalPodWeaver" : "0", "Dist::Zilla::Plugin::Test::Compile" : "0", "Dist::Zilla::Plugin::Test::MinimumVersion" : "0", "Dist::Zilla::Plugin::Test::Perl::Critic" : "0", "Dist::Zilla::Plugin::Test::PodSpelling" : "0", "Dist::Zilla::Plugin::Test::Portability" : "0", "Dist::Zilla::Plugin::Test::ReportPrereqs" : "0", "Dist::Zilla::Plugin::Test::Version" : "0", "Dist::Zilla::Plugin::TestRelease" : "0", "Dist::Zilla::Plugin::UploadToCPAN" : "0", "English" : "0", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Software::License::Perl_5" : "0", "Test::CPAN::Meta" : "0", "Test::More" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Spelling" : "0.12", "Test::Version" : "1", "blib" : "1.01" } }, "runtime" : { "requires" : { "B" : "0", "Carp" : "0", "perl" : "5.006", "strict" : "0", "version" : "0.88", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::More" : "0.88", "version" : "0.88" } } }, "provides" : { "CPAN::Meta::Requirements" : { "file" : "lib/CPAN/Meta/Requirements.pm", "version" : "2.140" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements/issues" }, "homepage" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements", "repository" : { "type" : "git", "url" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements.git", "web" : "https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements" } }, "version" : "2.140", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Ed J ", "Karen Etheridge ", "Leon Timmermans ", "robario " ] } PK!ž¬ß臇Iperl5/x86_64-linux-thread-multi/.meta/Scalar-List-Utils-1.55/install.jsonnuÏÃ6Ç${"provides":{"Scalar::Util":{"version":1.55,"file":"lib/Scalar/Util.pm"},"List::Util::XS":{"version":1.55,"file":"lib/List/Util/XS.pm"},"List::Util":{"version":1.55,"file":"lib/List/Util.pm"},"Sub::Util":{"version":1.55,"file":"lib/Sub/Util.pm"}},"target":"List::Util","version":1.55,"name":"List::Util","dist":"Scalar-List-Utils-1.55","pathname":"P/PE/PEVANS/Scalar-List-Utils-1.55.tar.gz"}PK!³úèÏÏHperl5/x86_64-linux-thread-multi/.meta/Scalar-List-Utils-1.55/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Common Scalar and List utility subroutines", "author" : [ "Graham Barr " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Scalar-List-Utils", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } }, "test" : { "requires" : { "Test::More" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-Scalar-List-Utils@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=Scalar-List-Utils" }, "repository" : { "type" : "git", "url" : "https://github.com/Scalar-List-Utils/Scalar-List-Utils.git", "web" : "https://github.com/Scalar-List-Utils/Scalar-List-Utils" } }, "version" : "1.55", "x_serialization_backend" : "JSON::PP version 4.04" } PK!€“§·úúHperl5/x86_64-linux-thread-multi/.meta/ExtUtils-ParseXS-3.35/install.jsonnuÏÃ6Ç${"provides":{"ExtUtils::ParseXS::CountLines":{"version":3.35,"file":"lib/ExtUtils/ParseXS/CountLines.pm"},"ExtUtils::Typemaps":{"version":3.35,"file":"lib/ExtUtils/Typemaps.pm"},"ExtUtils::ParseXS":{"version":3.35,"file":"lib/ExtUtils/ParseXS.pm"},"ExtUtils::Typemaps::InputMap":{"version":3.35,"file":"lib/ExtUtils/Typemaps/InputMap.pm"},"ExtUtils::Typemaps::Cmd":{"version":3.35,"file":"lib/ExtUtils/Typemaps/Cmd.pm"},"ExtUtils::Typemaps::Type":{"version":3.35,"file":"lib/ExtUtils/Typemaps/Type.pm"},"ExtUtils::Typemaps::OutputMap":{"version":3.35,"file":"lib/ExtUtils/Typemaps/OutputMap.pm"},"ExtUtils::ParseXS::Constants":{"version":3.35,"file":"lib/ExtUtils/ParseXS/Constants.pm"},"ExtUtils::ParseXS::Eval":{"version":3.35,"file":"lib/ExtUtils/ParseXS/Eval.pm"},"ExtUtils::ParseXS::Utilities":{"version":3.35,"file":"lib/ExtUtils/ParseXS/Utilities.pm"}},"target":"ExtUtils::ParseXS","version":3.35,"name":"ExtUtils::ParseXS","dist":"ExtUtils-ParseXS-3.35","pathname":"S/SM/SMUELLER/ExtUtils-ParseXS-3.35.tar.gz"}PK!êK¿²ââGperl5/x86_64-linux-thread-multi/.meta/ExtUtils-ParseXS-3.35/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "converts Perl XS code into C code", "author" : [ "Ken Williams " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150005, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "ExtUtils-ParseXS", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.46" } }, "runtime" : { "requires" : { "Carp" : "0", "Cwd" : "0", "DynaLoader" : "0", "Exporter" : "5.57", "ExtUtils::CBuilder" : "0", "ExtUtils::MakeMaker" : "6.46", "File::Basename" : "0", "File::Spec" : "0", "Symbol" : "0", "Test::More" : "0.47" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "http://rt.perl.org/rt3/" }, "repository" : { "type" : "git", "url" : "git://perl5.git.perl.org/gitroot/perl.git" } }, "version" : "3.35", "x_serialization_backend" : "JSON::PP version 2.27300" } PK!tºÈÎÎBperl5/x86_64-linux-thread-multi/.meta/File-Which-1.23/install.jsonnuÏÃ6Ç${"provides":{"File::Which":{"version":1.23,"file":"lib/File/Which.pm"}},"target":"File::Which","version":1.23,"name":"File::Which","dist":"File-Which-1.23","pathname":"P/PL/PLICEASE/File-Which-1.23.tar.gz"}PK!Iñ,\¬¬Aperl5/x86_64-linux-thread-multi/.meta/File-Which-1.23/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Perl implementation of the which utility as an API", "author" : [ "Per Einar Ellefsen ", "Adam Kennedy ", "Graham Ollis " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "File-Which", "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "FindBin" : "0", "Test::EOL" : "0", "Test::Fixme" : "0.07", "Test::More" : "0.47", "Test::NoTabs" : "0", "Test::Pod" : "0", "Test::Pod::Coverage" : "0", "Test::Pod::Spelling::CommonMistakes" : "0", "Test::Spelling" : "0", "Test::Strict" : "0", "YAML" : "0" } }, "runtime" : { "requires" : { "perl" : "5.006" } }, "test" : { "requires" : { "Test::More" : "0.47" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/plicease/File-Which/issues" }, "homepage" : "https://metacpan.org/pod/File::Which", "repository" : { "type" : "git", "url" : "git://github.com/plicease/File-Which.git", "web" : "https://github.com/plicease/File-Which" } }, "version" : "1.23", "x_generated_by_perl" : "v5.29.6", "x_serialization_backend" : "Cpanel::JSON::XS version 4.08", "x_use_unsafe_inc" : 0 } PK!yçñÒÒDperl5/x86_64-linux-thread-multi/.meta/common-sense-3.75/install.jsonnuÏÃ6Ç${"provides":{"common::sense":{"version":3.75,"file":"sense.pm.PL"}},"target":"common::sense","version":3.75,"name":"common::sense","dist":"common-sense-3.75","pathname":"M/ML/MLEHMANN/common-sense-3.75.tar.gz"}PK!°0míCperl5/x86_64-linux-thread-multi/.meta/common-sense-3.75/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "unknown", "author" : [ "unknown" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150001, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "common-sense", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } } }, "release_status" : "stable", "version" : 3.75 } PK!±sŸ3­ ­ Dperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0210/install.jsonnuÏÃ6Ç${"version":"2.0210","name":"XML::LibXML","dist":"XML-LibXML-2.0210","target":"XML::LibXML","pathname":"S/SH/SHLOMIF/XML-LibXML-2.0210.tar.gz","provides":{"XML::LibXML::Document":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::Attr":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::SAX::Parser":{"file":"lib/XML/LibXML/SAX/Parser.pm","version":"2.0210"},"XML::LibXML::Common":{"file":"lib/XML/LibXML/Common.pm","version":"2.0210"},"XML::LibXML::SAX::Builder":{"version":"2.0210","file":"lib/XML/LibXML/SAX/Builder.pm"},"XML::LibXML::Error":{"version":"2.0210","file":"lib/XML/LibXML/Error.pm"},"XML::LibXML::Element":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::Devel":{"version":"2.0210","file":"lib/XML/LibXML/Devel.pm"},"XML::LibXML::SAX::AttributeNode":{"version":"2.0210","file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::RelaxNG":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::SAX":{"file":"lib/XML/LibXML/SAX.pm","version":"2.0210"},"XML::LibXML::Comment":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::CDATASection":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::NodeList":{"version":"2.0210","file":"lib/XML/LibXML/NodeList.pm"},"XML::LibXML::ErrNo":{"file":"lib/XML/LibXML/ErrNo.pm","version":"2.0210"},"XML::LibXML::XPathExpression":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::Boolean":{"file":"lib/XML/LibXML/Boolean.pm","version":"2.0210"},"XML::LibXML::NamedNodeMap":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::DocumentFragment":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::Node":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::Reader":{"version":"2.0210","file":"lib/XML/LibXML/Reader.pm"},"XML::LibXML::Schema":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::Pattern":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::Namespace":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::SAX::Generator":{"file":"lib/XML/LibXML/SAX/Generator.pm","version":"2.0210"},"XML::LibXML::Text":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::Dtd":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::InputCallback":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML::RegExp":{"file":"LibXML.pm","version":"2.0210"},"XML::LibXML":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::XPathContext":{"file":"lib/XML/LibXML/XPathContext.pm","version":"2.0210"},"XML::LibXML::_SAXParser":{"version":"2.0210","file":"LibXML.pm"},"XML::LibXML::Literal":{"file":"lib/XML/LibXML/Literal.pm","version":"2.0210"},"XML::LibXML::AttributeHash":{"file":"lib/XML/LibXML/AttributeHash.pm","version":"2.0210"},"XML::LibXML::Number":{"version":"2.0210","file":"lib/XML/LibXML/Number.pm"},"XML::LibXML::PI":{"version":"2.0210","file":"LibXML.pm"}}}PK!ûMÛ Û Cperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0210/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Interface to Gnome libxml2 xml parsing and DOM library", "author" : [ "Petr Pajas " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.70, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "dom", "html", "libxml", "object oriented", "oop", "parse", "parser", "parsing", "pullparser", "sax", "sgml", "xml", "xpath", "XPath", "xs" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-LibXML", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Alien::Base::Wrapper" : "0", "Alien::Libxml2" : "0.14", "Config" : "0", "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "DynaLoader" : "0", "Encode" : "0", "Exporter" : "5.57", "IO::Handle" : "0", "Scalar::Util" : "0", "Tie::Hash" : "0", "XML::NamespaceSupport" : "1.07", "XML::SAX" : "0.11", "XML::SAX::Base" : "0", "XML::SAX::DocumentLocator" : "0", "XML::SAX::Exception" : "0", "base" : "0", "constant" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "vars" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Config" : "0", "Errno" : "0", "IO::File" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "0", "Test::More" : "0", "locale" : "0", "utf8" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/shlomif/perl-XML-LibXML.git", "web" : "https://github.com/shlomif/perl-XML-LibXML" } }, "version" : "2.0210", "x_serialization_backend" : "JSON::PP version 4.16" } PK!ÈXHN;perl5/x86_64-linux-thread-multi/.meta/HDB-1.05/install.jsonnuÏÃ6Ç${"provides":{"HDB::Parser":{"version":"1.0","file":"lib/HDB/Parser.pm"},"HDB::Encode":{"version":"1.0","file":"lib/HDB/Encode.pm"},"HDB::CORE":{"version":"1.0","file":"lib/HDB/CORE.pm"},"HDB::MOD::mysql":{"version":"1.0","file":"lib/HDB/MOD/mysql.pm"},"HDB::TABLE":{"version":1.05,"file":"lib/HDB.pm"},"HDB::CMDS":{"version":1.05,"file":"lib/HDB.pm"},"HDB::MOD::oracle":{"version":"1.0","file":"lib/HDB/MOD/oracle.pm"},"DBI":{"version":"1.0","file":"lib/HDB/MOD.pm"},"DBD":{"version":"1.0","file":"lib/HDB/MOD.pm"},"HDB::MOD":{"version":"1.0","file":"lib/HDB/MOD.pm"},"HDB":{"version":1.05,"file":"lib/HDB.pm"},"HDB::MOD::sqlite":{"version":"1.0","file":"lib/HDB/MOD/sqlite.pm"},"HDB::Object":{"version":0.02,"file":"lib/HDB/Object.pm"},"HDB::CMDS::TieHandle":{"version":"1.0","file":"lib/HDB/CMDS.pm"},"HDB::Object::Loader::TieHandler":{"version":0.02,"file":"lib/HDB/Object.pm"},"HDB::Object::Loader":{"version":0.02,"file":"lib/HDB/Object.pm"}},"target":"DBD","version":1.05,"name":"HDB","dist":"HDB-1.05","pathname":"G/GM/GMPASSOS/HDB-1.05.tar.gz"}PK!—y¶n‘‘:perl5/x86_64-linux-thread-multi/.meta/HDB-1.05/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Hybrid Database - Handles multiple databases with the same interface.", "author" : [ "Graciliano M. P. " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.50, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "HDB", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "DBI" : "1.13" } } }, "release_status" : "stable", "version" : "1.05" } PK!Ø*�eeDperl5/x86_64-linux-thread-multi/.meta/File-chdir-0.1010/install.jsonnuÏÃ6Ç${"provides":{"File::chdir::ARRAY":{"version":"0.1010","file":"lib/File/chdir.pm"},"File::chdir::SCALAR":{"version":"0.1010","file":"lib/File/chdir.pm"},"File::chdir":{"version":"0.1010","file":"lib/File/chdir.pm"}},"target":"File::chdir","version":"0.1010","name":"File::chdir","dist":"File-chdir-0.1010","pathname":"D/DA/DAGOLDEN/File-chdir-0.1010.tar.gz"}PK!ýYb©  Cperl5/x86_64-linux-thread-multi/.meta/File-chdir-0.1010/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "a more sensible way to change directories", "author" : [ "David Golden ", "Michael G. Schwern " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.031, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "File-chdir", "no_index" : { "directory" : [ "t", "xt", "examples", "corpus" ], "package" : [ "DB" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.17" } }, "develop" : { "requires" : { "Dist::Zilla" : "5", "Dist::Zilla::PluginBundle::DAGOLDEN" : "0.072", "File::Spec" : "0", "File::Temp" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Test::CPAN::Meta" : "0", "Test::More" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Spelling" : "0.12", "Test::Version" : "1" } }, "runtime" : { "requires" : { "Carp" : "0", "Cwd" : "3.16", "Exporter" : "0", "File::Spec::Functions" : "3.27", "perl" : "5.006", "strict" : "0", "vars" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::More" : "0", "warnings" : "0" } } }, "provides" : { "File::chdir" : { "file" : "lib/File/chdir.pm", "version" : "0.1010" }, "File::chdir::ARRAY" : { "file" : "lib/File/chdir.pm", "version" : "0.1010" }, "File::chdir::SCALAR" : { "file" : "lib/File/chdir.pm", "version" : "0.1010" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/dagolden/File-chdir/issues" }, "homepage" : "https://github.com/dagolden/File-chdir", "repository" : { "type" : "git", "url" : "https://github.com/dagolden/File-chdir.git", "web" : "https://github.com/dagolden/File-chdir" } }, "version" : "0.1010", "x_authority" : "cpan:DAGOLDEN", "x_contributors" : [ "Joel Berger " ] } PK!»ö‹ççHperl5/x86_64-linux-thread-multi/.meta/Canary-Stability-2013/install.jsonnuÏÃ6Ç${"provides":{"Canary::Stability":{"version":2013,"file":"Stability.pm"}},"target":"Canary::Stability","version":2013,"name":"Canary::Stability","dist":"Canary-Stability-2013","pathname":"M/ML/MLEHMANN/Canary-Stability-2013.tar.gz"}PK!ðL¦GGGperl5/x86_64-linux-thread-multi/.meta/Canary-Stability-2013/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "unknown", "author" : [ "unknown" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Canary-Stability", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } } }, "release_status" : "stable", "version" : "2013", "x_serialization_backend" : "JSON::PP version 2.27300" } PK!±*<[ÌÌBperl5/x86_64-linux-thread-multi/.meta/XML-Simple-2.25/install.jsonnuÏÃ6Ç${"provides":{"XML::Simple":{"version":2.25,"file":"lib/XML/Simple.pm"}},"target":"XML::Simple","version":2.25,"name":"XML::Simple","dist":"XML-Simple-2.25","pathname":"G/GR/GRANTM/XML-Simple-2.25.tar.gz"}PK!ˆ;ËõKKAperl5/x86_64-linux-thread-multi/.meta/XML-Simple-2.25/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "An API for simple XML files", "author" : [ "Grant McLean " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.043, CPAN::Meta::Converter version 2.150005, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-Simple", "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "XML::NamespaceSupport" : "1.04", "XML::SAX" : "0.15", "XML::SAX::Expat" : "0", "perl" : "5.008" } }, "test" : { "requires" : { "File::Temp" : "0", "Test::More" : "0.88" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "git://github.com/grantm/xml-simple.git", "web" : "https://github.com/grantm/xml-simple" } }, "version" : "2.25" } PK!o^ö'úúIperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.009/install.jsonnuÏÃ6Ç${"provides":{"Template::Base":{"version":3.009,"file":"lib/Template/Base.pm"},"Template::Stash::Context":{"version":3.009,"file":"lib/Template/Stash/Context.pm"},"Template::Config":{"version":3.009,"file":"lib/Template/Config.pm"},"Template::Plugin::Date::Calc":{"version":3.009,"file":"lib/Template/Plugin/Date.pm"},"Template::View":{"version":3.009,"file":"lib/Template/View.pm"},"Template::Perl":{"version":3.009,"file":"lib/Template/Filters.pm"},"Template::Plugin::Procedural":{"version":3.009,"file":"lib/Template/Plugin/Procedural.pm"},"Template::Plugin::Table":{"version":3.009,"file":"lib/Template/Plugin/Table.pm"},"Template::Plugin::Filter":{"version":3.009,"file":"lib/Template/Plugin/Filter.pm"},"Template::Iterator":{"version":3.009,"file":"lib/Template/Iterator.pm"},"Template::Plugin::Pod":{"version":3.009,"file":"lib/Template/Plugin/Pod.pm"},"Template::Constants":{"version":3.009,"file":"lib/Template/Constants.pm"},"Template::VMethods":{"version":3.009,"file":"lib/Template/VMethods.pm"},"Template::Monad::Scalar":{"version":3.009,"file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::Datafile":{"version":3.009,"file":"lib/Template/Plugin/Datafile.pm"},"Template::Plugin::URL":{"version":3.009,"file":"lib/Template/Plugin/URL.pm"},"Template::Filters":{"version":3.009,"file":"lib/Template/Filters.pm"},"Template::Namespace::Constants":{"version":3.009,"file":"lib/Template/Namespace/Constants.pm"},"Template::Toolkit":{"version":3.009,"file":"lib/Template/Toolkit.pm"},"Template::Context":{"version":3.009,"file":"lib/Template/Context.pm"},"Template::Directive":{"version":3.009,"file":"lib/Template/Directive.pm"},"Template::Plugin":{"version":3.009,"file":"lib/Template/Plugin.pm"},"Template::TieString":{"version":3.009,"file":"lib/Template/Config.pm"},"Template::Plugin::Wrap":{"version":3.009,"file":"lib/Template/Plugin/Wrap.pm"},"Template::Parser":{"version":3.009,"file":"lib/Template/Parser.pm"},"Template::Grammar":{"version":3.009,"file":"lib/Template/Grammar.pm"},"Template::Plugin::HTML":{"version":3.009,"file":"lib/Template/Plugin/HTML.pm"},"Template::Plugin::Format":{"version":3.009,"file":"lib/Template/Plugin/Format.pm"},"Template::Plugin::Scalar":{"version":3.009,"file":"lib/Template/Plugin/Scalar.pm"},"Template::Plugin::Directory":{"version":3.009,"file":"lib/Template/Plugin/Directory.pm"},"Template::Stash::XS":{"file":"lib/Template/Stash/XS.pm"},"Template::Plugin::Dumper":{"version":3.009,"file":"lib/Template/Plugin/Dumper.pm"},"Template::Plugins":{"version":3.009,"file":"lib/Template/Plugins.pm"},"Template::Plugin::Assert":{"version":3.009,"file":"lib/Template/Plugin/Assert.pm"},"Template::Provider":{"version":3.009,"file":"lib/Template/Provider.pm"},"Template::Stash":{"version":3.009,"file":"lib/Template/Stash.pm"},"Template::Plugin::Image":{"version":3.009,"file":"lib/Template/Plugin/Image.pm"},"Template::Plugin::Date::Manip":{"version":3.009,"file":"lib/Template/Plugin/Date.pm"},"Template::Exception":{"version":3.009,"file":"lib/Template/Exception.pm"},"Template::Plugin::String":{"version":3.009,"file":"lib/Template/Plugin/String.pm"},"Template::Document":{"version":3.009,"file":"lib/Template/Document.pm"},"Template::Plugin::Math":{"version":3.009,"file":"lib/Template/Plugin/Math.pm"},"Template::Service":{"version":3.009,"file":"lib/Template/Service.pm"},"Template::Test":{"version":3.009,"file":"lib/Template/Test.pm"},"Template::Monad::Assert":{"version":3.009,"file":"lib/Template/Plugin/Assert.pm"},"Template::Plugin::Iterator":{"version":3.009,"file":"lib/Template/Plugin/Iterator.pm"},"Template":{"version":3.009,"file":"lib/Template.pm"},"Template::Plugin::CGI":{"version":3.009,"file":"lib/Template/Plugin/CGI.pm"},"Template::Plugin::Date":{"version":3.009,"file":"lib/Template/Plugin/Date.pm"},"Template::Plugin::File":{"version":3.009,"file":"lib/Template/Plugin/File.pm"},"Template::Plugin::View":{"version":3.009,"file":"lib/Template/Plugin/View.pm"}},"target":"Template::Constants","version":3.009,"name":"Template","dist":"Template-Toolkit-3.009","pathname":"A/AT/ATOOMIC/Template-Toolkit-3.009.tar.gz"}PK!1gÛa°°Hperl5/x86_64-linux-thread-multi/.meta/Template-Toolkit-3.009/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "comprehensive template processing system", "author" : [ "Andy Wardley " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Template-Toolkit", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "AppConfig" : "1.56", "File::Spec" : "0.8", "File::Temp" : "0.12", "Scalar::Util" : "0" } }, "test" : { "requires" : { "CGI" : "4.11", "Test::LeakTrace" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/abw/Template2/issues" }, "homepage" : "http://www.template-toolkit.org", "repository" : { "type" : "git", "url" : "https://github.com/abw/Template2.git", "web" : "https://github.com/abw/Template2" } }, "version" : "3.009" } PK!šs0ê³³Gperl5/x86_64-linux-thread-multi/.meta/Types-Serialiser-1.0/install.jsonnuÏÃ6Ç${"provides":{"JSON::PP::Boolean":{"version":"1.0","file":"Serialiser.pm"},"Types::Serialiser":{"version":"1.0","file":"Serialiser.pm"},"Types::Serialiser::BooleanBase":{"version":"1.0","file":"Serialiser.pm"},"Types::Serialiser::Error":{"version":"1.0","file":"Serialiser.pm"}},"target":"Types::Serialiser","version":"1.0","name":"Types::Serialiser","dist":"Types-Serialiser-1.0","pathname":"M/ML/MLEHMANN/Types-Serialiser-1.0.tar.gz"}PK!»½O$llFperl5/x86_64-linux-thread-multi/.meta/Types-Serialiser-1.0/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "unknown", "author" : [ "unknown" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 6.8, CPAN::Meta::Converter version 2.120921, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Types-Serialiser", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "common::sense" : "0" } } }, "release_status" : "stable", "version" : "1.0" } PK!鸞,³³?perl5/x86_64-linux-thread-multi/.meta/JSON-XS-4.03/install.jsonnuÏÃ6Ç${"pathname":"M/ML/MLEHMANN/JSON-XS-4.03.tar.gz","provides":{"JSON::XS":{"file":"XS.pm","version":4.03}},"name":"JSON::XS","version":4.03,"target":"JSON::XS","dist":"JSON-XS-4.03"}PK!Poeç¶¶>perl5/x86_64-linux-thread-multi/.meta/JSON-XS-4.03/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "unknown", "author" : [ "unknown" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150001, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "JSON-XS", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Canary::Stability" : "0", "ExtUtils::MakeMaker" : "6.52" } }, "runtime" : { "requires" : { "Types::Serialiser" : "0", "common::sense" : "0" } } }, "release_status" : "stable", "version" : "4.03" } PK!wvî|ÎÎCperl5/x86_64-linux-thread-multi/.meta/Test-Fatal-0.016/install.jsonnuÏÃ6Ç${"provides":{"Test::Fatal":{"version":0.016,"file":"lib/Test/Fatal.pm"}},"target":"Test::Fatal","version":0.016,"name":"Test::Fatal","dist":"Test-Fatal-0.016","pathname":"R/RJ/RJBS/Test-Fatal-0.016.tar.gz"}PK!¸>ªoËJËJBperl5/x86_64-linux-thread-multi/.meta/Test-Fatal-0.016/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "incredibly simple helpers for testing code with exceptions", "author" : [ "Ricardo Signes " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.015, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Test-Fatal", "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Encode" : "0", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "Carp" : "0", "Exporter" : "5.57", "Test::Builder" : "0", "Try::Tiny" : "0.07", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::Builder::Tester" : "0", "Test::More" : "0.65", "overload" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/rjbs/Test-Fatal/issues" }, "homepage" : "https://github.com/rjbs/Test-Fatal", "repository" : { "type" : "git", "url" : "https://github.com/rjbs/Test-Fatal.git", "web" : "https://github.com/rjbs/Test-Fatal" } }, "version" : "0.016", "x_Dist_Zilla" : { "perl" : { "version" : "5.032000" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@RJBS/Git::GatherDir", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::CheckPrereqsIndexed", "name" : "@RJBS/CheckPrereqsIndexed", "version" : "0.020" }, { "class" : "Dist::Zilla::Plugin::CheckExtraTests", "name" : "@RJBS/CheckExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::RJBS" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@RJBS/RJBS-Outdated", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 0, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@RJBS/CPAN-Outdated", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@RJBS/@Filter/PruneCruft", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ManifestSkip", "name" : "@RJBS/@Filter/ManifestSkip", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@RJBS/@Filter/MetaYAML", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@RJBS/@Filter/License", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Readme", "name" : "@RJBS/@Filter/Readme", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@RJBS/@Filter/ExecDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@RJBS/@Filter/ShareDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@RJBS/@Filter/Manifest", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@RJBS/@Filter/TestRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@RJBS/@Filter/ConfirmRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@RJBS/@Filter/UploadToCPAN", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 9 } }, "name" : "@RJBS/MakeMaker", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "@RJBS/AutoPrereqs", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Git::NextVersion", "config" : { "Dist::Zilla::Plugin::Git::NextVersion" : { "first_version" : "0.001", "version_by_branch" : 0, "version_regexp" : "(?^:^([0-9]+\\.[0-9]+)$)" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.24.3 (Apple Git-128)", "repo_root" : "." } }, "name" : "@RJBS/Git::NextVersion", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::PkgVersion", "name" : "@RJBS/PkgVersion", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@RJBS/MetaConfig", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@RJBS/MetaJSON", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@RJBS/NextRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "@RJBS/Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@RJBS/PodSyntaxTests", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@RJBS/Test::ReportPrereqs", "version" : "0.027" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "test", "type" : "requires" } }, "name" : "@RJBS/TestMoreWithSubtests", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "config_plugins" : [ "@RJBS" ], "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@RJBS/SingleEncoding", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@RJBS/Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@RJBS/Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@RJBS/Prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "@RJBS/Synopsis", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "@RJBS/Description", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "@RJBS/Overview", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "@RJBS/Stability", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "Attributes", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "Methods", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "Functions", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@RJBS/Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@RJBS/postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@RJBS/Authors", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Contributors", "name" : "@RJBS/Contributors", "version" : "0.009" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@RJBS/Legal", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::Transformer", "name" : "@RJBS/List", "version" : "4.015" } ] } }, "name" : "@RJBS/PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@RJBS/GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.24.3 (Apple Git-128)", "repo_root" : "." } }, "name" : "@RJBS/@Git/Check", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.24.3 (Apple Git-128)", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@RJBS/@Git/Commit", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "0.016", "tag_format" : "%v", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.24.3 (Apple Git-128)", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@RJBS/@Git/Tag", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin :", "github :" ], "remotes_must_exist" : 0 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.24.3 (Apple Git-128)", "repo_root" : "." } }, "name" : "@RJBS/@Git/Push", "version" : "2.046" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.24.3 (Apple Git-128)", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "@RJBS/Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::RemovePrereqs", "config" : { "Dist::Zilla::Plugin::RemovePrereqs" : { "modules_to_remove" : [ "Test::More" ] } }, "name" : "RemovePrereqs", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "test", "type" : "requires" } }, "name" : "TestRequires", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.015" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.015" } }, "x_contributors" : [ "David Golden ", "Graham Knop ", "Jesse Luehrs ", "Joel Bernstein ", "Karen Etheridge " ], "x_generated_by_perl" : "v5.32.0", "x_serialization_backend" : "Cpanel::JSON::XS version 4.19", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } PK!<‰"XXCperl5/x86_64-linux-thread-multi/.meta/Getopt-Long-2.52/install.jsonnuÏÃ6Ç${"provides":{"Getopt::Long":{"version":2.52,"file":"lib/Getopt/Long.pm"},"Getopt::Long::CallBack":{"version":2.52,"file":"lib/Getopt/Long.pm"},"Getopt::Long::Parser":{"version":2.52,"file":"lib/Getopt/Long.pm"}},"target":"Getopt::Long","version":2.52,"name":"Getopt::Long","dist":"Getopt-Long-2.52","pathname":"J/JV/JV/Getopt-Long-2.52.tar.gz"}PK!ZbÚ{ººBperl5/x86_64-linux-thread-multi/.meta/Getopt-Long-2.52/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Module to handle parsing command line options", "author" : [ "Johan Vromans (jvromans@squirrel.nl)" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.46, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Getopt-Long", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Pod::Usage" : "1.14" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/sciurius/perl-Getopt-Long.git", "web" : "https://github.com/sciurius/perl-Getopt-Long" } }, "version" : "2.52", "x_serialization_backend" : "JSON::PP version 4.04" } PK!ø}Eperl5/x86_64-linux-thread-multi/.meta/WWW-Mechanize-2.02/install.jsonnuÏÃ6Ç${"provides":{"WWW::Mechanize::Image":{"version":"2.02","file":"lib/WWW/Mechanize/Image.pm"},"WWW::Mechanize::Link":{"version":"2.02","file":"lib/WWW/Mechanize/Link.pm"},"WWW::Mechanize":{"version":"2.02","file":"lib/WWW/Mechanize.pm"}},"target":"WWW::Mechanize","version":"2.02","name":"WWW::Mechanize","dist":"WWW-Mechanize-2.02","pathname":"O/OA/OALDERS/WWW-Mechanize-2.02.tar.gz"}PK!ã«  Dperl5/x86_64-linux-thread-multi/.meta/WWW-Mechanize-2.02/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Handy web browsing in a Perl object", "author" : [ "Andy Lester " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.015, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "WWW-Mechanize", "no_index" : { "directory" : [ "examples", "t", "xt" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "recommends" : { "Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007" }, "requires" : { "Code::TidyAll" : "0.71", "Code::TidyAll::Plugin::SortLines::Naturally" : "0.000003", "Code::TidyAll::Plugin::Test::Vars" : "0.04", "Code::TidyAll::Plugin::UniqueLines" : "0.000003", "Encode" : "0", "LWP::Protocol::https" : "6.07", "Parallel::ForkManager" : "1.19", "Perl::Critic" : "1.132", "Perl::Tidy" : "20180220", "Pod::Coverage::TrustPod" : "0", "Test::Code::TidyAll" : "0.50", "Test::EOL" : "0", "Test::Mojibake" : "0", "Test::More" : "0.88", "Test::Needs" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Portability::Files" : "0", "Test::RequiresInternet" : "0", "Test::Vars" : "0.014", "Test::Version" : "1", "constant" : "0", "lib" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "Getopt::Long" : "0", "HTML::Form" : "1.00", "HTML::HeadParser" : "0", "HTML::TokeParser" : "0", "HTML::TreeBuilder" : "5", "HTTP::Cookies" : "0", "HTTP::Request" : "1.30", "HTTP::Request::Common" : "0", "LWP::UserAgent" : "6.45", "Pod::Usage" : "0", "Scalar::Util" : "1.14", "Tie::RefHash" : "0", "URI::URL" : "0", "URI::file" : "0", "base" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "CGI" : "4.32", "Exporter" : "0", "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "File::Temp" : "0", "FindBin" : "0", "HTTP::Daemon" : "6.12", "HTTP::Response" : "0", "HTTP::Server::Simple::CGI" : "0", "LWP" : "0", "LWP::Simple" : "0", "Path::Tiny" : "0", "Test::Deep" : "0", "Test::Exception" : "0", "Test::Fatal" : "0", "Test::Memory::Cycle" : "1.06", "Test::More" : "0.96", "Test::NoWarnings" : "1.04", "Test::Output" : "0", "Test::Taint" : "1.08", "Test::Warnings" : "0", "URI" : "0", "URI::Escape" : "0", "bytes" : "0", "lib" : "0" } } }, "provides" : { "WWW::Mechanize" : { "file" : "lib/WWW/Mechanize.pm", "version" : "2.02" }, "WWW::Mechanize::Image" : { "file" : "lib/WWW/Mechanize/Image.pm", "version" : "2.02" }, "WWW::Mechanize::Link" : { "file" : "lib/WWW/Mechanize/Link.pm", "version" : "2.02" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/libwww-perl/WWW-Mechanize/issues" }, "homepage" : "https://github.com/libwww-perl/WWW-Mechanize", "repository" : { "type" : "git", "url" : "https://github.com/libwww-perl/WWW-Mechanize.git", "web" : "https://github.com/libwww-perl/WWW-Mechanize" } }, "version" : "2.02", "x_Dist_Zilla" : { "perl" : { "version" : "5.030002" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::Author::OALDERS" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, build", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 1, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::OALDERS/stale modules, release", "version" : "0.057" }, { "class" : "Dist::Zilla::Plugin::OALDERS::TidyAll", "name" : "@Author::OALDERS/OALDERS::TidyAll", "version" : "0.000028" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "@Author::OALDERS/AutoPrereqs", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4" } }, "name" : "@Author::OALDERS/MakeMaker", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::CPANFile", "name" : "@Author::OALDERS/CPANFile", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ContributorsFile", "name" : "@Author::OALDERS/ContributorsFile", "version" : "0.3.0" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::OALDERS/MetaJSON", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::OALDERS/MetaYAML", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::OALDERS/Manifest", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Author::OALDERS/MetaNoIndex", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::OALDERS/MetaConfig", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaResources", "name" : "@Author::OALDERS/MetaResources", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::OALDERS/License", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "config" : { "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.006" } }, "name" : "@Author::OALDERS/InstallGuide", "version" : "1.200013" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "requires" } }, "name" : "@Author::OALDERS/Modules for use with tidyall", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "@Author::OALDERS/ExecDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "@Author::OALDERS/MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::OALDERS/PodSyntaxTests", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::EOL", "config" : { "Dist::Zilla::Plugin::Test::EOL" : { "filename" : "xt/author/eol.t", "finder" : [ ":ExecFiles", ":InstallModules", ":TestFiles" ], "trailing_whitespace" : 1 } }, "name" : "@Author::OALDERS/Test::EOL", "version" : "0.19" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::Coverage::Configurable", "name" : "@Author::OALDERS/Test::Pod::Coverage::Configurable", "version" : "0.07" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "@Author::OALDERS/Test::Portability", "version" : "2.001000" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Author::OALDERS/TestRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Author::OALDERS/Test::ReportPrereqs", "version" : "0.028" }, { "class" : "Dist::Zilla::Plugin::Test::TidyAll", "name" : "@Author::OALDERS/Test::TidyAll", "version" : "0.04" }, { "class" : "Dist::Zilla::Plugin::Test::Version", "name" : "@Author::OALDERS/Test::Version", "version" : "1.09" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4" } }, "name" : "@Author::OALDERS/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@CorePrep/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@CorePrep/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Default/SingleEncoding", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Default/Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Default/Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Default/Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Default/postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Default/Authors", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Default/Legal", "version" : "4.015" } ] } }, "name" : "@Author::OALDERS/PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::PruneCruft", "name" : "@Author::OALDERS/PruneCruft", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromBuild", "name" : "@Author::OALDERS/CopyFilesFromBuild", "version" : "0.170880" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@Author::OALDERS/GithubMeta", "version" : "0.58" }, { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@Author::OALDERS/Git::GatherDir", "version" : "2.047" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Install" ], "match" : [] } }, "name" : "@Author::OALDERS/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Check", "version" : "2.047" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.28.0", "include_authors" : 0, "include_releaser" : 1, "order_by" : "name", "paths" : [] } }, "name" : "@Author::OALDERS/Git::Contributors", "version" : "0.035" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "@Author::OALDERS/ReadmeMdInBuild", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::StaticInstall", "config" : { "Dist::Zilla::Plugin::StaticInstall" : { "dry_run" : 0, "mode" : "on" } }, "name" : "@Author::OALDERS/StaticInstall", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::ShareDir", "name" : "@Author::OALDERS/ShareDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::TravisCI::StatusBadge", "name" : "@Author::OALDERS/TravisCI::StatusBadge", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::CheckIssues", "name" : "@Author::OALDERS/CheckIssues", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::OALDERS/ConfirmRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Author::OALDERS/UploadToCPAN", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Author::OALDERS/@Git::VersionManager/pluginbundle version", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Author::OALDERS/@Git::VersionManager/MetaProvides::Update", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Author::OALDERS/@Git::VersionManager/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "v%V%n%n%c", "signoff" : 0 }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Changes", "Install", "LICENSE", "META.json", "Makefile.PL", "README.md", "cpanfile", "dist.ini" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/release snapshot", "version" : "2.047" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v2.02", "tag_format" : "v%V", "tag_message" : "v%V" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/Git::Tag", "version" : "2.047" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 0, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Author::OALDERS/@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.009" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Author::OALDERS/@Git::VersionManager/NextRelease", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release", "signoff" : 0 }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::OALDERS/@Git::VersionManager/post-release commit", "version" : "2.047" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.28.0", "repo_root" : "." } }, "name" : "@Author::OALDERS/Git::Push", "version" : "2.047" }, { "class" : "Dist::Zilla::Plugin::ExecDir", "name" : "ExecDir", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : "4" } }, "name" : "RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "runtime", "type" : "requires" } }, "name" : "RuntimeRequires", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "test", "type" : "requires" } }, "name" : "TestRequires", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "requires" } }, "name" : "DevelopRequires", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Package", "config" : { "Dist::Zilla::Plugin::MetaProvides::Package" : { "finder_objects" : [ { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.015" } ], "include_underscores" : 0 }, "Dist::Zilla::Role::MetaProvider::Provider" : { "$Dist::Zilla::Role::MetaProvider::Provider::VERSION" : "2.002004", "inherit_missing" : 1, "inherit_version" : 1, "meta_noindex" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000037", "version" : "0.006" } }, "name" : "MetaProvides::Package", "version" : "2.004003" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.015" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : "MetaProvides::Package/AUTOVIV/:InstallModulesPM", "version" : "6.015" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.015" } }, "x_contributors" : [ "Alexandr Ciornii ", "Andrew Grangaard ", "Andy Lester ", "Bernhard Wagner ", "Chase Whitener ", "dakkar ", "Dave Doyle ", "David Precious ", "David Steinbrunner ", "Desmond Daignault ", "Ed Avis ", "Evan Zacks ", "Ferenc Erki ", "Flavio Poletti ", "Florian Schlichting ", "Gabor Szabo ", "Gareth Tunley ", "gregor herrmann ", "Grigor Karavardanyan ", "James Raspass ", "Jason May ", "Jesse Vincent ", "John Beppu ", "Jozef Kutej ", "Julien Fiegehenn ", "Karen Etheridge ", "Kirrily 'Skud' Robert ", "Kivanc Yazan ", "Lars Dɪᴇᴄᴋá´�á´¡ 迪拉斯 ", "Mark Stosberg ", "Martin H. Sluka ", "Matthew Chae ", "Matt S Trout ", "Max Maischein ", "Mohammad S Anwar ", "Neil Bowers ", "Nik LaBelle ", "Olaf Alders ", "Philippe Bruhat (BooK) ", "Ricardo Signes ", "Schuyler Langdon ", "Sergey Romanov ", "Shoichi Kaji ", "Steve Scaffidi ", "Stuart Johnston ", "sunnavy ", "Varadinsky ", "Ville Skyttä ", "Zefram ", "ç©�丹尼 Dan Jacobson " ], "x_generated_by_perl" : "v5.30.2", "x_serialization_backend" : "JSON::PP version 2.97001", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later", "x_static_install" : 1 } PK!PäÜDa a Dperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0213/install.jsonnuÏÃ6Ç${"dist":"XML-LibXML-2.0213","provides":{"XML::LibXML::Attr":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::Reader":{"file":"lib/XML/LibXML/Reader.pm","version":2.0213},"XML::LibXML::PI":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::RegExp":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Dtd":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::XPathContext":{"version":2.0213,"file":"lib/XML/LibXML/XPathContext.pm"},"XML::LibXML::SAX":{"version":2.0213,"file":"lib/XML/LibXML/SAX.pm"},"XML::LibXML::Node":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::DocumentFragment":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::SAX::Builder":{"file":"lib/XML/LibXML/SAX/Builder.pm","version":2.0213},"XML::LibXML::Comment":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::XPathExpression":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::ErrNo":{"file":"lib/XML/LibXML/ErrNo.pm","version":2.0213},"XML::LibXML::AttributeHash":{"version":2.0213,"file":"lib/XML/LibXML/AttributeHash.pm"},"XML::LibXML::Namespace":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::_SAXParser":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::SAX::AttributeNode":{"version":2.0213,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::Common":{"version":2.0213,"file":"lib/XML/LibXML/Common.pm"},"XML::LibXML::SAX::Generator":{"version":2.0213,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::NodeList":{"version":2.0213,"file":"lib/XML/LibXML/NodeList.pm"},"XML::LibXML::Schema":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Literal":{"version":2.0213,"file":"lib/XML/LibXML/Literal.pm"},"XML::LibXML::NamedNodeMap":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Text":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::RelaxNG":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Boolean":{"version":2.0213,"file":"lib/XML/LibXML/Boolean.pm"},"XML::LibXML::Devel":{"file":"lib/XML/LibXML/Devel.pm","version":2.0213},"XML::LibXML::Element":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Document":{"file":"LibXML.pm","version":2.0213},"XML::LibXML::CDATASection":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::SAX::Parser":{"version":2.0213,"file":"lib/XML/LibXML/SAX/Parser.pm"},"XML::LibXML::InputCallback":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Pattern":{"version":2.0213,"file":"LibXML.pm"},"XML::LibXML::Number":{"version":2.0213,"file":"lib/XML/LibXML/Number.pm"},"XML::LibXML::Error":{"version":2.0213,"file":"lib/XML/LibXML/Error.pm"}},"version":2.0213,"target":"XML::LibXML","pathname":"T/TO/TODDR/XML-LibXML-2.0213.tar.gz","name":"XML::LibXML"}PK!µ& & Cperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0213/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Interface to Gnome libxml2 xml parsing and DOM library", "author" : [ "Petr Pajas " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.76, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "dom", "html", "libxml", "object oriented", "oop", "parse", "parser", "parsing", "pullparser", "sax", "sgml", "xml", "xpath", "XPath", "xs" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-LibXML", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Alien::Base::Wrapper" : "0", "Alien::Libxml2" : "0.14", "Config" : "0", "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "DynaLoader" : "0", "Encode" : "0", "Exporter" : "5.57", "IO::Handle" : "0", "Scalar::Util" : "0", "Tie::Hash" : "0", "XML::NamespaceSupport" : "1.07", "XML::SAX" : "0.11", "XML::SAX::Base" : "0", "XML::SAX::DocumentLocator" : "0", "XML::SAX::Exception" : "0", "base" : "0", "constant" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Config" : "0", "Errno" : "0", "IO::File" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "0", "Test::More" : "0", "locale" : "0", "utf8" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/cpan-authors/XML-LibXML/issues" }, "repository" : { "type" : "git", "url" : "https://github.com/cpan-authors/XML-LibXML.git", "web" : "https://github.com/cpan-authors/XML-LibXML" } }, "version" : "2.0213", "x_serialization_backend" : "JSON::PP version 4.16" } PK!záKÃÃ@perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.30/install.jsonnuÏÃ6Ç${"provides":{"Try::Tiny":{"version":"0.30","file":"lib/Try/Tiny.pm"}},"target":"Try::Tiny","version":"0.30","name":"Try::Tiny","dist":"Try-Tiny-0.30","pathname":"E/ET/ETHER/Try-Tiny-0.30.tar.gz"}PK!X”\H”¸”¸?perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.30/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Minimal try/catch with proper preservation of $@", "author" : [ "יובל קוג'מן (Yuval Kogman) ", "Jesse Luehrs " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.010, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "license" : [ "mit" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Try-Tiny", "no_index" : { "directory" : [ "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" }, "suggests" : { "JSON::PP" : "2.27300" } }, "develop" : { "recommends" : { "Dist::Zilla::PluginBundle::Author::ETHER" : "0.132" }, "requires" : { "Capture::Tiny" : "0.12", "Encode" : "0", "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Pod::Coverage::TrustPod" : "0", "Pod::Wordlist" : "0", "Sub::Name" : "0.08", "Sub::Util" : "0", "Test::CPAN::Changes" : "0.19", "Test::CPAN::Meta" : "0", "Test::EOL" : "0", "Test::Kwalitee" : "1.21", "Test::MinimumVersion" : "0", "Test::Mojibake" : "0", "Test::More" : "0.96", "Test::NoTabs" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Pod::No404s" : "0", "Test::Portability::Files" : "0", "Test::Spelling" : "0.12" }, "suggests" : { "Dist::Zilla" : "5", "Dist::Zilla::Plugin::Authority" : "1.009", "Dist::Zilla::Plugin::AutoMetaResources" : "0", "Dist::Zilla::Plugin::AutoPrereqs" : "5.038", "Dist::Zilla::Plugin::Breaks" : "0", "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : "0.004", "Dist::Zilla::Plugin::CheckIssues" : "0", "Dist::Zilla::Plugin::CheckMetaResources" : "0", "Dist::Zilla::Plugin::CheckPrereqsIndexed" : "0.019", "Dist::Zilla::Plugin::CheckSelfDependency" : "0", "Dist::Zilla::Plugin::CheckStrictVersion" : "0", "Dist::Zilla::Plugin::ConfirmRelease" : "0", "Dist::Zilla::Plugin::CopyFilesFromRelease" : "0", "Dist::Zilla::Plugin::EnsureLatestPerl" : "0", "Dist::Zilla::Plugin::FileFinder::ByName" : "0", "Dist::Zilla::Plugin::FileFinder::Filter" : "0", "Dist::Zilla::Plugin::GenerateFile::FromShareDir" : "0", "Dist::Zilla::Plugin::Git::Check" : "0", "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch" : "0.004", "Dist::Zilla::Plugin::Git::CheckFor::MergeConflicts" : "0", "Dist::Zilla::Plugin::Git::Commit" : "2.020", "Dist::Zilla::Plugin::Git::Contributors" : "0.029", "Dist::Zilla::Plugin::Git::Describe" : "0.004", "Dist::Zilla::Plugin::Git::GatherDir" : "2.016", "Dist::Zilla::Plugin::Git::Push" : "0", "Dist::Zilla::Plugin::Git::Remote::Check" : "0", "Dist::Zilla::Plugin::Git::Tag" : "0", "Dist::Zilla::Plugin::GitHub::Update" : "0.40", "Dist::Zilla::Plugin::GithubMeta" : "0.54", "Dist::Zilla::Plugin::InstallGuide" : "1.200005", "Dist::Zilla::Plugin::Keywords" : "0.004", "Dist::Zilla::Plugin::License" : "5.038", "Dist::Zilla::Plugin::MakeMaker" : "0", "Dist::Zilla::Plugin::Manifest" : "0", "Dist::Zilla::Plugin::MetaConfig" : "0", "Dist::Zilla::Plugin::MetaJSON" : "0", "Dist::Zilla::Plugin::MetaNoIndex" : "0", "Dist::Zilla::Plugin::MetaProvides::Package" : "1.15000002", "Dist::Zilla::Plugin::MetaTests" : "0", "Dist::Zilla::Plugin::MetaYAML" : "0", "Dist::Zilla::Plugin::MinimumPerl" : "1.006", "Dist::Zilla::Plugin::MojibakeTests" : "0.8", "Dist::Zilla::Plugin::NextRelease" : "5.033", "Dist::Zilla::Plugin::OnlyCorePrereqs" : "0", "Dist::Zilla::Plugin::PodCoverageTests" : "5.040", "Dist::Zilla::Plugin::PodSyntaxTests" : "5.040", "Dist::Zilla::Plugin::PodWeaver" : "4.005", "Dist::Zilla::Plugin::Prereqs" : "0", "Dist::Zilla::Plugin::Prereqs::AuthorDeps" : "0.006", "Dist::Zilla::Plugin::Prereqs::Soften" : "0", "Dist::Zilla::Plugin::PromptIfStale" : "0", "Dist::Zilla::Plugin::Readme" : "0", "Dist::Zilla::Plugin::ReadmeAnyFromPod" : "0.142180", "Dist::Zilla::Plugin::RewriteVersion::Transitional" : "0.004", "Dist::Zilla::Plugin::Run::AfterBuild" : "0.041", "Dist::Zilla::Plugin::Run::AfterRelease" : "0.038", "Dist::Zilla::Plugin::RunExtraTests" : "0.024", "Dist::Zilla::Plugin::StaticInstall" : "0.005", "Dist::Zilla::Plugin::Substitute" : "0", "Dist::Zilla::Plugin::Test::CPAN::Changes" : "0.012", "Dist::Zilla::Plugin::Test::ChangesHasContent" : "0", "Dist::Zilla::Plugin::Test::CheckBreaks" : "0.018", "Dist::Zilla::Plugin::Test::Compile" : "2.039", "Dist::Zilla::Plugin::Test::EOL" : "0.17", "Dist::Zilla::Plugin::Test::Kwalitee" : "2.10", "Dist::Zilla::Plugin::Test::MinimumVersion" : "2.000003", "Dist::Zilla::Plugin::Test::NoTabs" : "0.08", "Dist::Zilla::Plugin::Test::Pod::No404s" : "1.003", "Dist::Zilla::Plugin::Test::PodSpelling" : "2.006003", "Dist::Zilla::Plugin::Test::Portability" : "2.000007", "Dist::Zilla::Plugin::Test::ReportPrereqs" : "0.022", "Dist::Zilla::Plugin::TestRelease" : "0", "Dist::Zilla::Plugin::UploadToCPAN" : "0", "Dist::Zilla::Plugin::UseUnsafeInc" : "0", "Dist::Zilla::PluginBundle::Author::ETHER" : "0.119", "Dist::Zilla::PluginBundle::Git::VersionManager" : "0", "Software::License::MIT" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "Exporter" : "5.57", "constant" : "0", "perl" : "5.006", "strict" : "0", "warnings" : "0" }, "suggests" : { "Sub::Name" : "0.08", "Sub::Util" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "Test::More" : "0", "if" : "0" }, "suggests" : { "CPAN::Meta::Check" : "0.011", "CPAN::Meta::Requirements" : "0", "Capture::Tiny" : "0.12" } } }, "provides" : { "Try::Tiny" : { "file" : "lib/Try/Tiny.pm", "version" : "0.30" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-Try-Tiny@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=Try-Tiny" }, "homepage" : "https://github.com/p5sagit/Try-Tiny", "repository" : { "type" : "git", "url" : "https://github.com/p5sagit/Try-Tiny.git", "web" : "https://github.com/p5sagit/Try-Tiny" } }, "version" : "0.30", "x_Dist_Zilla" : { "perl" : { "version" : "5.027006" }, "plugins" : [ { "class" : "Dist::Zilla::Plugin::FileFinder::Filter", "name" : "all_files_but_using_5.10_features", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 0, "check_all_prereqs" : 0, "modules" : [ "Dist::Zilla::PluginBundle::Author::ETHER" ], "phase" : "build", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::ETHER/stale modules, build", "version" : "0.054" }, { "class" : "Dist::Zilla::Plugin::PromptIfStale", "config" : { "Dist::Zilla::Plugin::PromptIfStale" : { "check_all_plugins" : 1, "check_all_prereqs" : 1, "modules" : [], "phase" : "release", "run_under_travis" : 0, "skip" : [] } }, "name" : "@Author::ETHER/stale modules, release", "version" : "0.054" }, { "class" : "Dist::Zilla::Plugin::FileFinder::ByName", "name" : "@Author::ETHER/Examples", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Git::GatherDir", "config" : { "Dist::Zilla::Plugin::GatherDir" : { "exclude_filename" : [ "CONTRIBUTING", "INSTALL", "LICENCE", "README.pod" ], "exclude_match" : [], "follow_symlinks" : 0, "include_dotfiles" : 0, "prefix" : "", "prune_directory" : [], "root" : "." }, "Dist::Zilla::Plugin::Git::GatherDir" : { "include_untracked" : 0 } }, "name" : "@Author::ETHER/Git::GatherDir", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::MetaYAML", "name" : "@Author::ETHER/MetaYAML", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::MetaJSON", "name" : "@Author::ETHER/MetaJSON", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Readme", "name" : "@Author::ETHER/Readme", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Manifest", "name" : "@Author::ETHER/Manifest", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::License", "name" : "@Author::ETHER/License", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::GenerateFile::FromShareDir", "config" : { "Dist::Zilla::Plugin::GenerateFile::FromShareDir" : { "destination_filename" : "CONTRIBUTING", "dist" : "Dist-Zilla-PluginBundle-Author-ETHER", "encoding" : "UTF-8", "has_xs" : 0, "location" : "build", "source_filename" : "CONTRIBUTING" }, "Dist::Zilla::Role::RepoFileInjector" : { "allow_overwrite" : 1, "repo_root" : ".", "version" : "0.007" } }, "name" : "@Author::ETHER/generate CONTRIBUTING", "version" : "0.013" }, { "class" : "Dist::Zilla::Plugin::InstallGuide", "name" : "@Author::ETHER/InstallGuide", "version" : "1.200007" }, { "class" : "Dist::Zilla::Plugin::Test::Compile", "config" : { "Dist::Zilla::Plugin::Test::Compile" : { "bail_out_on_fail" : 1, "fail_on_warning" : "author", "fake_home" : 0, "filename" : "xt/author/00-compile.t", "module_finder" : [ ":InstallModules" ], "needs_display" : 0, "phase" : "develop", "script_finder" : [ ":PerlExecFiles", "@Author::ETHER/Examples" ], "skips" : [], "switch" : [] } }, "name" : "@Author::ETHER/Test::Compile", "version" : "2.058" }, { "class" : "Dist::Zilla::Plugin::Test::NoTabs", "config" : { "Dist::Zilla::Plugin::Test::NoTabs" : { "filename" : "xt/author/no-tabs.t", "finder" : [ ":InstallModules", ":ExecFiles", "@Author::ETHER/Examples", ":TestFiles", ":ExtraTestFiles" ] } }, "name" : "@Author::ETHER/Test::NoTabs", "version" : "0.15" }, { "class" : "Dist::Zilla::Plugin::Test::EOL", "config" : { "Dist::Zilla::Plugin::Test::EOL" : { "filename" : "xt/author/eol.t", "finder" : [ ":ExecFiles", ":ExtraTestFiles", ":InstallModules", ":TestFiles", "@Author::ETHER/Examples" ], "trailing_whitespace" : 1 } }, "name" : "@Author::ETHER/Test::EOL", "version" : "0.19" }, { "class" : "Dist::Zilla::Plugin::MetaTests", "name" : "@Author::ETHER/MetaTests", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Test::CPAN::Changes", "config" : { "Dist::Zilla::Plugin::Test::CPAN::Changes" : { "changelog" : "Changes" } }, "name" : "@Author::ETHER/Test::CPAN::Changes", "version" : "0.012" }, { "class" : "Dist::Zilla::Plugin::Test::ChangesHasContent", "name" : "@Author::ETHER/Test::ChangesHasContent", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Test::MinimumVersion", "name" : "@Author::ETHER/Test::MinimumVersion", "version" : "2.000007" }, { "class" : "Dist::Zilla::Plugin::PodSyntaxTests", "name" : "@Author::ETHER/PodSyntaxTests", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::PodCoverageTests", "name" : "@Author::ETHER/PodCoverageTests", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Test::PodSpelling", "config" : { "Dist::Zilla::Plugin::Test::PodSpelling" : { "directories" : [ "examples", "lib", "script", "t", "xt" ], "spell_cmd" : "", "stopwords" : [ "irc" ], "wordlist" : "Pod::Wordlist" } }, "name" : "@Author::ETHER/Test::PodSpelling", "version" : "2.007005" }, { "class" : "Dist::Zilla::Plugin::Test::Pod::No404s", "name" : "@Author::ETHER/Test::Pod::No404s", "version" : "1.004" }, { "class" : "Dist::Zilla::Plugin::Test::Kwalitee", "config" : { "Dist::Zilla::Plugin::Test::Kwalitee" : { "filename" : "xt/author/kwalitee.t", "skiptest" : [] } }, "name" : "@Author::ETHER/Test::Kwalitee", "version" : "2.12" }, { "class" : "Dist::Zilla::Plugin::MojibakeTests", "name" : "@Author::ETHER/MojibakeTests", "version" : "0.8" }, { "class" : "Dist::Zilla::Plugin::Test::ReportPrereqs", "name" : "@Author::ETHER/Test::ReportPrereqs", "version" : "0.027" }, { "class" : "Dist::Zilla::Plugin::Test::Portability", "config" : { "Dist::Zilla::Plugin::Test::Portability" : { "options" : "" } }, "name" : "@Author::ETHER/Test::Portability", "version" : "2.001000" }, { "class" : "Dist::Zilla::Plugin::Git::Describe", "name" : "@Author::ETHER/Git::Describe", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::PodWeaver", "config" : { "Dist::Zilla::Plugin::PodWeaver" : { "config_plugins" : [ "@Author::ETHER" ], "finder" : [ ":InstallModules", ":ExecFiles" ], "plugins" : [ { "class" : "Pod::Weaver::Plugin::EnsurePod5", "name" : "@Author::ETHER/EnsurePod5", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::H1Nester", "name" : "@Author::ETHER/H1Nester", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::SingleEncoding", "name" : "@Author::ETHER/SingleEncoding", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::Transformer", "name" : "@Author::ETHER/List", "version" : "4.015" }, { "class" : "Pod::Weaver::Plugin::Transformer", "name" : "@Author::ETHER/Verbatim", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/header", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Name", "name" : "@Author::ETHER/Name", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Version", "name" : "@Author::ETHER/Version", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/prelude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "SYNOPSIS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "DESCRIPTION", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Generic", "name" : "OVERVIEW", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "ATTRIBUTES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "METHODS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "FUNCTIONS", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Collect", "name" : "TYPES", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Leftovers", "name" : "@Author::ETHER/Leftovers", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/postlude", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::GenerateSection", "name" : "@Author::ETHER/generate SUPPORT", "version" : "1.06" }, { "class" : "Pod::Weaver::Section::AllowOverride", "name" : "@Author::ETHER/allow override SUPPORT", "version" : "0.05" }, { "class" : "Pod::Weaver::Section::Authors", "name" : "@Author::ETHER/Authors", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Contributors", "name" : "@Author::ETHER/Contributors", "version" : "0.009" }, { "class" : "Pod::Weaver::Section::Legal", "name" : "@Author::ETHER/Legal", "version" : "4.015" }, { "class" : "Pod::Weaver::Section::Region", "name" : "@Author::ETHER/footer", "version" : "4.015" } ] } }, "name" : "@Author::ETHER/PodWeaver", "version" : "4.008" }, { "class" : "Dist::Zilla::Plugin::GithubMeta", "name" : "@Author::ETHER/GithubMeta", "version" : "0.54" }, { "class" : "Dist::Zilla::Plugin::AutoMetaResources", "name" : "@Author::ETHER/AutoMetaResources", "version" : "1.21" }, { "class" : "Dist::Zilla::Plugin::Authority", "name" : "@Author::ETHER/Authority", "version" : "1.009" }, { "class" : "Dist::Zilla::Plugin::MetaNoIndex", "name" : "@Author::ETHER/MetaNoIndex", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Package", "config" : { "Dist::Zilla::Plugin::MetaProvides::Package" : { "finder" : [ ":InstallModules" ], "finder_objects" : [ { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.010" } ], "include_underscores" : 0 }, "Dist::Zilla::Role::MetaProvider::Provider" : { "$Dist::Zilla::Role::MetaProvider::Provider::VERSION" : "2.002004", "inherit_missing" : 0, "inherit_version" : 0, "meta_noindex" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000033", "version" : "0.004" } }, "name" : "@Author::ETHER/MetaProvides::Package", "version" : "2.004003" }, { "class" : "Dist::Zilla::Plugin::MetaConfig", "name" : "@Author::ETHER/MetaConfig", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Keywords", "config" : { "Dist::Zilla::Plugin::Keywords" : { "keywords" : [] } }, "name" : "@Author::ETHER/Keywords", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::UseUnsafeInc", "config" : { "Dist::Zilla::Plugin::UseUnsafeInc" : { "dot_in_INC" : 0 } }, "name" : "@Author::ETHER/UseUnsafeInc", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::AutoPrereqs", "name" : "@Author::ETHER/AutoPrereqs", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Prereqs::AuthorDeps", "name" : "@Author::ETHER/Prereqs::AuthorDeps", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::MinimumPerl", "name" : "@Author::ETHER/MinimumPerl", "version" : "1.006" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "recommends" } }, "name" : "@Author::ETHER/pluginbundle_version", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::MakeMaker", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 9 } }, "name" : "@Author::ETHER/MakeMaker", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Git::Contributors", "config" : { "Dist::Zilla::Plugin::Git::Contributors" : { "git_version" : "2.14.2", "include_authors" : 0, "include_releaser" : 1, "order_by" : "commits", "paths" : [] } }, "name" : "@Author::ETHER/Git::Contributors", "version" : "0.032" }, { "class" : "Dist::Zilla::Plugin::StaticInstall", "config" : { "Dist::Zilla::Plugin::StaticInstall" : { "dry_run" : 1, "mode" : "auto" } }, "name" : "@Author::ETHER/StaticInstall", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::RunExtraTests", "config" : { "Dist::Zilla::Role::TestRunner" : { "default_jobs" : 9 } }, "name" : "@Author::ETHER/RunExtraTests", "version" : "0.029" }, { "class" : "Dist::Zilla::Plugin::CheckSelfDependency", "config" : { "Dist::Zilla::Plugin::CheckSelfDependency" : { "finder" : [ ":InstallModules" ] }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000033", "version" : "0.004" } }, "name" : "@Author::ETHER/CheckSelfDependency", "version" : "0.011" }, { "class" : "Dist::Zilla::Plugin::Run::AfterBuild", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "fatal_errors" : 1, "quiet" : 1, "run" : [ "bash -c \"test -e .ackrc && grep -q -- '--ignore-dir=.latest' .ackrc || echo '--ignore-dir=.latest' >> .ackrc; if [[ `dirname '%d'` != .build ]]; then test -e .ackrc && grep -q -- '--ignore-dir=%d' .ackrc || echo '--ignore-dir=%d' >> .ackrc; fi\"" ], "version" : "0.046" } }, "name" : "@Author::ETHER/.ackrc", "version" : "0.046" }, { "class" : "Dist::Zilla::Plugin::Run::AfterBuild", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "eval" : [ "if ('%d' =~ /^%n-[.[:xdigit:]]+$/) { unlink '.latest'; symlink '%d', '.latest'; }" ], "fatal_errors" : 0, "quiet" : 1, "version" : "0.046" } }, "name" : "@Author::ETHER/.latest", "version" : "0.046" }, { "class" : "Dist::Zilla::Plugin::CheckStrictVersion", "name" : "@Author::ETHER/CheckStrictVersion", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::CheckMetaResources", "name" : "@Author::ETHER/CheckMetaResources", "version" : "0.001" }, { "class" : "Dist::Zilla::Plugin::EnsureLatestPerl", "config" : { "Dist::Zilla::Plugin::EnsureLatestPerl" : { "Module::CoreList" : "5.20171120" } }, "name" : "@Author::ETHER/EnsureLatestPerl", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." } }, "name" : "@Author::ETHER/initial check", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::Git::CheckFor::MergeConflicts", "config" : { "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." } }, "name" : "@Author::ETHER/Git::CheckFor::MergeConflicts", "version" : "0.014" }, { "class" : "Dist::Zilla::Plugin::Git::CheckFor::CorrectBranch", "config" : { "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." } }, "name" : "@Author::ETHER/Git::CheckFor::CorrectBranch", "version" : "0.014" }, { "class" : "Dist::Zilla::Plugin::Git::Remote::Check", "name" : "@Author::ETHER/Git::Remote::Check", "version" : "0.1.2" }, { "class" : "Dist::Zilla::Plugin::CheckPrereqsIndexed", "name" : "@Author::ETHER/CheckPrereqsIndexed", "version" : "0.020" }, { "class" : "Dist::Zilla::Plugin::TestRelease", "name" : "@Author::ETHER/TestRelease", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Git::Check", "config" : { "Dist::Zilla::Plugin::Git::Check" : { "untracked_files" : "die" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." } }, "name" : "@Author::ETHER/after tests", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::CheckIssues", "name" : "@Author::ETHER/CheckIssues", "version" : "0.010" }, { "class" : "Dist::Zilla::Plugin::UploadToCPAN", "name" : "@Author::ETHER/UploadToCPAN", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "CONTRIBUTING", "INSTALL", "LICENCE", "LICENSE", "ppport.h" ], "match" : [] } }, "name" : "@Author::ETHER/copy generated files", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::ReadmeAnyFromPod", "config" : { "Dist::Zilla::Role::FileWatcher" : { "version" : "0.006" } }, "name" : "@Author::ETHER/ReadmeAnyFromPod", "version" : "0.163250" }, { "class" : "Dist::Zilla::Plugin::RewriteVersion::Transitional", "config" : { "Dist::Zilla::Plugin::RewriteVersion" : { "add_tarball_name" : 0, "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 1, "skip_version_provider" : 0 }, "Dist::Zilla::Plugin::RewriteVersion::Transitional" : {} }, "name" : "@Author::ETHER/@Git::VersionManager/RewriteVersion::Transitional", "version" : "0.008" }, { "class" : "Dist::Zilla::Plugin::MetaProvides::Update", "name" : "@Author::ETHER/@Git::VersionManager/MetaProvides::Update", "version" : "0.003" }, { "class" : "Dist::Zilla::Plugin::CopyFilesFromRelease", "config" : { "Dist::Zilla::Plugin::CopyFilesFromRelease" : { "filename" : [ "Changes" ], "match" : [] } }, "name" : "@Author::ETHER/@Git::VersionManager/CopyFilesFromRelease", "version" : "0.007" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [ "." ], "commit_msg" : "%N-%v%t%n%n%c" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "CONTRIBUTING", "Changes", "INSTALL", "LICENCE", "README.pod" ], "allow_dirty_match" : [], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::ETHER/@Git::VersionManager/release snapshot", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::Git::Tag", "config" : { "Dist::Zilla::Plugin::Git::Tag" : { "branch" : null, "changelog" : "Changes", "signed" : 0, "tag" : "v0.30", "tag_format" : "v%v", "tag_message" : "v%v%t" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::ETHER/@Git::VersionManager/Git::Tag", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional", "config" : { "Dist::Zilla::Plugin::BumpVersionAfterRelease" : { "finders" : [ ":ExecFiles", ":InstallModules" ], "global" : 1, "munge_makefile_pl" : 1 }, "Dist::Zilla::Plugin::BumpVersionAfterRelease::Transitional" : {} }, "name" : "@Author::ETHER/@Git::VersionManager/BumpVersionAfterRelease::Transitional", "version" : "0.008" }, { "class" : "Dist::Zilla::Plugin::NextRelease", "name" : "@Author::ETHER/@Git::VersionManager/NextRelease", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Git::Commit", "config" : { "Dist::Zilla::Plugin::Git::Commit" : { "add_files_in" : [], "commit_msg" : "increment $VERSION after %v release" }, "Dist::Zilla::Role::Git::DirtyFiles" : { "allow_dirty" : [ "Build.PL", "Changes", "Makefile.PL" ], "allow_dirty_match" : [ "(?^:^lib/.*\\.pm$)" ], "changelog" : "Changes" }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." }, "Dist::Zilla::Role::Git::StringFormatter" : { "time_zone" : "local" } }, "name" : "@Author::ETHER/@Git::VersionManager/post-release commit", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "suggests" } }, "name" : "@Author::ETHER/@Git::VersionManager/prereqs for @Git::VersionManager", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Git::Push", "config" : { "Dist::Zilla::Plugin::Git::Push" : { "push_to" : [ "origin" ], "remotes_must_exist" : 1 }, "Dist::Zilla::Role::Git::Repo" : { "git_version" : "2.14.2", "repo_root" : "." } }, "name" : "@Author::ETHER/Git::Push", "version" : "2.043" }, { "class" : "Dist::Zilla::Plugin::GitHub::Update", "config" : { "Dist::Zilla::Plugin::GitHub::Update" : { "metacpan" : 1 } }, "name" : "@Author::ETHER/GitHub::Update", "version" : "0.44" }, { "class" : "Dist::Zilla::Plugin::Run::AfterRelease", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "fatal_errors" : 0, "quiet" : 0, "run" : [ "REDACTED" ], "version" : "0.046" } }, "name" : "@Author::ETHER/install release", "version" : "0.046" }, { "class" : "Dist::Zilla::Plugin::Run::AfterRelease", "config" : { "Dist::Zilla::Plugin::Run::Role::Runner" : { "eval" : [ "print \"release complete!\\xa\"" ], "fatal_errors" : 1, "quiet" : 1, "version" : "0.046" } }, "name" : "@Author::ETHER/release complete", "version" : "0.046" }, { "class" : "Dist::Zilla::Plugin::ConfirmRelease", "name" : "@Author::ETHER/ConfirmRelease", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Prereqs", "config" : { "Dist::Zilla::Plugin::Prereqs" : { "phase" : "develop", "type" : "suggests" } }, "name" : "@Author::ETHER/prereqs for @Author::ETHER", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::Substitute", "name" : "Substitute", "version" : "0.006" }, { "class" : "Dist::Zilla::Plugin::Prereqs::Soften", "config" : { "Dist::Zilla::Plugin::Prereqs::Soften" : { "copy_to" : [ "develop.requires" ], "modules" : [ "Capture::Tiny", "Sub::Name", "Sub::Util" ], "modules_from_features" : null, "to_relationship" : "suggests" } }, "name" : "Prereqs::Soften", "version" : "0.006003" }, { "class" : "Dist::Zilla::Plugin::OnlyCorePrereqs", "config" : { "Dist::Zilla::Plugin::OnlyCorePrereqs" : { "also_disallow" : [], "check_dual_life_versions" : "0", "deprecated_ok" : 0, "phases" : [ "configure", "build", "runtime", "test" ], "skips" : [], "starting_version" : "to be determined from perl prereq" } }, "name" : "OnlyCorePrereqs", "version" : "0.024" }, { "class" : "Dist::Zilla::Plugin::Breaks", "name" : "Breaks", "version" : "0.004" }, { "class" : "Dist::Zilla::Plugin::Test::CheckBreaks", "config" : { "Dist::Zilla::Plugin::Test::CheckBreaks" : { "conflicts_module" : [], "no_forced_deps" : 1 }, "Dist::Zilla::Role::ModuleMetadata" : { "Module::Metadata" : "1.000033", "version" : "0.004" } }, "name" : "Test::CheckBreaks", "version" : "0.019" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":InstallModules", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":IncModules", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":TestFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExtraTestFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ExecFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":PerlExecFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":ShareFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":MainModule", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":AllFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::FinderCode", "name" : ":NoFiles", "version" : "6.010" }, { "class" : "Dist::Zilla::Plugin::VerifyPhases", "name" : "@Author::ETHER/PHASE VERIFICATION", "version" : "0.016" } ], "zilla" : { "class" : "Dist::Zilla::Dist::Builder", "config" : { "is_trial" : 0 }, "version" : "6.010" } }, "x_authority" : "cpan:NUFFIN", "x_breaks" : { "Try::Tiny::Except" : "<= 0.01" }, "x_contributors" : [ "Karen Etheridge ", "Peter Rabbitson ", "Ricardo Signes ", "Mark Fowler ", "Graham Knop ", "Lukas Mai ", "Aristotle Pagaltzis ", "Dagfinn Ilmari MannsÃ¥ker ", "Paul Howarth ", "Rudolf Leermakers ", "anaxagoras ", "awalker ", "chromatic ", "Alex ", "cm-perl ", "Andrew Yates ", "David Lowe ", "Glenn Fowler ", "Hans Dieter Pearcey ", "Jens Berthold ", "Jonathan Yu ", "Marc Mims ", "Mark Stosberg ", "Pali " ], "x_serialization_backend" : "Cpanel::JSON::XS version 3.0239", "x_use_unsafe_inc" : 0 } PK!:+c c Dperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0207/install.jsonnuÏÃ6Ç${"provides":{"XML::LibXML::PI":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Pattern":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::SAX":{"version":2.0207,"file":"lib/XML/LibXML/SAX.pm"},"XML::LibXML::XPathContext":{"version":2.0207,"file":"lib/XML/LibXML/XPathContext.pm"},"XML::LibXML::SAX::AttributeNode":{"version":2.0207,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::SAX::Generator":{"version":2.0207,"file":"lib/XML/LibXML/SAX/Generator.pm"},"XML::LibXML::XPathExpression":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::NodeList":{"version":2.0207,"file":"lib/XML/LibXML/NodeList.pm"},"XML::LibXML::Error":{"version":2.0207,"file":"lib/XML/LibXML/Error.pm"},"XML::LibXML::RegExp":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::_SAXParser":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::InputCallback":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Devel":{"version":2.0207,"file":"lib/XML/LibXML/Devel.pm"},"XML::LibXML::Boolean":{"version":2.0207,"file":"lib/XML/LibXML/Boolean.pm"},"XML::LibXML::AttributeHash":{"version":2.0207,"file":"lib/XML/LibXML/AttributeHash.pm"},"XML::LibXML":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Literal":{"version":2.0207,"file":"lib/XML/LibXML/Literal.pm"},"XML::LibXML::Reader":{"version":2.0207,"file":"lib/XML/LibXML/Reader.pm"},"XML::LibXML::SAX::Builder":{"version":2.0207,"file":"lib/XML/LibXML/SAX/Builder.pm"},"XML::LibXML::Schema":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Element":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Attr":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Node":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::CDATASection":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Number":{"version":2.0207,"file":"lib/XML/LibXML/Number.pm"},"XML::LibXML::Namespace":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::ErrNo":{"version":2.0207,"file":"lib/XML/LibXML/ErrNo.pm"},"XML::LibXML::SAX::Parser":{"version":2.0207,"file":"lib/XML/LibXML/SAX/Parser.pm"},"XML::LibXML::Dtd":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::NamedNodeMap":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Common":{"version":2.0207,"file":"lib/XML/LibXML/Common.pm"},"XML::LibXML::Comment":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Document":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::DocumentFragment":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::RelaxNG":{"version":2.0207,"file":"LibXML.pm"},"XML::LibXML::Text":{"version":2.0207,"file":"LibXML.pm"}},"target":"XML::LibXML","version":2.0207,"name":"XML::LibXML","dist":"XML-LibXML-2.0207","pathname":"S/SH/SHLOMIF/XML-LibXML-2.0207.tar.gz"}PK!]G#Û Û Cperl5/x86_64-linux-thread-multi/.meta/XML-LibXML-2.0207/MYMETA.jsonnuÏÃ6Ç${ "abstract" : "Interface to Gnome libxml2 xml parsing and DOM library", "author" : [ "Petr Pajas " ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.60, CPAN::Meta::Converter version 2.150010, CPAN::Meta::Converter version 2.143240", "keywords" : [ "dom", "html", "libxml", "object oriented", "oop", "parse", "parser", "parsing", "pullparser", "sax", "sgml", "xml", "xpath", "XPath", "xs" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-LibXML", "no_index" : { "directory" : [ "t", "inc", "xt" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "Alien::Base::Wrapper" : "0", "Alien::Libxml2" : "0.14", "Config" : "0", "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "DynaLoader" : "0", "Encode" : "0", "Exporter" : "5.57", "IO::Handle" : "0", "Scalar::Util" : "0", "Tie::Hash" : "0", "XML::NamespaceSupport" : "1.07", "XML::SAX" : "0.11", "XML::SAX::Base" : "0", "XML::SAX::DocumentLocator" : "0", "XML::SAX::Exception" : "0", "base" : "0", "constant" : "0", "overload" : "0", "parent" : "0", "perl" : "5.008001", "strict" : "0", "vars" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Config" : "0", "Errno" : "0", "IO::File" : "0", "IO::Handle" : "0", "POSIX" : "0", "Scalar::Util" : "0", "Test::More" : "0", "locale" : "0", "utf8" : "0" } } }, "release_status" : "stable", "resources" : { "repository" : { "type" : "git", "url" : "https://github.com/shlomif/perl-XML-LibXML.git", "web" : "https://github.com/shlomif/perl-XML-LibXML" } }, "version" : "2.0207", "x_serialization_backend" : "JSON::PP version 4.06" } PK!×È@I I perl5/Digest/HMAC.pmnuÏÃ6Ç$package Digest::HMAC; $VERSION = "1.03"; use strict; # OO interface sub new { my($class, $key, $hasher, $block_size) = @_; $block_size ||= 64; $key = $hasher->new->add($key)->digest if length($key) > $block_size; my $self = bless {}, $class; $self->{k_ipad} = $key ^ (chr(0x36) x $block_size); $self->{k_opad} = $key ^ (chr(0x5c) x $block_size); $self->{hasher} = $hasher->new->add($self->{k_ipad}); $self; } sub reset { my $self = shift; $self->{hasher}->reset->add($self->{k_ipad}); $self; } sub add { my $self = shift; $self->{hasher}->add(@_); $self; } sub addfile { my $self = shift; $self->{hasher}->addfile(@_); $self; } sub _digest { my $self = shift; my $inner_digest = $self->{hasher}->digest; $self->{hasher}->reset->add($self->{k_opad}, $inner_digest); } sub digest { shift->_digest->digest; } sub hexdigest { shift->_digest->hexdigest; } sub b64digest { shift->_digest->b64digest; } # Functional interface require Exporter; *import = \&Exporter::import; use vars qw(@EXPORT_OK); @EXPORT_OK = qw(hmac hmac_hex); sub hmac { my($data, $key, $hash_func, $block_size) = @_; $block_size ||= 64; $key = &$hash_func($key) if length($key) > $block_size; my $k_ipad = $key ^ (chr(0x36) x $block_size); my $k_opad = $key ^ (chr(0x5c) x $block_size); &$hash_func($k_opad, &$hash_func($k_ipad, $data)); } sub hmac_hex { unpack("H*", &hmac); } 1; __END__ =head1 NAME Digest::HMAC - Keyed-Hashing for Message Authentication =head1 SYNOPSIS # Functional style use Digest::HMAC qw(hmac hmac_hex); $digest = hmac($data, $key, \&myhash); print hmac_hex($data, $key, \&myhash); # OO style use Digest::HMAC; $hmac = Digest::HMAC->new($key, "Digest::MyHash"); $hmac->add($data); $hmac->addfile(*FILE); $digest = $hmac->digest; $digest = $hmac->hexdigest; $digest = $hmac->b64digest; =head1 DESCRIPTION HMAC is used for message integrity checks between two parties that share a secret key, and works in combination with some other Digest algorithm, usually MD5 or SHA-1. The HMAC mechanism is described in RFC 2104. HMAC follow the common C interface, but the constructor takes the secret key and the name of some other simple C as argument. The hmac() and hmac_hex() functions and the Digest::HMAC->new() constructor takes an optional $blocksize argument as well. The HMAC algorithm assumes the digester to hash by iterating a basic compression function on blocks of data and the $blocksize should match the byte-length of such blocks. The default $blocksize is 64 which is suitable for the MD5 and SHA-1 digest functions. For stronger algorithms the blocksize probably needs to be increased. =head1 SEE ALSO L, L RFC 2104 =head1 AUTHORS Graham Barr , Gisle Aas =cut PK!?ø\H‹‹perl5/Digest/HMAC_SHA1.pmnuÏÃ6Ç$package Digest::HMAC_SHA1; $VERSION="1.03"; use strict; use Digest::SHA qw(sha1); use Digest::HMAC qw(hmac); # OO interface use vars qw(@ISA); @ISA=qw(Digest::HMAC); sub new { my $class = shift; $class->SUPER::new($_[0], "Digest::SHA", 64); # Digest::SHA defaults to SHA-1 } # Functional interface require Exporter; *import = \&Exporter::import; use vars qw(@EXPORT_OK); @EXPORT_OK=qw(hmac_sha1 hmac_sha1_hex); sub hmac_sha1 { hmac($_[0], $_[1], \&sha1, 64); } sub hmac_sha1_hex { unpack("H*", &hmac_sha1) } 1; __END__ =head1 NAME Digest::HMAC_SHA1 - Keyed-Hashing for Message Authentication =head1 SYNOPSIS # Functional style use Digest::HMAC_SHA1 qw(hmac_sha1 hmac_sha1_hex); $digest = hmac_sha1($data, $key); print hmac_sha1_hex($data, $key); # OO style use Digest::HMAC_SHA1; $hmac = Digest::HMAC_SHA1->new($key); $hmac->add($data); $hmac->addfile(*FILE); $digest = $hmac->digest; $digest = $hmac->hexdigest; $digest = $hmac->b64digest; =head1 DESCRIPTION This module provide HMAC-SHA-1 hashing. =head1 SEE ALSO L, L, L =head1 AUTHOR Gisle Aas =cut PK!ªÄ[QZZperl5/Digest/HMAC_MD5.pmnuÏÃ6Ç$package Digest::HMAC_MD5; $VERSION="1.01"; use strict; use Digest::MD5 qw(md5); use Digest::HMAC qw(hmac); # OO interface use vars qw(@ISA); @ISA=qw(Digest::HMAC); sub new { my $class = shift; $class->SUPER::new($_[0], "Digest::MD5", 64); } # Functional interface require Exporter; *import = \&Exporter::import; use vars qw(@EXPORT_OK); @EXPORT_OK=qw(hmac_md5 hmac_md5_hex); sub hmac_md5 { hmac($_[0], $_[1], \&md5, 64); } sub hmac_md5_hex { unpack("H*", &hmac_md5) } 1; __END__ =head1 NAME Digest::HMAC_MD5 - Keyed-Hashing for Message Authentication =head1 SYNOPSIS # Functional style use Digest::HMAC_MD5 qw(hmac_md5 hmac_md5_hex); $digest = hmac_md5($data, $key); print hmac_md5_hex($data, $key); # OO style use Digest::HMAC_MD5; $hmac = Digest::HMAC_MD5->new($key); $hmac->add($data); $hmac->addfile(*FILE); $digest = $hmac->digest; $digest = $hmac->hexdigest; $digest = $hmac->b64digest; =head1 DESCRIPTION This module provide HMAC-MD5 hashing. =head1 SEE ALSO L, L, L =head1 AUTHOR Gisle Aas =cut PK!«ÂÂÞ¬T¬T perl5/LWP.pmnuÏÃ6Ç$package LWP; our $VERSION = '6.49'; require LWP::UserAgent; # this should load everything you need sub Version { $VERSION; } 1; __END__ =pod =encoding utf-8 =head1 NAME LWP - The World-Wide Web library for Perl =head1 SYNOPSIS use LWP; print "This is libwww-perl-$LWP::VERSION\n"; =head1 DESCRIPTION The libwww-perl collection is a set of Perl modules which provides a simple and consistent application programming interface (API) to the World-Wide Web. The main focus of the library is to provide classes and functions that allow you to write WWW clients. The library also contain modules that are of more general use and even classes that help you implement simple HTTP servers. Most modules in this library provide an object oriented API. The user agent, requests sent and responses received from the WWW server are all represented by objects. This makes a simple and powerful interface to these services. The interface is easy to extend and customize for your own needs. The main features of the library are: =over 3 =item * Contains various reusable components (modules) that can be used separately or together. =item * Provides an object oriented model of HTTP-style communication. Within this framework we currently support access to C, C, C, C, C, C, and C resources. =item * Provides a full object oriented interface or a very simple procedural interface. =item * Supports the basic and digest authorization schemes. =item * Supports transparent redirect handling. =item * Supports access through proxy servers. =item * Provides parser for F files and a framework for constructing robots. =item * Supports parsing of HTML forms. =item * Implements HTTP content negotiation algorithm that can be used both in protocol modules and in server scripts (like CGI scripts). =item * Supports HTTP cookies. =item * Some simple command line clients, for instance C and C. =back =head1 HTTP STYLE COMMUNICATION The libwww-perl library is based on HTTP style communication. This section tries to describe what that means. Let us start with this quote from the HTTP specification document : =over 3 =item * The HTTP protocol is based on a request/response paradigm. A client establishes a connection with a server and sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content. The server responds with a status line, including the message's protocol version and a success or error code, followed by a MIME-like message containing server information, entity meta-information, and possible body content. =back What this means to libwww-perl is that communication always take place through these steps: First a I object is created and configured. This object is then passed to a server and we get a I object in return that we can examine. A request is always independent of any previous requests, i.e. the service is stateless. The same simple model is used for any kind of service we want to access. For example, if we want to fetch a document from a remote file server, then we send it a request that contains a name for that document and the response will contain the document itself. If we access a search engine, then the content of the request will contain the query parameters and the response will contain the query result. If we want to send a mail message to somebody then we send a request object which contains our message to the mail server and the response object will contain an acknowledgment that tells us that the message has been accepted and will be forwarded to the recipient(s). It is as simple as that! =head2 The Request Object The libwww-perl request object has the class name L. The fact that the class name uses C as a prefix only implies that we use the HTTP model of communication. It does not limit the kind of services we can try to pass this I to. For instance, we will send Ls both to ftp and gopher servers, as well as to the local file system. The main attributes of the request objects are: =over 3 =item * B is a short string that tells what kind of request this is. The most common methods are B, B, B and B. =item * B is a string denoting the protocol, server and the name of the "document" we want to access. The B might also encode various other parameters. =item * B contains additional information about the request and can also used to describe the content. The headers are a set of keyword/value pairs. =item * B is an arbitrary amount of data. =back =head2 The Response Object The libwww-perl response object has the class name L. The main attributes of objects of this class are: =over 3 =item * B is a numerical value that indicates the overall outcome of the request. =item * B is a short, human readable string that corresponds to the I. =item * B contains additional information about the response and describe the content. =item * B is an arbitrary amount of data. =back Since we don't want to handle all possible I values directly in our programs, a libwww-perl response object has methods that can be used to query what kind of response this is. The most commonly used response classification methods are: =over 3 =item is_success() The request was successfully received, understood or accepted. =item is_error() The request failed. The server or the resource might not be available, access to the resource might be denied or other things might have failed for some reason. =back =head2 The User Agent Let us assume that we have created a I object. What do we actually do with it in order to receive a I? The answer is that you pass it to a I object and this object takes care of all the things that need to be done (like low-level communication and error handling) and returns a I object. The user agent represents your application on the network and provides you with an interface that can accept I and return I. The user agent is an interface layer between your application code and the network. Through this interface you are able to access the various servers on the network. The class name for the user agent is L. Every libwww-perl application that wants to communicate should create at least one object of this class. The main method provided by this object is request(). This method takes an L object as argument and (eventually) returns a L object. The user agent has many other attributes that let you configure how it will interact with the network and with your application. =over 3 =item * B specifies how much time we give remote servers to respond before the library disconnects and creates an internal I response. =item * B specifies the name that your application uses when it presents itself on the network. =item * B can be set to the e-mail address of the person responsible for running the application. If this is set, then the address will be sent to the servers with every request. =item * B specifies whether we should initialize response headers from the Ehead> section of HTML documents. =item * B and B specify if and when to go through a proxy server. =item * B provides a way to set up user names and passwords needed to access certain services. =back Many applications want even more control over how they interact with the network and they get this by sub-classing L. The library includes a sub-class, L, for robot applications. =head2 An Example This example shows how the user agent, a request and a response are represented in actual perl code: # Create a user agent object use LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->agent("MyApp/0.1 "); # Create a request my $req = HTTP::Request->new(POST => 'http://search.cpan.org/search'); $req->content_type('application/x-www-form-urlencoded'); $req->content('query=libwww-perl&mode=dist'); # Pass request to the user agent and get a response back my $res = $ua->request($req); # Check the outcome of the response if ($res->is_success) { print $res->content; } else { print $res->status_line, "\n"; } The $ua is created once when the application starts up. New request objects should normally created for each request sent. =head1 NETWORK SUPPORT This section discusses the various protocol schemes and the HTTP style methods that headers may be used for each. For all requests, a "User-Agent" header is added and initialized from the $ua->agent attribute before the request is handed to the network layer. In the same way, a "From" header is initialized from the $ua->from attribute. For all responses, the library adds a header called "Client-Date". This header holds the time when the response was received by your application. The format and semantics of the header are the same as the server created "Date" header. You may also encounter other "Client-XXX" headers. They are all generated by the library internally and are not received from the servers. =head2 HTTP Requests HTTP requests are just handed off to an HTTP server and it decides what happens. Few servers implement methods beside the usual "GET", "HEAD", "POST" and "PUT", but CGI-scripts may implement any method they like. If the server is not available then the library will generate an internal error response. The library automatically adds a "Host" and a "Content-Length" header to the HTTP request before it is sent over the network. For a GET request you might want to add a "If-Modified-Since" or "If-None-Match" header to make the request conditional. For a POST request you should add the "Content-Type" header. When you try to emulate HTML EFORM> handling you should usually let the value of the "Content-Type" header be "application/x-www-form-urlencoded". See L for examples of this. The libwww-perl HTTP implementation currently support the HTTP/1.1 and HTTP/1.0 protocol. The library allows you to access proxy server through HTTP. This means that you can set up the library to forward all types of request through the HTTP protocol module. See L for documentation of this. =head2 HTTPS Requests HTTPS requests are HTTP requests over an encrypted network connection using the SSL protocol developed by Netscape. Everything about HTTP requests above also apply to HTTPS requests. In addition the library will add the headers "Client-SSL-Cipher", "Client-SSL-Cert-Subject" and "Client-SSL-Cert-Issuer" to the response. These headers denote the encryption method used and the name of the server owner. The request can contain the header "If-SSL-Cert-Subject" in order to make the request conditional on the content of the server certificate. If the certificate subject does not match, no request is sent to the server and an internally generated error response is returned. The value of the "If-SSL-Cert-Subject" header is interpreted as a Perl regular expression. =head2 FTP Requests The library currently supports GET, HEAD and PUT requests. GET retrieves a file or a directory listing from an FTP server. PUT stores a file on a ftp server. You can specify a ftp account for servers that want this in addition to user name and password. This is specified by including an "Account" header in the request. User name/password can be specified using basic authorization or be encoded in the URL. Failed logins return an UNAUTHORIZED response with "WWW-Authenticate: Basic" and can be treated like basic authorization for HTTP. The library supports ftp ASCII transfer mode by specifying the "type=a" parameter in the URL. It also supports transfer of ranges for FTP transfers using the "Range" header. Directory listings are by default returned unprocessed (as returned from the ftp server) with the content media type reported to be "text/ftp-dir-listing". The L module provides methods for parsing of these directory listing. The ftp module is also able to convert directory listings to HTML and this can be requested via the standard HTTP content negotiation mechanisms (add an "Accept: text/html" header in the request if you want this). For normal file retrievals, the "Content-Type" is guessed based on the file name suffix. See L. The "If-Modified-Since" request header works for servers that implement the C command. It will probably not work for directory listings though. Example: $req = HTTP::Request->new(GET => 'ftp://me:passwd@ftp.some.where.com/'); $req->header(Accept => "text/html, */*;q=0.1"); =head2 News Requests Access to the USENET News system is implemented through the NNTP protocol. The name of the news server is obtained from the NNTP_SERVER environment variable and defaults to "news". It is not possible to specify the hostname of the NNTP server in news: URLs. The library supports GET and HEAD to retrieve news articles through the NNTP protocol. You can also post articles to newsgroups by using (surprise!) the POST method. GET on newsgroups is not implemented yet. Examples: $req = HTTP::Request->new(GET => 'news:abc1234@a.sn.no'); $req = HTTP::Request->new(POST => 'news:comp.lang.perl.test'); $req->header(Subject => 'This is a test', From => 'me@some.where.org'); $req->content(<new(GET => 'gopher://gopher.sn.no/'); =head2 File Request The library supports GET and HEAD methods for file requests. The "If-Modified-Since" header is supported. All other headers are ignored. The I component of the file URL must be empty or set to "localhost". Any other I value will be treated as an error. Directories are always converted to an HTML document. For normal files, the "Content-Type" and "Content-Encoding" in the response are guessed based on the file suffix. Example: $req = HTTP::Request->new(GET => 'file:/etc/passwd'); =head2 Mailto Request You can send (aka "POST") mail messages using the library. All headers specified for the request are passed on to the mail system. The "To" header is initialized from the mail address in the URL. Example: $req = HTTP::Request->new(POST => 'mailto:libwww@perl.org'); $req->header(Subject => "subscribe"); $req->content("Please subscribe me to the libwww-perl mailing list!\n"); =head2 CPAN Requests URLs with scheme C are redirected to a suitable CPAN mirror. If you have your own local mirror of CPAN you might tell LWP to use it for C URLs by an assignment like this: $LWP::Protocol::cpan::CPAN = "file:/local/CPAN/"; Suitable CPAN mirrors are also picked up from the configuration for the CPAN.pm, so if you have used that module a suitable mirror should be picked automatically. If neither of these apply, then a redirect to the generic CPAN http location is issued. Example request to download the newest perl: $req = HTTP::Request->new(GET => "cpan:src/latest.tar.gz"); =head1 OVERVIEW OF CLASSES AND PACKAGES This table should give you a quick overview of the classes provided by the library. Indentation shows class inheritance. LWP::MemberMixin -- Access to member variables of Perl5 classes LWP::UserAgent -- WWW user agent class LWP::RobotUA -- When developing a robot applications LWP::Protocol -- Interface to various protocol schemes LWP::Protocol::http -- http:// access LWP::Protocol::file -- file:// access LWP::Protocol::ftp -- ftp:// access ... LWP::Authen::Basic -- Handle 401 and 407 responses LWP::Authen::Digest HTTP::Headers -- MIME/RFC822 style header (used by HTTP::Message) HTTP::Message -- HTTP style message HTTP::Request -- HTTP request HTTP::Response -- HTTP response HTTP::Daemon -- A HTTP server class WWW::RobotRules -- Parse robots.txt files WWW::RobotRules::AnyDBM_File -- Persistent RobotRules Net::HTTP -- Low level HTTP client The following modules provide various functions and definitions. LWP -- This file. Library version number and documentation. LWP::MediaTypes -- MIME types configuration (text/html etc.) LWP::Simple -- Simplified procedural interface for common functions HTTP::Status -- HTTP status code (200 OK etc) HTTP::Date -- Date parsing module for HTTP date formats HTTP::Negotiate -- HTTP content negotiation calculation File::Listing -- Parse directory listings HTML::Form -- Processing for
s in HTML documents =head1 MORE DOCUMENTATION All modules contain detailed information on the interfaces they provide. The L manpage is the libwww-perl cookbook that contain examples of typical usage of the library. You might want to take a look at how the scripts L, L, L and L are implemented. =head1 ENVIRONMENT The following environment variables are used by LWP: =over =item HOME The L functions will look for the F<.media.types> and F<.mime.types> files relative to you home directory. =item http_proxy =item ftp_proxy =item xxx_proxy =item no_proxy These environment variables can be set to enable communication through a proxy server. See the description of the C method in L. =item PERL_LWP_ENV_PROXY If set to a TRUE value, then the L will by default call C during initialization. This makes LWP honor the proxy variables described above. =item PERL_LWP_SSL_VERIFY_HOSTNAME The default C setting for L. If not set the default will be 1. Set it as 0 to disable hostname verification (the default prior to libwww-perl 5.840. =item PERL_LWP_SSL_CA_FILE =item PERL_LWP_SSL_CA_PATH The file and/or directory where the trusted Certificate Authority certificates is located. See L for details. =item PERL_HTTP_URI_CLASS Used to decide what URI objects to instantiate. The default is L. You might want to set it to L for compatibility with old times. =back =head1 AUTHORS LWP was made possible by contributions from Adam Newby, Albert Dvornik, Alexandre Duret-Lutz, Andreas Gustafsson, Andreas König, Andrew Pimlott, Andy Lester, Ben Coleman, Benjamin Low, Ben Low, Ben Tilly, Blair Zajac, Bob Dalgleish, BooK, Brad Hughes, Brian J. Murrell, Brian McCauley, Charles C. Fu, Charles Lane, Chris Nandor, Christian Gilmore, Chris W. Unger, Craig Macdonald, Dale Couch, Dan Kubb, Dave Dunkin, Dave W. Smith, David Coppit, David Dick, David D. Kilzer, Doug MacEachern, Edward Avis, erik, Gary Shea, Gisle Aas, Graham Barr, Gurusamy Sarathy, Hans de Graaff, Harald Joerg, Harry Bochner, Hugo, Ilya Zakharevich, INOUE Yoshinari, Ivan Panchenko, Jack Shirazi, James Tillman, Jan Dubois, Jared Rhine, Jim Stern, Joao Lopes, John Klar, Johnny Lee, Josh Kronengold, Josh Rai, Joshua Chamas, Joshua Hoblitt, Kartik Subbarao, Keiichiro Nagano, Ken Williams, KONISHI Katsuhiro, Lee T Lindley, Liam Quinn, Marc Hedlund, Marc Langheinrich, Mark D. Anderson, Marko Asplund, Mark Stosberg, Markus B Krüger, Markus Laker, Martijn Koster, Martin Thurn, Matthew Eldridge, Matthew.van.Eerde, Matt Sergeant, Michael A. Chase, Michael Quaranta, Michael Thompson, Mike Schilli, Moshe Kaminsky, Nathan Torkington, Nicolai Langfeldt, Norton Allen, Olly Betts, Paul J. Schinder, peterm, Philip Guenther, Daniel Buenzli, Pon Hwa Lin, Radoslaw Zielinski, Radu Greab, Randal L. Schwartz, Richard Chen, Robin Barker, Roy Fielding, Sander van Zoest, Sean M. Burke, shildreth, Slaven Rezic, Steve A Fink, Steve Hay, Steven Butler, Steve_Kilbane, Takanori Ugai, Thomas Lotterer, Tim Bunce, Tom Hughes, Tony Finch, Ville Skyttä, Ward Vandewege, William York, Yale Huang, and Yitzchak Scott-Thoennes. LWP owes a lot in motivation, design, and code, to the libwww-perl library for Perl4 by Roy Fielding, which included work from Alberto Accomazzi, James Casey, Brooks Cutter, Martijn Koster, Oscar Nierstrasz, Mel Melchner, Gertjan van Oosten, Jared Rhine, Jack Shirazi, Gene Spafford, Marc VanHeyningen, Steven E. Brenner, Marion Hakanson, Waldemar Kebsch, Tony Sanders, and Larry Wall; see the libwww-perl-0.40 library for details. =head1 COPYRIGHT Copyright 1995-2009, Gisle Aas Copyright 1995, Martijn Koster This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 AVAILABILITY The latest version of this library is likely to be available from CPAN as well as: http://github.com/libwww-perl/libwww-perl The best place to discuss this code is on the mailing list. =cut PK!¬«õririperl5/CPAN/Meta/YAML.pmnuÏÃ6Ç$use 5.008001; # sane UTF-8 support use strict; use warnings; package CPAN::Meta::YAML; # git description: v1.68-2-gcc5324e # XXX-INGY is 5.8.1 too old/broken for utf8? # XXX-XDG Lancaster consensus was that it was sufficient until # proven otherwise $CPAN::Meta::YAML::VERSION = '0.018'; ; # original $VERSION removed by Doppelgaenger ##################################################################### # The CPAN::Meta::YAML API. # # These are the currently documented API functions/methods and # exports: use Exporter; our @ISA = qw{ Exporter }; our @EXPORT = qw{ Load Dump }; our @EXPORT_OK = qw{ LoadFile DumpFile freeze thaw }; ### # Functional/Export API: sub Dump { return CPAN::Meta::YAML->new(@_)->_dump_string; } # XXX-INGY Returning last document seems a bad behavior. # XXX-XDG I think first would seem more natural, but I don't know # that it's worth changing now sub Load { my $self = CPAN::Meta::YAML->_load_string(@_); if ( wantarray ) { return @$self; } else { # To match YAML.pm, return the last document return $self->[-1]; } } # XXX-INGY Do we really need freeze and thaw? # XXX-XDG I don't think so. I'd support deprecating them. BEGIN { *freeze = \&Dump; *thaw = \&Load; } sub DumpFile { my $file = shift; return CPAN::Meta::YAML->new(@_)->_dump_file($file); } sub LoadFile { my $file = shift; my $self = CPAN::Meta::YAML->_load_file($file); if ( wantarray ) { return @$self; } else { # Return only the last document to match YAML.pm, return $self->[-1]; } } ### # Object Oriented API: # Create an empty CPAN::Meta::YAML object # XXX-INGY Why do we use ARRAY object? # NOTE: I get it now, but I think it's confusing and not needed. # Will change it on a branch later, for review. # # XXX-XDG I don't support changing it yet. It's a very well-documented # "API" of CPAN::Meta::YAML. I'd support deprecating it, but Adam suggested # we not change it until YAML.pm's own OO API is established so that # users only have one API change to digest, not two sub new { my $class = shift; bless [ @_ ], $class; } # XXX-INGY It probably doesn't matter, and it's probably too late to # change, but 'read/write' are the wrong names. Read and Write # are actions that take data from storage to memory # characters/strings. These take the data to/from storage to native # Perl objects, which the terms dump and load are meant. As long as # this is a legacy quirk to CPAN::Meta::YAML it's ok, but I'd prefer not # to add new {read,write}_* methods to this API. sub read_string { my $self = shift; $self->_load_string(@_); } sub write_string { my $self = shift; $self->_dump_string(@_); } sub read { my $self = shift; $self->_load_file(@_); } sub write { my $self = shift; $self->_dump_file(@_); } ##################################################################### # Constants # Printed form of the unprintable characters in the lowest range # of ASCII characters, listed by ASCII ordinal position. my @UNPRINTABLE = qw( 0 x01 x02 x03 x04 x05 x06 a b t n v f r x0E x0F x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x1A e x1C x1D x1E x1F ); # Printable characters for escapes my %UNESCAPES = ( 0 => "\x00", z => "\x00", N => "\x85", a => "\x07", b => "\x08", t => "\x09", n => "\x0a", v => "\x0b", f => "\x0c", r => "\x0d", e => "\x1b", '\\' => '\\', ); # XXX-INGY # I(ngy) need to decide if these values should be quoted in # CPAN::Meta::YAML or not. Probably yes. # These 3 values have special meaning when unquoted and using the # default YAML schema. They need quotes if they are strings. my %QUOTE = map { $_ => 1 } qw{ null true false }; # The commented out form is simpler, but overloaded the Perl regex # engine due to recursion and backtracking problems on strings # larger than 32,000ish characters. Keep it for reference purposes. # qr/\"((?:\\.|[^\"])*)\"/ my $re_capture_double_quoted = qr/\"([^\\"]*(?:\\.[^\\"]*)*)\"/; my $re_capture_single_quoted = qr/\'([^\']*(?:\'\'[^\']*)*)\'/; # unquoted re gets trailing space that needs to be stripped my $re_capture_unquoted_key = qr/([^:]+(?::+\S(?:[^:]*|.*?(?=:)))*)(?=\s*\:(?:\s+|$))/; my $re_trailing_comment = qr/(?:\s+\#.*)?/; my $re_key_value_separator = qr/\s*:(?:\s+(?:\#.*)?|$)/; ##################################################################### # CPAN::Meta::YAML Implementation. # # These are the private methods that do all the work. They may change # at any time. ### # Loader functions: # Create an object from a file sub _load_file { my $class = ref $_[0] ? ref shift : shift; # Check the file my $file = shift or $class->_error( 'You did not specify a file name' ); $class->_error( "File '$file' does not exist" ) unless -e $file; $class->_error( "'$file' is a directory, not a file" ) unless -f _; $class->_error( "Insufficient permissions to read '$file'" ) unless -r _; # Open unbuffered with strict UTF-8 decoding and no translation layers open( my $fh, "<:unix:encoding(UTF-8)", $file ); unless ( $fh ) { $class->_error("Failed to open file '$file': $!"); } # flock if available (or warn if not possible for OS-specific reasons) if ( _can_flock() ) { flock( $fh, Fcntl::LOCK_SH() ) or warn "Couldn't lock '$file' for reading: $!"; } # slurp the contents my $contents = eval { use warnings FATAL => 'utf8'; local $/; <$fh> }; if ( my $err = $@ ) { $class->_error("Error reading from file '$file': $err"); } # close the file (release the lock) unless ( close $fh ) { $class->_error("Failed to close file '$file': $!"); } $class->_load_string( $contents ); } # Create an object from a string sub _load_string { my $class = ref $_[0] ? ref shift : shift; my $self = bless [], $class; my $string = $_[0]; eval { unless ( defined $string ) { die \"Did not provide a string to load"; } # Check if Perl has it marked as characters, but it's internally # inconsistent. E.g. maybe latin1 got read on a :utf8 layer if ( utf8::is_utf8($string) && ! utf8::valid($string) ) { die \<<'...'; Read an invalid UTF-8 string (maybe mixed UTF-8 and 8-bit character set). Did you decode with lax ":utf8" instead of strict ":encoding(UTF-8)"? ... } # Ensure Unicode character semantics, even for 0x80-0xff utf8::upgrade($string); # Check for and strip any leading UTF-8 BOM $string =~ s/^\x{FEFF}//; # Check for some special cases return $self unless length $string; # Split the file into lines my @lines = grep { ! /^\s*(?:\#.*)?\z/ } split /(?:\015{1,2}\012|\015|\012)/, $string; # Strip the initial YAML header @lines and $lines[0] =~ /^\%YAML[: ][\d\.]+.*\z/ and shift @lines; # A nibbling parser my $in_document = 0; while ( @lines ) { # Do we have a document header? if ( $lines[0] =~ /^---\s*(?:(.+)\s*)?\z/ ) { # Handle scalar documents shift @lines; if ( defined $1 and $1 !~ /^(?:\#.+|\%YAML[: ][\d\.]+)\z/ ) { push @$self, $self->_load_scalar( "$1", [ undef ], \@lines ); next; } $in_document = 1; } if ( ! @lines or $lines[0] =~ /^(?:---|\.\.\.)/ ) { # A naked document push @$self, undef; while ( @lines and $lines[0] !~ /^---/ ) { shift @lines; } $in_document = 0; # XXX The final '-+$' is to look for -- which ends up being an # error later. } elsif ( ! $in_document && @$self ) { # only the first document can be explicit die \"CPAN::Meta::YAML failed to classify the line '$lines[0]'"; } elsif ( $lines[0] =~ /^\s*\-(?:\s|$|-+$)/ ) { # An array at the root my $document = [ ]; push @$self, $document; $self->_load_array( $document, [ 0 ], \@lines ); } elsif ( $lines[0] =~ /^(\s*)\S/ ) { # A hash at the root my $document = { }; push @$self, $document; $self->_load_hash( $document, [ length($1) ], \@lines ); } else { # Shouldn't get here. @lines have whitespace-only lines # stripped, and previous match is a line with any # non-whitespace. So this clause should only be reachable via # a perlbug where \s is not symmetric with \S # uncoverable statement die \"CPAN::Meta::YAML failed to classify the line '$lines[0]'"; } } }; my $err = $@; if ( ref $err eq 'SCALAR' ) { $self->_error(${$err}); } elsif ( $err ) { $self->_error($err); } return $self; } sub _unquote_single { my ($self, $string) = @_; return '' unless length $string; $string =~ s/\'\'/\'/g; return $string; } sub _unquote_double { my ($self, $string) = @_; return '' unless length $string; $string =~ s/\\"/"/g; $string =~ s{\\([Nnever\\fartz0b]|x([0-9a-fA-F]{2}))} {(length($1)>1)?pack("H2",$2):$UNESCAPES{$1}}gex; return $string; } # Load a YAML scalar string to the actual Perl scalar sub _load_scalar { my ($self, $string, $indent, $lines) = @_; # Trim trailing whitespace $string =~ s/\s*\z//; # Explitic null/undef return undef if $string eq '~'; # Single quote if ( $string =~ /^$re_capture_single_quoted$re_trailing_comment\z/ ) { return $self->_unquote_single($1); } # Double quote. if ( $string =~ /^$re_capture_double_quoted$re_trailing_comment\z/ ) { return $self->_unquote_double($1); } # Special cases if ( $string =~ /^[\'\"!&]/ ) { die \"CPAN::Meta::YAML does not support a feature in line '$string'"; } return {} if $string =~ /^{}(?:\s+\#.*)?\z/; return [] if $string =~ /^\[\](?:\s+\#.*)?\z/; # Regular unquoted string if ( $string !~ /^[>|]/ ) { die \"CPAN::Meta::YAML found illegal characters in plain scalar: '$string'" if $string =~ /^(?:-(?:\s|$)|[\@\%\`])/ or $string =~ /:(?:\s|$)/; $string =~ s/\s+#.*\z//; return $string; } # Error die \"CPAN::Meta::YAML failed to find multi-line scalar content" unless @$lines; # Check the indent depth $lines->[0] =~ /^(\s*)/; $indent->[-1] = length("$1"); if ( defined $indent->[-2] and $indent->[-1] <= $indent->[-2] ) { die \"CPAN::Meta::YAML found bad indenting in line '$lines->[0]'"; } # Pull the lines my @multiline = (); while ( @$lines ) { $lines->[0] =~ /^(\s*)/; last unless length($1) >= $indent->[-1]; push @multiline, substr(shift(@$lines), length($1)); } my $j = (substr($string, 0, 1) eq '>') ? ' ' : "\n"; my $t = (substr($string, 1, 1) eq '-') ? '' : "\n"; return join( $j, @multiline ) . $t; } # Load an array sub _load_array { my ($self, $array, $indent, $lines) = @_; while ( @$lines ) { # Check for a new document if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) { while ( @$lines and $lines->[0] !~ /^---/ ) { shift @$lines; } return 1; } # Check the indent level $lines->[0] =~ /^(\s*)/; if ( length($1) < $indent->[-1] ) { return 1; } elsif ( length($1) > $indent->[-1] ) { die \"CPAN::Meta::YAML found bad indenting in line '$lines->[0]'"; } if ( $lines->[0] =~ /^(\s*\-\s+)[^\'\"]\S*\s*:(?:\s+|$)/ ) { # Inline nested hash my $indent2 = length("$1"); $lines->[0] =~ s/-/ /; push @$array, { }; $self->_load_hash( $array->[-1], [ @$indent, $indent2 ], $lines ); } elsif ( $lines->[0] =~ /^\s*\-\s*\z/ ) { shift @$lines; unless ( @$lines ) { push @$array, undef; return 1; } if ( $lines->[0] =~ /^(\s*)\-/ ) { my $indent2 = length("$1"); if ( $indent->[-1] == $indent2 ) { # Null array entry push @$array, undef; } else { # Naked indenter push @$array, [ ]; $self->_load_array( $array->[-1], [ @$indent, $indent2 ], $lines ); } } elsif ( $lines->[0] =~ /^(\s*)\S/ ) { push @$array, { }; $self->_load_hash( $array->[-1], [ @$indent, length("$1") ], $lines ); } else { die \"CPAN::Meta::YAML failed to classify line '$lines->[0]'"; } } elsif ( $lines->[0] =~ /^\s*\-(\s*)(.+?)\s*\z/ ) { # Array entry with a value shift @$lines; push @$array, $self->_load_scalar( "$2", [ @$indent, undef ], $lines ); } elsif ( defined $indent->[-2] and $indent->[-1] == $indent->[-2] ) { # This is probably a structure like the following... # --- # foo: # - list # bar: value # # ... so lets return and let the hash parser handle it return 1; } else { die \"CPAN::Meta::YAML failed to classify line '$lines->[0]'"; } } return 1; } # Load a hash sub _load_hash { my ($self, $hash, $indent, $lines) = @_; while ( @$lines ) { # Check for a new document if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) { while ( @$lines and $lines->[0] !~ /^---/ ) { shift @$lines; } return 1; } # Check the indent level $lines->[0] =~ /^(\s*)/; if ( length($1) < $indent->[-1] ) { return 1; } elsif ( length($1) > $indent->[-1] ) { die \"CPAN::Meta::YAML found bad indenting in line '$lines->[0]'"; } # Find the key my $key; # Quoted keys if ( $lines->[0] =~ s/^\s*$re_capture_single_quoted$re_key_value_separator// ) { $key = $self->_unquote_single($1); } elsif ( $lines->[0] =~ s/^\s*$re_capture_double_quoted$re_key_value_separator// ) { $key = $self->_unquote_double($1); } elsif ( $lines->[0] =~ s/^\s*$re_capture_unquoted_key$re_key_value_separator// ) { $key = $1; $key =~ s/\s+$//; } elsif ( $lines->[0] =~ /^\s*\?/ ) { die \"CPAN::Meta::YAML does not support a feature in line '$lines->[0]'"; } else { die \"CPAN::Meta::YAML failed to classify line '$lines->[0]'"; } if ( exists $hash->{$key} ) { warn "CPAN::Meta::YAML found a duplicate key '$key' in line '$lines->[0]'"; } # Do we have a value? if ( length $lines->[0] ) { # Yes $hash->{$key} = $self->_load_scalar( shift(@$lines), [ @$indent, undef ], $lines ); } else { # An indent shift @$lines; unless ( @$lines ) { $hash->{$key} = undef; return 1; } if ( $lines->[0] =~ /^(\s*)-/ ) { $hash->{$key} = []; $self->_load_array( $hash->{$key}, [ @$indent, length($1) ], $lines ); } elsif ( $lines->[0] =~ /^(\s*)./ ) { my $indent2 = length("$1"); if ( $indent->[-1] >= $indent2 ) { # Null hash entry $hash->{$key} = undef; } else { $hash->{$key} = {}; $self->_load_hash( $hash->{$key}, [ @$indent, length($1) ], $lines ); } } } } return 1; } ### # Dumper functions: # Save an object to a file sub _dump_file { my $self = shift; require Fcntl; # Check the file my $file = shift or $self->_error( 'You did not specify a file name' ); my $fh; # flock if available (or warn if not possible for OS-specific reasons) if ( _can_flock() ) { # Open without truncation (truncate comes after lock) my $flags = Fcntl::O_WRONLY()|Fcntl::O_CREAT(); sysopen( $fh, $file, $flags ); unless ( $fh ) { $self->_error("Failed to open file '$file' for writing: $!"); } # Use no translation and strict UTF-8 binmode( $fh, ":raw:encoding(UTF-8)"); flock( $fh, Fcntl::LOCK_EX() ) or warn "Couldn't lock '$file' for reading: $!"; # truncate and spew contents truncate $fh, 0; seek $fh, 0, 0; } else { open $fh, ">:unix:encoding(UTF-8)", $file; } # serialize and spew to the handle print {$fh} $self->_dump_string; # close the file (release the lock) unless ( close $fh ) { $self->_error("Failed to close file '$file': $!"); } return 1; } # Save an object to a string sub _dump_string { my $self = shift; return '' unless ref $self && @$self; # Iterate over the documents my $indent = 0; my @lines = (); eval { foreach my $cursor ( @$self ) { push @lines, '---'; # An empty document if ( ! defined $cursor ) { # Do nothing # A scalar document } elsif ( ! ref $cursor ) { $lines[-1] .= ' ' . $self->_dump_scalar( $cursor ); # A list at the root } elsif ( ref $cursor eq 'ARRAY' ) { unless ( @$cursor ) { $lines[-1] .= ' []'; next; } push @lines, $self->_dump_array( $cursor, $indent, {} ); # A hash at the root } elsif ( ref $cursor eq 'HASH' ) { unless ( %$cursor ) { $lines[-1] .= ' {}'; next; } push @lines, $self->_dump_hash( $cursor, $indent, {} ); } else { die \("Cannot serialize " . ref($cursor)); } } }; if ( ref $@ eq 'SCALAR' ) { $self->_error(${$@}); } elsif ( $@ ) { $self->_error($@); } join '', map { "$_\n" } @lines; } sub _has_internal_string_value { my $value = shift; my $b_obj = B::svref_2object(\$value); # for round trip problem return $b_obj->FLAGS & B::SVf_POK(); } sub _dump_scalar { my $string = $_[1]; my $is_key = $_[2]; # Check this before checking length or it winds up looking like a string! my $has_string_flag = _has_internal_string_value($string); return '~' unless defined $string; return "''" unless length $string; if (Scalar::Util::looks_like_number($string)) { # keys and values that have been used as strings get quoted if ( $is_key || $has_string_flag ) { return qq['$string']; } else { return $string; } } if ( $string =~ /[\x00-\x09\x0b-\x0d\x0e-\x1f\x7f-\x9f\'\n]/ ) { $string =~ s/\\/\\\\/g; $string =~ s/"/\\"/g; $string =~ s/\n/\\n/g; $string =~ s/[\x85]/\\N/g; $string =~ s/([\x00-\x1f])/\\$UNPRINTABLE[ord($1)]/g; $string =~ s/([\x7f-\x9f])/'\x' . sprintf("%X",ord($1))/ge; return qq|"$string"|; } if ( $string =~ /(?:^[~!@#%&*|>?:,'"`{}\[\]]|^-+$|\s|:\z)/ or $QUOTE{$string} ) { return "'$string'"; } return $string; } sub _dump_array { my ($self, $array, $indent, $seen) = @_; if ( $seen->{refaddr($array)}++ ) { die \"CPAN::Meta::YAML does not support circular references"; } my @lines = (); foreach my $el ( @$array ) { my $line = (' ' x $indent) . '-'; my $type = ref $el; if ( ! $type ) { $line .= ' ' . $self->_dump_scalar( $el ); push @lines, $line; } elsif ( $type eq 'ARRAY' ) { if ( @$el ) { push @lines, $line; push @lines, $self->_dump_array( $el, $indent + 1, $seen ); } else { $line .= ' []'; push @lines, $line; } } elsif ( $type eq 'HASH' ) { if ( keys %$el ) { push @lines, $line; push @lines, $self->_dump_hash( $el, $indent + 1, $seen ); } else { $line .= ' {}'; push @lines, $line; } } else { die \"CPAN::Meta::YAML does not support $type references"; } } @lines; } sub _dump_hash { my ($self, $hash, $indent, $seen) = @_; if ( $seen->{refaddr($hash)}++ ) { die \"CPAN::Meta::YAML does not support circular references"; } my @lines = (); foreach my $name ( sort keys %$hash ) { my $el = $hash->{$name}; my $line = (' ' x $indent) . $self->_dump_scalar($name, 1) . ":"; my $type = ref $el; if ( ! $type ) { $line .= ' ' . $self->_dump_scalar( $el ); push @lines, $line; } elsif ( $type eq 'ARRAY' ) { if ( @$el ) { push @lines, $line; push @lines, $self->_dump_array( $el, $indent + 1, $seen ); } else { $line .= ' []'; push @lines, $line; } } elsif ( $type eq 'HASH' ) { if ( keys %$el ) { push @lines, $line; push @lines, $self->_dump_hash( $el, $indent + 1, $seen ); } else { $line .= ' {}'; push @lines, $line; } } else { die \"CPAN::Meta::YAML does not support $type references"; } } @lines; } ##################################################################### # DEPRECATED API methods: # Error storage (DEPRECATED as of 1.57) our $errstr = ''; # Set error sub _error { require Carp; $errstr = $_[1]; $errstr =~ s/ at \S+ line \d+.*//; Carp::croak( $errstr ); } # Retrieve error my $errstr_warned; sub errstr { require Carp; Carp::carp( "CPAN::Meta::YAML->errstr and \$CPAN::Meta::YAML::errstr is deprecated" ) unless $errstr_warned++; $errstr; } ##################################################################### # Helper functions. Possibly not needed. # Use to detect nv or iv use B; # XXX-INGY Is flock CPAN::Meta::YAML's responsibility? # Some platforms can't flock :-( # XXX-XDG I think it is. When reading and writing files, we ought # to be locking whenever possible. People (foolishly) use YAML # files for things like session storage, which has race issues. my $HAS_FLOCK; sub _can_flock { if ( defined $HAS_FLOCK ) { return $HAS_FLOCK; } else { require Config; my $c = \%Config::Config; $HAS_FLOCK = grep { $c->{$_} } qw/d_flock d_fcntl_can_lock d_lockf/; require Fcntl if $HAS_FLOCK; return $HAS_FLOCK; } } # XXX-INGY Is this core in 5.8.1? Can we remove this? # XXX-XDG Scalar::Util 1.18 didn't land until 5.8.8, so we need this ##################################################################### # Use Scalar::Util if possible, otherwise emulate it use Scalar::Util (); BEGIN { local $@; if ( eval { Scalar::Util->VERSION(1.18); } ) { *refaddr = *Scalar::Util::refaddr; } else { eval <<'END_PERL'; # Scalar::Util failed to load or too old sub refaddr { my $pkg = ref($_[0]) or return undef; if ( !! UNIVERSAL::can($_[0], 'can') ) { bless $_[0], 'Scalar::Util::Fake'; } else { $pkg = undef; } "$_[0]" =~ /0x(\w+)/; my $i = do { no warnings 'portable'; hex $1 }; bless $_[0], $pkg if defined $pkg; $i; } END_PERL } } delete $CPAN::Meta::YAML::{refaddr}; 1; # XXX-INGY Doc notes I'm putting up here. Changing the doc when it's wrong # but leaving grey area stuff up here. # # I would like to change Read/Write to Load/Dump below without # changing the actual API names. # # It might be better to put Load/Dump API in the SYNOPSIS instead of the # dubious OO API. # # null and bool explanations may be outdated. =pod =encoding UTF-8 =head1 NAME CPAN::Meta::YAML - Read and write a subset of YAML for CPAN Meta files =head1 VERSION version 0.018 =head1 SYNOPSIS use CPAN::Meta::YAML; # reading a META file open $fh, "<:utf8", "META.yml"; $yaml_text = do { local $/; <$fh> }; $yaml = CPAN::Meta::YAML->read_string($yaml_text) or die CPAN::Meta::YAML->errstr; # finding the metadata $meta = $yaml->[0]; # writing a META file $yaml_text = $yaml->write_string or die CPAN::Meta::YAML->errstr; open $fh, ">:utf8", "META.yml"; print $fh $yaml_text; =head1 DESCRIPTION This module implements a subset of the YAML specification for use in reading and writing CPAN metadata files like F and F. It should not be used for any other general YAML parsing or generation task. NOTE: F (and F) files should be UTF-8 encoded. Users are responsible for proper encoding and decoding. In particular, the C and C methods do B support UTF-8 and should not be used. =head1 SUPPORT This module is currently derived from L by Adam Kennedy. If there are bugs in how it parses a particular META.yml file, please file a bug report in the YAML::Tiny bugtracker: L =head1 SEE ALSO L, L, L =head1 AUTHORS =over 4 =item * Adam Kennedy =item * David Golden =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by Adam Kennedy. 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 __END__ # ABSTRACT: Read and write a subset of YAML for CPAN Meta files PK!†ñcmõõperl5/CPAN/Meta/Merge.pmnuÏÃ6Ç$use strict; use warnings; package CPAN::Meta::Merge; # VERSION $CPAN::Meta::Merge::VERSION = '2.143240'; use Carp qw/croak/; use Scalar::Util qw/blessed/; use CPAN::Meta::Converter; sub _identical { my ($left, $right, $path) = @_; croak sprintf "Can't merge attribute %s: '%s' does not equal '%s'", join('.', @{$path}), $left, $right unless $left eq $right; return $left; } sub _merge { my ($current, $next, $mergers, $path) = @_; for my $key (keys %{$next}) { if (not exists $current->{$key}) { $current->{$key} = $next->{$key}; } elsif (my $merger = $mergers->{$key}) { $current->{$key} = $merger->($current->{$key}, $next->{$key}, [ @{$path}, $key ]); } elsif ($merger = $mergers->{':default'}) { $current->{$key} = $merger->($current->{$key}, $next->{$key}, [ @{$path}, $key ]); } else { croak sprintf "Can't merge unknown attribute '%s'", join '.', @{$path}, $key; } } return $current; } sub _uniq { my %seen = (); return grep { not $seen{$_}++ } @_; } sub _set_addition { my ($left, $right) = @_; return [ +_uniq(@{$left}, @{$right}) ]; } sub _uniq_map { my ($left, $right, $path) = @_; for my $key (keys %{$right}) { if (not exists $left->{$key}) { $left->{$key} = $right->{$key}; } else { croak 'Duplication of element ' . join '.', @{$path}, $key; } } return $left; } sub _improvize { my ($left, $right, $path) = @_; my ($name) = reverse @{$path}; if ($name =~ /^x_/) { if (ref($left) eq 'ARRAY') { return _set_addition($left, $right, $path); } elsif (ref($left) eq 'HASH') { return _uniq_map($left, $right, $path); } else { return _identical($left, $right, $path); } } croak sprintf "Can't merge '%s'", join '.', @{$path}; } sub _optional_features { my ($left, $right, $path) = @_; for my $key (keys %{$right}) { if (not exists $left->{$key}) { $left->{$key} = $right->{$key}; } else { for my $subkey (keys %{ $right->{$key} }) { next if $subkey eq 'prereqs'; if (not exists $left->{$key}{$subkey}) { $left->{$key}{$subkey} = $right->{$key}{$subkey}; } else { Carp::croak "Cannot merge two optional_features named '$key' with different '$subkey' values" if do { no warnings 'uninitialized'; $left->{$key}{$subkey} ne $right->{$key}{$subkey} }; } } require CPAN::Meta::Prereqs; $left->{$key}{prereqs} = CPAN::Meta::Prereqs->new($left->{$key}{prereqs}) ->with_merged_prereqs(CPAN::Meta::Prereqs->new($right->{$key}{prereqs})) ->as_string_hash; } } return $left; } my %default = ( abstract => \&_identical, author => \&_set_addition, dynamic_config => sub { my ($left, $right) = @_; return $left || $right; }, generated_by => sub { my ($left, $right) = @_; return join ', ', _uniq(split(/, /, $left), split(/, /, $right)); }, license => \&_set_addition, 'meta-spec' => { version => \&_identical, url => \&_identical }, name => \&_identical, release_status => \&_identical, version => \&_identical, description => \&_identical, keywords => \&_set_addition, no_index => { map { ($_ => \&_set_addition) } qw/file directory package namespace/ }, optional_features => \&_optional_features, prereqs => sub { require CPAN::Meta::Prereqs; my ($left, $right) = map { CPAN::Meta::Prereqs->new($_) } @_[0,1]; return $left->with_merged_prereqs($right)->as_string_hash; }, provides => \&_uniq_map, resources => { license => \&_set_addition, homepage => \&_identical, bugtracker => \&_uniq_map, repository => \&_uniq_map, ':default' => \&_improvize, }, ':default' => \&_improvize, ); sub new { my ($class, %arguments) = @_; croak 'default version required' if not exists $arguments{default_version}; my %mapping = %default; my %extra = %{ $arguments{extra_mappings} || {} }; for my $key (keys %extra) { if (ref($mapping{$key}) eq 'HASH') { $mapping{$key} = { %{ $mapping{$key} }, %{ $extra{$key} } }; } else { $mapping{$key} = $extra{$key}; } } return bless { default_version => $arguments{default_version}, mapping => _coerce_mapping(\%mapping, []), }, $class; } my %coderef_for = ( set_addition => \&_set_addition, uniq_map => \&_uniq_map, identical => \&_identical, improvize => \&_improvize, ); sub _coerce_mapping { my ($orig, $map_path) = @_; my %ret; for my $key (keys %{$orig}) { my $value = $orig->{$key}; if (ref($orig->{$key}) eq 'CODE') { $ret{$key} = $value; } elsif (ref($value) eq 'HASH') { my $mapping = _coerce_mapping($value, [ @{$map_path}, $key ]); $ret{$key} = sub { my ($left, $right, $path) = @_; return _merge($left, $right, $mapping, [ @{$path} ]); }; } elsif ($coderef_for{$value}) { $ret{$key} = $coderef_for{$value}; } else { croak "Don't know what to do with " . join '.', @{$map_path}, $key; } } return \%ret; } sub merge { my ($self, @items) = @_; my $current = {}; for my $next (@items) { if ( blessed($next) && $next->isa('CPAN::Meta') ) { $next = $next->as_struct; } elsif ( ref($next) eq 'HASH' ) { my $cmc = CPAN::Meta::Converter->new( $next, default_version => $self->{default_version} ); $next = $cmc->upgrade_fragment; } else { croak "Don't know how to merge '$next'"; } $current = _merge($current, $next, $self->{mapping}, []); } return $current; } 1; # ABSTRACT: Merging CPAN Meta fragments __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Merge - Merging CPAN Meta fragments =head1 VERSION version 2.143240 =head1 SYNOPSIS my $merger = CPAN::Meta::Merge->new(default_version => "2"); my $meta = $merger->merge($base, @additional); =head1 DESCRIPTION =head1 METHODS =head2 new This creates a CPAN::Meta::Merge object. It takes one mandatory named argument, C, declaring the version of the meta-spec that must be used for the merge. It can optionally take an C argument that allows one to add additional merging functions for specific elements. =head2 merge(@fragments) Merge all C<@fragments> together. It will accept both CPAN::Meta objects and (possibly incomplete) hashrefs of metadata. =head1 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!ýsomFUFUperl5/CPAN/Meta/Requirements.pmnuÏÃ6Ç$use v5.10; use strict; use warnings; package CPAN::Meta::Requirements; # ABSTRACT: a set of version requirements for a CPAN dist our $VERSION = '2.143'; use CPAN::Meta::Requirements::Range; #pod =head1 SYNOPSIS #pod #pod use CPAN::Meta::Requirements; #pod #pod my $build_requires = CPAN::Meta::Requirements->new; #pod #pod $build_requires->add_minimum('Library::Foo' => 1.208); #pod #pod $build_requires->add_minimum('Library::Foo' => 2.602); #pod #pod $build_requires->add_minimum('Module::Bar' => 'v1.2.3'); #pod #pod $METAyml->{build_requires} = $build_requires->as_string_hash; #pod #pod =head1 DESCRIPTION #pod #pod A CPAN::Meta::Requirements object models a set of version constraints like #pod those specified in the F or F files in CPAN distributions, #pod and as defined by L. #pod It can be built up by adding more and more constraints, and it will reduce them #pod to the simplest representation. #pod #pod Logically impossible constraints will be identified immediately by thrown #pod exceptions. #pod #pod =cut use Carp (); #pod =method new #pod #pod my $req = CPAN::Meta::Requirements->new; #pod #pod This returns a new CPAN::Meta::Requirements object. It takes an optional #pod hash reference argument. Currently, only one key is supported: #pod #pod =for :list #pod * C -- if provided, when a version cannot be parsed into #pod a version object, this code reference will be called with the invalid #pod version string as first argument, and the module name as second #pod argument. It must return a valid version object. #pod #pod All other keys are ignored. #pod #pod =cut my @valid_options = qw( bad_version_hook ); sub new { my ($class, $options) = @_; $options ||= {}; Carp::croak "Argument to $class\->new() must be a hash reference" unless ref $options eq 'HASH'; my %self = map {; $_ => $options->{$_}} @valid_options; return bless \%self => $class; } #pod =method add_minimum #pod #pod $req->add_minimum( $module => $version ); #pod #pod This adds a new minimum version requirement. If the new requirement is #pod redundant to the existing specification, this has no effect. #pod #pod Minimum requirements are inclusive. C<$version> is required, along with any #pod greater version number. #pod #pod This method returns the requirements object. #pod #pod =method add_maximum #pod #pod $req->add_maximum( $module => $version ); #pod #pod This adds a new maximum version requirement. If the new requirement is #pod redundant to the existing specification, this has no effect. #pod #pod Maximum requirements are inclusive. No version strictly greater than the given #pod version is allowed. #pod #pod This method returns the requirements object. #pod #pod =method add_exclusion #pod #pod $req->add_exclusion( $module => $version ); #pod #pod This adds a new excluded version. For example, you might use these three #pod method calls: #pod #pod $req->add_minimum( $module => '1.00' ); #pod $req->add_maximum( $module => '1.82' ); #pod #pod $req->add_exclusion( $module => '1.75' ); #pod #pod Any version between 1.00 and 1.82 inclusive would be acceptable, except for #pod 1.75. #pod #pod This method returns the requirements object. #pod #pod =method exact_version #pod #pod $req->exact_version( $module => $version ); #pod #pod This sets the version required for the given module to I the given #pod version. No other version would be considered acceptable. #pod #pod This method returns the requirements object. #pod #pod =cut BEGIN { for my $type (qw(maximum exclusion exact_version)) { my $method = "with_$type"; my $to_add = $type eq 'exact_version' ? $type : "add_$type"; my $code = sub { my ($self, $name, $version) = @_; $self->__modify_entry_for($name, $method, $version); return $self; }; no strict 'refs'; *$to_add = $code; } } # add_minimum is optimized compared to generated subs above because # it is called frequently and with "0" or equivalent input sub add_minimum { my ($self, $name, $version) = @_; # stringify $version so that version->new("0.00")->stringify ne "0" # which preserves the user's choice of "0.00" as the requirement if (not defined $version or "$version" eq '0') { return $self if $self->__entry_for($name); Carp::croak("can't add new requirements to finalized requirements") if $self->is_finalized; $self->{requirements}{ $name } = CPAN::Meta::Requirements::Range->with_minimum('0', $name); } else { $self->__modify_entry_for($name, 'with_minimum', $version); } return $self; } #pod =method version_range_for_module #pod #pod $req->version_range_for_module( $another_req_object ); #pod #pod =cut sub version_range_for_module { my ($self, $module) = @_; return $self->{requirements}{$module}; } #pod =method add_requirements #pod #pod $req->add_requirements( $another_req_object ); #pod #pod This method adds all the requirements in the given CPAN::Meta::Requirements #pod object to the requirements object on which it was called. If there are any #pod conflicts, an exception is thrown. #pod #pod This method returns the requirements object. #pod #pod =cut sub add_requirements { my ($self, $req) = @_; for my $module ($req->required_modules) { my $new_range = $req->version_range_for_module($module); $self->__modify_entry_for($module, 'with_range', $new_range); } return $self; } #pod =method accepts_module #pod #pod my $bool = $req->accepts_module($module => $version); #pod #pod Given an module and version, this method returns true if the version #pod specification for the module accepts the provided version. In other words, #pod given: #pod #pod Module => '>= 1.00, < 2.00' #pod #pod We will accept 1.00 and 1.75 but not 0.50 or 2.00. #pod #pod For modules that do not appear in the requirements, this method will return #pod true. #pod #pod =cut sub accepts_module { my ($self, $module, $version) = @_; return 1 unless my $range = $self->__entry_for($module); return $range->accepts($version); } #pod =method clear_requirement #pod #pod $req->clear_requirement( $module ); #pod #pod This removes the requirement for a given module from the object. #pod #pod This method returns the requirements object. #pod #pod =cut sub clear_requirement { my ($self, $module) = @_; return $self unless $self->__entry_for($module); Carp::croak("can't clear requirements on finalized requirements") if $self->is_finalized; delete $self->{requirements}{ $module }; return $self; } #pod =method requirements_for_module #pod #pod $req->requirements_for_module( $module ); #pod #pod This returns a string containing the version requirements for a given module in #pod the format described in L or undef if the given module has no #pod requirements. This should only be used for informational purposes such as error #pod messages and should not be interpreted or used for comparison (see #pod L instead). #pod #pod =cut sub requirements_for_module { my ($self, $module) = @_; my $entry = $self->__entry_for($module); return unless $entry; return $entry->as_string; } #pod =method structured_requirements_for_module #pod #pod $req->structured_requirements_for_module( $module ); #pod #pod This returns a data structure containing the version requirements for a given #pod module or undef if the given module has no requirements. This should #pod not be used for version checks (see L instead). #pod #pod Added in version 2.134. #pod #pod =cut sub structured_requirements_for_module { my ($self, $module) = @_; my $entry = $self->__entry_for($module); return unless $entry; return $entry->as_struct; } #pod =method required_modules #pod #pod This method returns a list of all the modules for which requirements have been #pod specified. #pod #pod =cut sub required_modules { keys %{ $_[0]{requirements} } } #pod =method clone #pod #pod $req->clone; #pod #pod This method returns a clone of the invocant. The clone and the original object #pod can then be changed independent of one another. #pod #pod =cut sub clone { my ($self) = @_; my $new = (ref $self)->new; return $new->add_requirements($self); } sub __entry_for { $_[0]{requirements}{ $_[1] } } sub __modify_entry_for { my ($self, $name, $method, $version) = @_; my $fin = $self->is_finalized; my $old = $self->__entry_for($name); Carp::croak("can't add new requirements to finalized requirements") if $fin and not $old; my $new = ($old || 'CPAN::Meta::Requirements::Range') ->$method($version, $name, $self->{bad_version_hook}); Carp::croak("can't modify finalized requirements") if $fin and $old->as_string ne $new->as_string; $self->{requirements}{ $name } = $new; } #pod =method is_simple #pod #pod This method returns true if and only if all requirements are inclusive minimums #pod -- that is, if their string expression is just the version number. #pod #pod =cut sub is_simple { my ($self) = @_; for my $module ($self->required_modules) { # XXX: This is a complete hack, but also entirely correct. return if not $self->__entry_for($module)->is_simple; } return 1; } #pod =method is_finalized #pod #pod This method returns true if the requirements have been finalized by having the #pod C method called on them. #pod #pod =cut sub is_finalized { $_[0]{finalized} } #pod =method finalize #pod #pod This method marks the requirements finalized. Subsequent attempts to change #pod the requirements will be fatal, I they would result in a change. If they #pod would not alter the requirements, they have no effect. #pod #pod If a finalized set of requirements is cloned, the cloned requirements are not #pod also finalized. #pod #pod =cut sub finalize { $_[0]{finalized} = 1 } #pod =method as_string_hash #pod #pod This returns a reference to a hash describing the requirements using the #pod strings in the L specification. #pod #pod For example after the following program: #pod #pod my $req = CPAN::Meta::Requirements->new; #pod #pod $req->add_minimum('CPAN::Meta::Requirements' => 0.102); #pod #pod $req->add_minimum('Library::Foo' => 1.208); #pod #pod $req->add_maximum('Library::Foo' => 2.602); #pod #pod $req->add_minimum('Module::Bar' => 'v1.2.3'); #pod #pod $req->add_exclusion('Module::Bar' => 'v1.2.8'); #pod #pod $req->exact_version('Xyzzy' => '6.01'); #pod #pod my $hashref = $req->as_string_hash; #pod #pod C<$hashref> would contain: #pod #pod { #pod 'CPAN::Meta::Requirements' => '0.102', #pod 'Library::Foo' => '>= 1.208, <= 2.206', #pod 'Module::Bar' => '>= v1.2.3, != v1.2.8', #pod 'Xyzzy' => '== 6.01', #pod } #pod #pod =cut sub as_string_hash { my ($self) = @_; my %hash = map {; $_ => $self->{requirements}{$_}->as_string } $self->required_modules; return \%hash; } #pod =method add_string_requirement #pod #pod $req->add_string_requirement('Library::Foo' => '>= 1.208, <= 2.206'); #pod $req->add_string_requirement('Library::Foo' => v1.208); #pod #pod This method parses the passed in string and adds the appropriate requirement #pod for the given module. A version can be a Perl "v-string". It understands #pod version ranges as described in the L. For #pod example: #pod #pod =over 4 #pod #pod =item 1.3 #pod #pod =item >= 1.3 #pod #pod =item <= 1.3 #pod #pod =item == 1.3 #pod #pod =item != 1.3 #pod #pod =item > 1.3 #pod #pod =item < 1.3 #pod #pod =item >= 1.3, != 1.5, <= 2.0 #pod #pod A version number without an operator is equivalent to specifying a minimum #pod (C=>). Extra whitespace is allowed. #pod #pod =back #pod #pod =cut sub add_string_requirement { my ($self, $module, $req) = @_; $self->__modify_entry_for($module, 'with_string_requirement', $req); } #pod =method from_string_hash #pod #pod my $req = CPAN::Meta::Requirements->from_string_hash( \%hash ); #pod my $req = CPAN::Meta::Requirements->from_string_hash( \%hash, \%opts ); #pod #pod This is an alternate constructor for a CPAN::Meta::Requirements #pod object. It takes a hash of module names and version requirement #pod strings and returns a new CPAN::Meta::Requirements object. As with #pod add_string_requirement, a version can be a Perl "v-string". Optionally, #pod you can supply a hash-reference of options, exactly as with the L
#pod method. #pod #pod =cut sub from_string_hash { my ($class, $hash, $options) = @_; my $self = $class->new($options); for my $module (keys %$hash) { my $req = $hash->{$module}; $self->add_string_requirement($module, $req); } return $self; } 1; # vim: ts=2 sts=2 sw=2 et: __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Requirements - a set of version requirements for a CPAN dist =head1 VERSION version 2.143 =head1 SYNOPSIS use CPAN::Meta::Requirements; my $build_requires = CPAN::Meta::Requirements->new; $build_requires->add_minimum('Library::Foo' => 1.208); $build_requires->add_minimum('Library::Foo' => 2.602); $build_requires->add_minimum('Module::Bar' => 'v1.2.3'); $METAyml->{build_requires} = $build_requires->as_string_hash; =head1 DESCRIPTION A CPAN::Meta::Requirements object models a set of version constraints like those specified in the F or F files in CPAN distributions, and as defined by L. It can be built up by adding more and more constraints, and it will reduce them to the simplest representation. Logically impossible constraints will be identified immediately by thrown exceptions. =head1 METHODS =head2 new my $req = CPAN::Meta::Requirements->new; This returns a new CPAN::Meta::Requirements object. It takes an optional hash reference argument. Currently, only one key is supported: =over 4 =item * C -- if provided, when a version cannot be parsed into a version object, this code reference will be called with the invalid version string as first argument, and the module name as second argument. It must return a valid version object. =back All other keys are ignored. =head2 add_minimum $req->add_minimum( $module => $version ); This adds a new minimum version requirement. If the new requirement is redundant to the existing specification, this has no effect. Minimum requirements are inclusive. C<$version> is required, along with any greater version number. This method returns the requirements object. =head2 add_maximum $req->add_maximum( $module => $version ); This adds a new maximum version requirement. If the new requirement is redundant to the existing specification, this has no effect. Maximum requirements are inclusive. No version strictly greater than the given version is allowed. This method returns the requirements object. =head2 add_exclusion $req->add_exclusion( $module => $version ); This adds a new excluded version. For example, you might use these three method calls: $req->add_minimum( $module => '1.00' ); $req->add_maximum( $module => '1.82' ); $req->add_exclusion( $module => '1.75' ); Any version between 1.00 and 1.82 inclusive would be acceptable, except for 1.75. This method returns the requirements object. =head2 exact_version $req->exact_version( $module => $version ); This sets the version required for the given module to I the given version. No other version would be considered acceptable. This method returns the requirements object. =head2 version_range_for_module $req->version_range_for_module( $another_req_object ); =head2 add_requirements $req->add_requirements( $another_req_object ); This method adds all the requirements in the given CPAN::Meta::Requirements object to the requirements object on which it was called. If there are any conflicts, an exception is thrown. This method returns the requirements object. =head2 accepts_module my $bool = $req->accepts_module($module => $version); Given an module and version, this method returns true if the version specification for the module accepts the provided version. In other words, given: Module => '>= 1.00, < 2.00' We will accept 1.00 and 1.75 but not 0.50 or 2.00. For modules that do not appear in the requirements, this method will return true. =head2 clear_requirement $req->clear_requirement( $module ); This removes the requirement for a given module from the object. This method returns the requirements object. =head2 requirements_for_module $req->requirements_for_module( $module ); This returns a string containing the version requirements for a given module in the format described in L or undef if the given module has no requirements. This should only be used for informational purposes such as error messages and should not be interpreted or used for comparison (see L instead). =head2 structured_requirements_for_module $req->structured_requirements_for_module( $module ); This returns a data structure containing the version requirements for a given module or undef if the given module has no requirements. This should not be used for version checks (see L instead). Added in version 2.134. =head2 required_modules This method returns a list of all the modules for which requirements have been specified. =head2 clone $req->clone; This method returns a clone of the invocant. The clone and the original object can then be changed independent of one another. =head2 is_simple This method returns true if and only if all requirements are inclusive minimums -- that is, if their string expression is just the version number. =head2 is_finalized This method returns true if the requirements have been finalized by having the C method called on them. =head2 finalize This method marks the requirements finalized. Subsequent attempts to change the requirements will be fatal, I they would result in a change. If they would not alter the requirements, they have no effect. If a finalized set of requirements is cloned, the cloned requirements are not also finalized. =head2 as_string_hash This returns a reference to a hash describing the requirements using the strings in the L specification. For example after the following program: my $req = CPAN::Meta::Requirements->new; $req->add_minimum('CPAN::Meta::Requirements' => 0.102); $req->add_minimum('Library::Foo' => 1.208); $req->add_maximum('Library::Foo' => 2.602); $req->add_minimum('Module::Bar' => 'v1.2.3'); $req->add_exclusion('Module::Bar' => 'v1.2.8'); $req->exact_version('Xyzzy' => '6.01'); my $hashref = $req->as_string_hash; C<$hashref> would contain: { 'CPAN::Meta::Requirements' => '0.102', 'Library::Foo' => '>= 1.208, <= 2.206', 'Module::Bar' => '>= v1.2.3, != v1.2.8', 'Xyzzy' => '== 6.01', } =head2 add_string_requirement $req->add_string_requirement('Library::Foo' => '>= 1.208, <= 2.206'); $req->add_string_requirement('Library::Foo' => v1.208); This method parses the passed in string and adds the appropriate requirement for the given module. A version can be a Perl "v-string". It understands version ranges as described in the L. For example: =over 4 =item 1.3 =item >= 1.3 =item <= 1.3 =item == 1.3 =item != 1.3 =item > 1.3 =item < 1.3 =item >= 1.3, != 1.5, <= 2.0 A version number without an operator is equivalent to specifying a minimum (C=>). Extra whitespace is allowed. =back =head2 from_string_hash my $req = CPAN::Meta::Requirements->from_string_hash( \%hash ); my $req = CPAN::Meta::Requirements->from_string_hash( \%hash, \%opts ); This is an alternate constructor for a CPAN::Meta::Requirements object. It takes a hash of module names and version requirement strings and returns a new CPAN::Meta::Requirements object. As with add_string_requirement, a version can be a Perl "v-string". Optionally, you can supply a hash-reference of options, exactly as with the L method. =for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements.git =head1 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 CONTRIBUTORS =for stopwords Ed J Graham Knop Karen Etheridge Leon Timmermans Paul Howarth Ricardo Signes robario Tatsuhiko Miyagawa =over 4 =item * Ed J =item * Graham Knop =item * Karen Etheridge =item * Leon Timmermans =item * Paul Howarth =item * Ricardo Signes =item * robario =item * Tatsuhiko Miyagawa =item * Tatsuhiko Miyagawa =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!‹E'é  perl5/CPAN/Meta/Feature.pmnuÏÃ6Ç$use 5.006; use strict; use warnings; package CPAN::Meta::Feature; # VERSION $CPAN::Meta::Feature::VERSION = '2.143240'; use CPAN::Meta::Prereqs; #pod =head1 DESCRIPTION #pod #pod A CPAN::Meta::Feature object describes an optional feature offered by a CPAN #pod distribution and specified in the distribution's F (or F) #pod file. #pod #pod For the most part, this class will only be used when operating on the result of #pod the C or C methods on a L object. #pod #pod =method new #pod #pod my $feature = CPAN::Meta::Feature->new( $identifier => \%spec ); #pod #pod This returns a new Feature object. The C<%spec> argument to the constructor #pod should be the same as the value of the C entry in the #pod distmeta. It must contain entries for C and C. #pod #pod =cut sub new { my ($class, $identifier, $spec) = @_; my %guts = ( identifier => $identifier, description => $spec->{description}, prereqs => CPAN::Meta::Prereqs->new($spec->{prereqs}), ); bless \%guts => $class; } #pod =method identifier #pod #pod This method returns the feature's identifier. #pod #pod =cut sub identifier { $_[0]{identifier} } #pod =method description #pod #pod This method returns the feature's long description. #pod #pod =cut sub description { $_[0]{description} } #pod =method prereqs #pod #pod This method returns the feature's prerequisites as a L #pod object. #pod #pod =cut sub prereqs { $_[0]{prereqs} } 1; # ABSTRACT: an optional feature provided by a CPAN distribution __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Feature - an optional feature provided by a CPAN distribution =head1 VERSION version 2.143240 =head1 DESCRIPTION A CPAN::Meta::Feature object describes an optional feature offered by a CPAN distribution and specified in the distribution's F (or F) file. For the most part, this class will only be used when operating on the result of the C or C methods on a L object. =head1 METHODS =head2 new my $feature = CPAN::Meta::Feature->new( $identifier => \%spec ); This returns a new Feature object. The C<%spec> argument to the constructor should be the same as the value of the C entry in the distmeta. It must contain entries for C and C. =head2 identifier This method returns the feature's identifier. =head2 description This method returns the feature's long description. =head2 prereqs This method returns the feature's prerequisites as a L object. =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at 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 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!B$s��perl5/CPAN/Meta/Spec.pmnuÏÃ6Ç$# XXX RULES FOR PATCHING THIS FILE XXX # Patches that fix typos or formatting are acceptable. Patches # that change semantics are not acceptable without prior approval # by David Golden or Ricardo Signes. use 5.006; use strict; use warnings; package CPAN::Meta::Spec; # VERSION $CPAN::Meta::Spec::VERSION = '2.143240'; 1; # ABSTRACT: specification for CPAN distribution metadata # vi:tw=72 __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Spec - specification for CPAN distribution metadata =head1 VERSION version 2.143240 =head1 SYNOPSIS my $distmeta = { name => 'Module-Build', abstract => 'Build and install Perl modules', description => "Module::Build is a system for " . "building, testing, and installing Perl modules. " . "It is meant to ... blah blah blah ...", version => '0.36', release_status => 'stable', author => [ 'Ken Williams ', 'Module-Build List ', # additional contact ], license => [ 'perl_5' ], prereqs => { runtime => { requires => { 'perl' => '5.006', 'ExtUtils::Install' => '0', 'File::Basename' => '0', 'File::Compare' => '0', 'IO::File' => '0', }, recommends => { 'Archive::Tar' => '1.00', 'ExtUtils::Install' => '0.3', 'ExtUtils::ParseXS' => '2.02', }, }, build => { requires => { 'Test::More' => '0', }, } }, resources => { license => ['http://dev.perl.org/licenses/'], }, optional_features => { domination => { description => 'Take over the world', prereqs => { develop => { requires => { 'Genius::Evil' => '1.234' } }, runtime => { requires => { 'Machine::Weather' => '2.0' } }, }, }, }, dynamic_config => 1, keywords => [ qw/ toolchain cpan dual-life / ], 'meta-spec' => { version => '2', url => 'https://metacpan.org/pod/CPAN::Meta::Spec', }, generated_by => 'Module::Build version 0.36', }; =head1 DESCRIPTION This document describes version 2 of the CPAN distribution metadata specification, also known as the "CPAN Meta Spec". Revisions of this specification for typo corrections and prose clarifications may be issued as CPAN::Meta::Spec 2.I. These revisions will never change semantics or add or remove specified behavior. Distribution metadata describe important properties of Perl distributions. Distribution building tools like Module::Build, Module::Install, ExtUtils::MakeMaker or Dist::Zilla should create a metadata file in accordance with this specification and include it with the distribution for use by automated tools that index, examine, package or install Perl distributions. =head1 TERMINOLOGY =over 4 =item distribution This is the primary object described by the metadata. In the context of this document it usually refers to a collection of modules, scripts, and/or documents that are distributed together for other developers to use. Examples of distributions are C, C, or C. =item module This refers to a reusable library of code contained in a single file. Modules usually contain one or more packages and are often referred to by the name of a primary package that can be mapped to the file name. For example, one might refer to C instead of F =item package This refers to a namespace declared with the Perl C statement. In Perl, packages often have a version number property given by the C<$VERSION> variable in the namespace. =item consumer This refers to code that reads a metadata file, deserializes it into a data structure in memory, or interprets a data structure of metadata elements. =item producer This refers to code that constructs a metadata data structure, serializes into a bytestream and/or writes it to disk. =item must, should, may, etc. These terms are interpreted as described in IETF RFC 2119. =back =head1 DATA TYPES Fields in the L section describe data elements, each of which has an associated data type as described herein. There are four primitive types: Boolean, String, List and Map. Other types are subtypes of primitives and define compound data structures or define constraints on the values of a data element. =head2 Boolean A I is used to provide a true or false value. It B be represented as a defined value. =head2 String A I is data element containing a non-zero length sequence of Unicode characters, such as an ordinary Perl scalar that is not a reference. =head2 List A I is an ordered collection of zero or more data elements. Elements of a List may be of mixed types. Producers B represent List elements using a data structure which unambiguously indicates that multiple values are possible, such as a reference to a Perl array (an "arrayref"). Consumers expecting a List B consider a String as equivalent to a List of length 1. =head2 Map A I is an unordered collection of zero or more data elements ("values"), indexed by associated String elements ("keys"). The Map's value elements may be of mixed types. =head2 License String A I is a subtype of String with a restricted set of values. Valid values are described in detail in the description of the L field. =head2 URL I is a subtype of String containing a Uniform Resource Locator or Identifier. [ This type is called URL and not URI for historical reasons. ] =head2 Version A I is a subtype of String containing a value that describes the version number of packages or distributions. Restrictions on format are described in detail in the L section. =head2 Version Range The I type is a subtype of String. It describes a range of Versions that may be present or installed to fulfill prerequisites. It is specified in detail in the L section. =head1 STRUCTURE The metadata structure is a data element of type Map. This section describes valid keys within the Map. Any keys not described in this specification document (whether top-level or within compound data structures described herein) are considered I and B begin with an "x" or "X" and be followed by an underscore; i.e. they must match the pattern: C<< qr{\Ax_}i >>. If a custom key refers to a compound data structure, subkeys within it do not need an "x_" or "X_" prefix. Consumers of metadata may ignore any or all custom keys. All other keys not described herein are invalid and should be ignored by consumers. Producers must not generate or output invalid keys. For each key, an example is provided followed by a description. The description begins with the version of spec in which the key was added or in which the definition was modified, whether the key is I or I and the data type of the corresponding data element. These items are in parentheses, brackets and braces, respectively. If a data type is a Map or Map subtype, valid subkeys will be described as well. Some fields are marked I. These are shown for historical context and must not be produced in or consumed from any metadata structure of version 2 or higher. =head2 REQUIRED FIELDS =head3 abstract Example: abstract => 'Build and install Perl modules' (Spec 1.2) [required] {String} This is a short description of the purpose of the distribution. =head3 author Example: author => [ 'Ken Williams ' ] (Spec 1.2) [required] {List of one or more Strings} This List indicates the person(s) to contact concerning the distribution. The preferred form of the contact string is: contact-name This field provides a general contact list independent of other structured fields provided within the L field, such as C. The addressee(s) can be contacted for any purpose including but not limited to (security) problems with the distribution, questions about the distribution or bugs in the distribution. A distribution's original author is usually the contact listed within this field. Co-maintainers, successor maintainers or mailing lists devoted to the distribution may also be listed in addition to or instead of the original author. =head3 dynamic_config Example: dynamic_config => 1 (Spec 2) [required] {Boolean} A boolean flag indicating whether a F or F (or similar) must be executed to determine prerequisites. This field should be set to a true value if the distribution performs some dynamic configuration (asking questions, sensing the environment, etc.) as part of its configuration. This field should be set to a false value to indicate that prerequisites included in metadata may be considered final and valid for static analysis. Note: when this field is true, post-configuration prerequisites are not guaranteed to bear any relation whatsoever to those stated in the metadata, and relying on them doing so is an error. See also L in the implementors' notes. This field explicitly B indicate whether installation may be safely performed without using a Makefile or Build file, as there may be special files to install or custom installation targets (e.g. for dual-life modules that exist on CPAN as well as in the Perl core). This field only defines whether or not prerequisites are exactly as given in the metadata. =head3 generated_by Example: generated_by => 'Module::Build version 0.36' (Spec 1.0) [required] {String} This field indicates the tool that was used to create this metadata. There are no defined semantics for this field, but it is traditional to use a string in the form "Generating::Package version 1.23" or the author's name, if the file was generated by hand. =head3 license Example: license => [ 'perl_5' ] license => [ 'apache_2_0', 'mozilla_1_0' ] (Spec 2) [required] {List of one or more License Strings} One or more licenses that apply to some or all of the files in the distribution. If multiple licenses are listed, the distribution documentation should be consulted to clarify the interpretation of multiple licenses. The following list of license strings are valid: string description ------------- ----------------------------------------------- agpl_3 GNU Affero General Public License, Version 3 apache_1_1 Apache Software License, Version 1.1 apache_2_0 Apache License, Version 2.0 artistic_1 Artistic License, (Version 1) artistic_2 Artistic License, Version 2.0 bsd BSD License (three-clause) freebsd FreeBSD License (two-clause) gfdl_1_2 GNU Free Documentation License, Version 1.2 gfdl_1_3 GNU Free Documentation License, Version 1.3 gpl_1 GNU General Public License, Version 1 gpl_2 GNU General Public License, Version 2 gpl_3 GNU General Public License, Version 3 lgpl_2_1 GNU Lesser General Public License, Version 2.1 lgpl_3_0 GNU Lesser General Public License, Version 3.0 mit MIT (aka X11) License mozilla_1_0 Mozilla Public License, Version 1.0 mozilla_1_1 Mozilla Public License, Version 1.1 openssl OpenSSL License perl_5 The Perl 5 License (Artistic 1 & GPL 1 or later) qpl_1_0 Q Public License, Version 1.0 ssleay Original SSLeay License sun Sun Internet Standards Source License (SISSL) zlib zlib License The following license strings are also valid and indicate other licensing not described above: string description ------------- ----------------------------------------------- open_source Other Open Source Initiative (OSI) approved license restricted Requires special permission from copyright holder unrestricted Not an OSI approved license, but not restricted unknown License not provided in metadata All other strings are invalid in the license field. =head3 meta-spec Example: 'meta-spec' => { version => '2', url => 'http://search.cpan.org/perldoc?CPAN::Meta::Spec', } (Spec 1.2) [required] {Map} This field indicates the version of the CPAN Meta Spec that should be used to interpret the metadata. Consumers must check this key as soon as possible and abort further metadata processing if the meta-spec version is not supported by the consumer. The following keys are valid, but only C is required. =over =item version This subkey gives the integer I of the CPAN Meta Spec against which the document was generated. =item url This is a I of the metadata specification document corresponding to the given version. This is strictly for human-consumption and should not impact the interpretation of the document. For the version 2 spec, either of these are recommended: =over 4 =item * C =item * C =back =back =head3 name Example: name => 'Module-Build' (Spec 1.0) [required] {String} This field is the name of the distribution. This is often created by taking the "main package" in the distribution and changing C<::> to C<->, but the name may be completely unrelated to the packages within the distribution. For example, L is distributed as part of the distribution name "libwww-perl". =head3 release_status Example: release_status => 'stable' (Spec 2) [required] {String} This field provides the release status of this distribution. If the C field contains an underscore character, then C B be "stable." The C field B have one of the following values: =over =item stable This indicates an ordinary, "final" release that should be indexed by PAUSE or other indexers. =item testing This indicates a "beta" release that is substantially complete, but has an elevated risk of bugs and requires additional testing. The distribution should not be installed over a stable release without an explicit request or other confirmation from a user. This release status may also be used for "release candidate" versions of a distribution. =item unstable This indicates an "alpha" release that is under active development, but has been released for early feedback or testing and may be missing features or may have serious bugs. The distribution should not be installed over a stable release without an explicit request or other confirmation from a user. =back Consumers B use this field to determine how to index the distribution for CPAN or other repositories in addition to or in replacement of heuristics based on version number or file name. =head3 version Example: version => '0.36' (Spec 1.0) [required] {Version} This field gives the version of the distribution to which the metadata structure refers. =head2 OPTIONAL FIELDS =head3 description Example: description => "Module::Build is a system for " . "building, testing, and installing Perl modules. " . "It is meant to ... blah blah blah ...", (Spec 2) [optional] {String} A longer, more complete description of the purpose or intended use of the distribution than the one provided by the C key. =head3 keywords Example: keywords => [ qw/ toolchain cpan dual-life / ] (Spec 1.1) [optional] {List of zero or more Strings} A List of keywords that describe this distribution. Keywords B include whitespace. =head3 no_index Example: no_index => { file => [ 'My/Module.pm' ], directory => [ 'My/Private' ], package => [ 'My::Module::Secret' ], namespace => [ 'My::Module::Sample' ], } (Spec 1.2) [optional] {Map} This Map describes any files, directories, packages, and namespaces that are private to the packaging or implementation of the distribution and should be ignored by indexing or search tools. Note that this is a list of exclusions, and the spec does not define what to I - see L in the implementors notes for more information. Valid subkeys are as follows: =over =item file A I of relative paths to files. Paths B specified with unix conventions. =item directory A I of relative paths to directories. Paths B specified with unix conventions. [ Note: previous editions of the spec had C instead of C ] =item package A I of package names. =item namespace A I of package namespaces, where anything below the namespace must be ignored, but I the namespace itself. In the example above for C, C would be ignored, but C would not. =back =head3 optional_features Example: optional_features => { sqlite => { description => 'Provides SQLite support', prereqs => { runtime => { requires => { 'DBD::SQLite' => '1.25' } } } } } (Spec 2) [optional] {Map} This Map describes optional features with incremental prerequisites. Each key of the C Map is a String used to identify the feature and each value is a Map with additional information about the feature. Valid subkeys include: =over =item description This is a String describing the feature. Every optional feature should provide a description =item prereqs This entry is required and has the same structure as that of the C> key. It provides a list of package requirements that must be satisfied for the feature to be supported or enabled. There is one crucial restriction: the prereqs of an optional feature B include C phase prereqs. =back Consumers B include optional features as prerequisites without explicit instruction from users (whether via interactive prompting, a function parameter or a configuration value, etc. ). If an optional feature is used by a consumer to add additional prerequisites, the consumer should merge the optional feature prerequisites into those given by the C key using the same semantics. See L for details on merging prerequisites. I Because there is currently no way for a distribution to specify a dependency on an optional feature of another dependency, the use of C is discouraged. Instead, create a separate, installable distribution that ensures the desired feature is available. For example, if C has a C feature, release a separate C distribution that satisfies requirements for the feature. =head3 prereqs Example: prereqs => { runtime => { requires => { 'perl' => '5.006', 'File::Spec' => '0.86', 'JSON' => '2.16', }, recommends => { 'JSON::XS' => '2.26', }, suggests => { 'Archive::Tar' => '0', }, }, build => { requires => { 'Alien::SDL' => '1.00', }, }, test => { recommends => { 'Test::Deep' => '0.10', }, } } (Spec 2) [optional] {Map} This is a Map that describes all the prerequisites of the distribution. The keys are phases of activity, such as C, C, C or C. Values are Maps in which the keys name the type of prerequisite relationship such as C, C, or C and the value provides a set of prerequisite relations. The set of relations B be specified as a Map of package names to version ranges. The full definition for this field is given in the L section. =head3 provides Example: provides => { 'Foo::Bar' => { file => 'lib/Foo/Bar.pm', version => '0.27_02', }, 'Foo::Bar::Blah' => { file => 'lib/Foo/Bar/Blah.pm', }, 'Foo::Bar::Baz' => { file => 'lib/Foo/Bar/Baz.pm', version => '0.3', }, } (Spec 1.2) [optional] {Map} This describes all packages provided by this distribution. This information is used by distribution and automation mechanisms like PAUSE, CPAN, metacpan.org and search.cpan.org to build indexes saying in which distribution various packages can be found. The keys of C are package names that can be found within the distribution. If a package name key is provided, it must have a Map with the following valid subkeys: =over =item file This field is required. It must contain a Unix-style relative file path from the root of the distribution directory to a file that contains or generates the package. It may be given as C or C to claim a package for indexing without needing a C<*.pm>. =item version If it exists, this field must contains a I String for the package. If the package does not have a C<$VERSION>, this field must be omitted. =back =head3 resources Example: resources => { license => [ 'http://dev.perl.org/licenses/' ], homepage => 'http://sourceforge.net/projects/module-build', bugtracker => { web => 'http://rt.cpan.org/Public/Dist/Display.html?Name=CPAN-Meta', mailto => 'meta-bugs@example.com', }, repository => { url => 'git://github.com/dagolden/cpan-meta.git', web => 'http://github.com/dagolden/cpan-meta', type => 'git', }, x_twitter => 'http://twitter.com/cpan_linked/', } (Spec 2) [optional] {Map} This field describes resources related to this distribution. Valid subkeys include: =over =item homepage The official home of this project on the web. =item license A List of I's that relate to this distribution's license. As with the top-level C field, distribution documentation should be consulted to clarify the interpretation of multiple licenses provided here. =item bugtracker This entry describes the bug tracking system for this distribution. It is a Map with the following valid keys: web - a URL pointing to a web front-end for the bug tracker mailto - an email address to which bugs can be sent =item repository This entry describes the source control repository for this distribution. It is a Map with the following valid keys: url - a URL pointing to the repository itself web - a URL pointing to a web front-end for the repository type - a lowercase string indicating the VCS used Because a url like C is ambiguous as to type, producers should provide a C whenever a C key is given. The C field should be the name of the most common program used to work with the repository, e.g. C, C, C, C, C or C. =back =head2 DEPRECATED FIELDS =head3 build_requires I<(Deprecated in Spec 2)> [optional] {String} Replaced by C =head3 configure_requires I<(Deprecated in Spec 2)> [optional] {String} Replaced by C =head3 conflicts I<(Deprecated in Spec 2)> [optional] {String} Replaced by C =head3 distribution_type I<(Deprecated in Spec 2)> [optional] {String} This field indicated 'module' or 'script' but was considered meaningless, since many distributions are hybrids of several kinds of things. =head3 license_uri I<(Deprecated in Spec 1.2)> [optional] {URL} Replaced by C in C =head3 private I<(Deprecated in Spec 1.2)> [optional] {Map} This field has been renamed to L. =head3 recommends I<(Deprecated in Spec 2)> [optional] {String} Replaced by C =head3 requires I<(Deprecated in Spec 2)> [optional] {String} Replaced by C =head1 VERSION NUMBERS =head2 Version Formats This section defines the Version type, used by several fields in the CPAN Meta Spec. Version numbers must be treated as strings, not numbers. For example, C<1.200> B be serialized as C<1.2>. Version comparison should be delegated to the Perl L module, version 0.80 or newer. Unless otherwise specified, version numbers B appear in one of two formats: =over =item Decimal versions Decimal versions are regular "decimal numbers", with some limitations. They B be non-negative and B begin and end with a digit. A single underscore B be included, but B be between two digits. They B use exponential notation ("1.23e-2"). version => '1.234' # OK version => '1.23_04' # OK version => '1.23_04_05' # Illegal version => '1.' # Illegal version => '.1' # Illegal =item Dotted-integer versions Dotted-integer (also known as dotted-decimal) versions consist of positive integers separated by full stop characters (i.e. "dots", "periods" or "decimal points"). This are equivalent in format to Perl "v-strings", with some additional restrictions on form. They must be given in "normal" form, which has a leading "v" character and at least three integer components. To retain a one-to-one mapping with decimal versions, all components after the first B be restricted to the range 0 to 999. The final component B be separated by an underscore character instead of a period. version => 'v1.2.3' # OK version => 'v1.2_3' # OK version => 'v1.2.3.4' # OK version => 'v1.2.3_4' # OK version => 'v2009.10.31' # OK version => 'v1.2' # Illegal version => '1.2.3' # Illegal version => 'v1.2_3_4' # Illegal version => 'v1.2009.10.31' # Not recommended =back =head2 Version Ranges Some fields (prereq, optional_features) indicate the particular version(s) of some other module that may be required as a prerequisite. This section details the Version Range type used to provide this information. The simplest format for a Version Range is just the version number itself, e.g. C<2.4>. This means that B version 2.4 must be present. To indicate that B version of a prerequisite is okay, even if the prerequisite doesn't define a version at all, use the version C<0>. Alternatively, a version range B use the operators E (less than), E= (less than or equal), E (greater than), E= (greater than or equal), == (equal), and != (not equal). For example, the specification C 2.0> means that any version of the prerequisite less than 2.0 is suitable. For more complicated situations, version specifications B be AND-ed together using commas. The specification C= 1.2, != 1.5, E 2.0> indicates a version that must be B 1.2, B 2.0, and B 1.5. =head1 PREREQUISITES =head2 Prereq Spec The C key in the top-level metadata and within C define the relationship between a distribution and other packages. The prereq spec structure is a hierarchical data structure which divides prerequisites into I of activity in the installation process and I that indicate how prerequisites should be resolved. For example, to specify that C is C during the C phase, this entry would appear in the distribution metadata: prereqs => { test => { requires => { 'Data::Dumper' => '2.00' } } } =head3 Phases Requirements for regular use must be listed in the C phase. Other requirements should be listed in the earliest stage in which they are required and consumers must accumulate and satisfy requirements across phases before executing the activity. For example, C requirements must also be available during the C phase. before action requirements that must be met ---------------- -------------------------------- perl Build.PL configure perl Makefile.PL make configure, runtime, build Build make test configure, runtime, build, test Build test Consumers that install the distribution must ensure that I requirements are also installed and may install dependencies from other phases. after action requirements that must be met ---------------- -------------------------------- make install runtime Build install =over =item configure The configure phase occurs before any dynamic configuration has been attempted. Libraries required by the configure phase B be available for use before the distribution building tool has been executed. =item build The build phase is when the distribution's source code is compiled (if necessary) and otherwise made ready for installation. =item test The test phase is when the distribution's automated test suite is run. Any library that is needed only for testing and not for subsequent use should be listed here. =item runtime The runtime phase refers not only to when the distribution's contents are installed, but also to its continued use. Any library that is a prerequisite for regular use of this distribution should be indicated here. =item develop The develop phase's prereqs are libraries needed to work on the distribution's source code as its author does. These tools might be needed to build a release tarball, to run author-only tests, or to perform other tasks related to developing new versions of the distribution. =back =head3 Relationships =over =item requires These dependencies B be installed for proper completion of the phase. =item recommends Recommended dependencies are I encouraged and should be satisfied except in resource constrained environments. =item suggests These dependencies are optional, but are suggested for enhanced operation of the described distribution. =item conflicts These libraries cannot be installed when the phase is in operation. This is a very rare situation, and the C relationship should be used with great caution, or not at all. =back =head2 Merging and Resolving Prerequisites Whenever metadata consumers merge prerequisites, either from different phases or from C, they should merged in a way which preserves the intended semantics of the prerequisite structure. Generally, this means concatenating the version specifications using commas, as described in the L section. Another subtle error that can occur in resolving prerequisites comes from the way that modules in prerequisites are indexed to distribution files on CPAN. When a module is deleted from a distribution, prerequisites calling for that module could indicate an older distribution should be installed, potentially overwriting files from a newer distribution. For example, as of Oct 31, 2009, the CPAN index file contained these module-distribution mappings: Class::MOP 0.94 D/DR/DROLSKY/Class-MOP-0.94.tar.gz Class::MOP::Class 0.94 D/DR/DROLSKY/Class-MOP-0.94.tar.gz Class::MOP::Class::Immutable 0.04 S/ST/STEVAN/Class-MOP-0.36.tar.gz Consider the case where "Class::MOP" 0.94 is installed. If a distribution specified "Class::MOP::Class::Immutable" as a prerequisite, it could result in Class-MOP-0.36.tar.gz being installed, overwriting any files from Class-MOP-0.94.tar.gz. Consumers of metadata B test whether prerequisites would result in installed module files being "downgraded" to an older version and B warn users or ignore the prerequisite that would cause such a result. =head1 SERIALIZATION Distribution metadata should be serialized (as a hashref) as JSON-encoded data and packaged with distributions as the file F. In the past, the distribution metadata structure had been packed with distributions as F, a file in the YAML Tiny format (for which, see L). Tools that consume distribution metadata from disk should be capable of loading F, but should prefer F if both are found. =head1 NOTES FOR IMPLEMENTORS =head2 Extracting Version Numbers from Perl Modules To get the version number from a Perl module, consumers should use the C<< MM->parse_version($file) >> method provided by L or L. For example, for the module given by C<$mod>, the version may be retrieved in one of the following ways: # via ExtUtils::MakeMaker my $file = MM->_installed_file_for_module($mod); my $version = MM->parse_version($file) The private C<_installed_file_for_module> method may be replaced with other methods for locating a module in C<@INC>. # via Module::Metadata my $info = Module::Metadata->new_from_module($mod); my $version = $info->version; If only a filename is available, the following approach may be used: # via Module::Build my $info = Module::Metadata->new_from_file($file); my $version = $info->version; =head2 Comparing Version Numbers The L module provides the most reliable way to compare version numbers in all the various ways they might be provided or might exist within modules. Given two strings containing version numbers, C<$v1> and C<$v2>, they should be converted to C objects before using ordinary comparison operators. For example: use version; if ( version->new($v1) <=> version->new($v2) ) { print "Versions are not equal\n"; } If the only comparison needed is whether an installed module is of a sufficiently high version, a direct test may be done using the string form of C and the C function. For example, for module C<$mod> and version prerequisite C<$prereq>: if ( eval "use $mod $prereq (); 1" ) { print "Module $mod version is OK.\n"; } If the values of C<$mod> and C<$prereq> have not been scrubbed, however, this presents security implications. =head2 Prerequisites for dynamically configured distributions When C is true, it is an error to presume that the prerequisites given in distribution metadata will have any relationship whatsoever to the actual prerequisites of the distribution. In practice, however, one can generally expect such prerequisites to be one of two things: =over 4 =item * The minimum prerequisites for the distribution, to which dynamic configuration will only add items =item * Whatever the distribution configured with on the releaser's machine at release time =back The second case often turns out to have identical results to the first case, albeit only by accident. As such, consumers may use this data for informational analysis, but presenting it to the user as canonical or relying on it as such is invariably the height of folly. =head2 Indexing distributions a la PAUSE While no_index tells you what must be ignored when indexing, this spec holds no opinion on how you should get your initial candidate list of things to possibly index. For "normal" distributions you might consider simply indexing the contents of lib/, but there are many fascinating oddities on CPAN and many dists from the days when it was normal to put the main .pm file in the root of the distribution archive - so PAUSE currently indexes all .pm and .PL files that are not either (a) specifically excluded by no_index (b) in C, C, or C directories, or common 'mistake' directories such as C. Or: If you're trying to be PAUSE-like, make sure you skip C, C and C as well as anything marked as no_index. Also remember: If the META file contains a provides field, you shouldn't be indexing anything in the first place - just use that. =head1 SEE ALSO =over 4 =item * CPAN, L =item * JSON, L =item * YAML, L =item * L =item * L =item * L =item * L =item * L =back =head1 HISTORY Ken Williams wrote the original CPAN Meta Spec (also known as the "META.yml spec") in 2003 and maintained it through several revisions with input from various members of the community. In 2005, Randy Sims redrafted it from HTML to POD for the version 1.2 release. Ken continued to maintain the spec through version 1.4. In late 2009, David Golden organized the version 2 proposal review process. David and Ricardo Signes drafted the final version 2 spec in April 2010 based on the version 1.4 spec and patches contributed during the proposal process. =head1 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!…Ÿ+n„n„perl5/CPAN/Meta/Validator.pmnuÏÃ6Ç$use 5.006; use strict; use warnings; package CPAN::Meta::Validator; # VERSION $CPAN::Meta::Validator::VERSION = '2.143240'; #pod =head1 SYNOPSIS #pod #pod my $struct = decode_json_file('META.json'); #pod #pod my $cmv = CPAN::Meta::Validator->new( $struct ); #pod #pod unless ( $cmv->is_valid ) { #pod my $msg = "Invalid META structure. Errors found:\n"; #pod $msg .= join( "\n", $cmv->errors ); #pod die $msg; #pod } #pod #pod =head1 DESCRIPTION #pod #pod This module validates a CPAN Meta structure against the version of the #pod the specification claimed in the C field of the structure. #pod #pod =cut #--------------------------------------------------------------------------# # This code copied and adapted from Test::CPAN::Meta # by Barbie, for Miss Barbell Productions, # L #--------------------------------------------------------------------------# #--------------------------------------------------------------------------# # Specification Definitions #--------------------------------------------------------------------------# my %known_specs = ( '1.4' => 'http://module-build.sourceforge.net/META-spec-v1.4.html', '1.3' => 'http://module-build.sourceforge.net/META-spec-v1.3.html', '1.2' => 'http://module-build.sourceforge.net/META-spec-v1.2.html', '1.1' => 'http://module-build.sourceforge.net/META-spec-v1.1.html', '1.0' => 'http://module-build.sourceforge.net/META-spec-v1.0.html' ); my %known_urls = map {$known_specs{$_} => $_} keys %known_specs; my $module_map1 = { 'map' => { ':key' => { name => \&module, value => \&exversion } } }; my $module_map2 = { 'map' => { ':key' => { name => \&module, value => \&version } } }; my $no_index_2 = { 'map' => { file => { list => { value => \&string } }, directory => { list => { value => \&string } }, 'package' => { list => { value => \&string } }, namespace => { list => { value => \&string } }, ':key' => { name => \&custom_2, value => \&anything }, } }; my $no_index_1_3 = { 'map' => { file => { list => { value => \&string } }, directory => { list => { value => \&string } }, 'package' => { list => { value => \&string } }, namespace => { list => { value => \&string } }, ':key' => { name => \&string, value => \&anything }, } }; my $no_index_1_2 = { 'map' => { file => { list => { value => \&string } }, dir => { list => { value => \&string } }, 'package' => { list => { value => \&string } }, namespace => { list => { value => \&string } }, ':key' => { name => \&string, value => \&anything }, } }; my $no_index_1_1 = { 'map' => { ':key' => { name => \&string, list => { value => \&string } }, } }; my $prereq_map = { map => { ':key' => { name => \&phase, 'map' => { ':key' => { name => \&relation, %$module_map1, }, }, } }, }; my %definitions = ( '2' => { # REQUIRED 'abstract' => { mandatory => 1, value => \&string }, 'author' => { mandatory => 1, list => { value => \&string } }, 'dynamic_config' => { mandatory => 1, value => \&boolean }, 'generated_by' => { mandatory => 1, value => \&string }, 'license' => { mandatory => 1, list => { value => \&license } }, 'meta-spec' => { mandatory => 1, 'map' => { version => { mandatory => 1, value => \&version}, url => { value => \&url }, ':key' => { name => \&custom_2, value => \&anything }, } }, 'name' => { mandatory => 1, value => \&string }, 'release_status' => { mandatory => 1, value => \&release_status }, 'version' => { mandatory => 1, value => \&version }, # OPTIONAL 'description' => { value => \&string }, 'keywords' => { list => { value => \&string } }, 'no_index' => $no_index_2, 'optional_features' => { 'map' => { ':key' => { name => \&string, 'map' => { description => { value => \&string }, prereqs => $prereq_map, ':key' => { name => \&custom_2, value => \&anything }, } } } }, 'prereqs' => $prereq_map, 'provides' => { 'map' => { ':key' => { name => \&module, 'map' => { file => { mandatory => 1, value => \&file }, version => { value => \&version }, ':key' => { name => \&custom_2, value => \&anything }, } } } }, 'resources' => { 'map' => { license => { list => { value => \&url } }, homepage => { value => \&url }, bugtracker => { 'map' => { web => { value => \&url }, mailto => { value => \&string}, ':key' => { name => \&custom_2, value => \&anything }, } }, repository => { 'map' => { web => { value => \&url }, url => { value => \&url }, type => { value => \&string }, ':key' => { name => \&custom_2, value => \&anything }, } }, ':key' => { value => \&string, name => \&custom_2 }, } }, # CUSTOM -- additional user defined key/value pairs # note we can only validate the key name, as the structure is user defined ':key' => { name => \&custom_2, value => \&anything }, }, '1.4' => { 'meta-spec' => { mandatory => 1, 'map' => { version => { mandatory => 1, value => \&version}, url => { mandatory => 1, value => \&urlspec }, ':key' => { name => \&string, value => \&anything }, }, }, 'name' => { mandatory => 1, value => \&string }, 'version' => { mandatory => 1, value => \&version }, 'abstract' => { mandatory => 1, value => \&string }, 'author' => { mandatory => 1, list => { value => \&string } }, 'license' => { mandatory => 1, value => \&license }, 'generated_by' => { mandatory => 1, value => \&string }, 'distribution_type' => { value => \&string }, 'dynamic_config' => { value => \&boolean }, 'requires' => $module_map1, 'recommends' => $module_map1, 'build_requires' => $module_map1, 'configure_requires' => $module_map1, 'conflicts' => $module_map2, 'optional_features' => { 'map' => { ':key' => { name => \&string, 'map' => { description => { value => \&string }, requires => $module_map1, recommends => $module_map1, build_requires => $module_map1, conflicts => $module_map2, ':key' => { name => \&string, value => \&anything }, } } } }, 'provides' => { 'map' => { ':key' => { name => \&module, 'map' => { file => { mandatory => 1, value => \&file }, version => { value => \&version }, ':key' => { name => \&string, value => \&anything }, } } } }, 'no_index' => $no_index_1_3, 'private' => $no_index_1_3, 'keywords' => { list => { value => \&string } }, 'resources' => { 'map' => { license => { value => \&url }, homepage => { value => \&url }, bugtracker => { value => \&url }, repository => { value => \&url }, ':key' => { value => \&string, name => \&custom_1 }, } }, # additional user defined key/value pairs # note we can only validate the key name, as the structure is user defined ':key' => { name => \&string, value => \&anything }, }, '1.3' => { 'meta-spec' => { mandatory => 1, 'map' => { version => { mandatory => 1, value => \&version}, url => { mandatory => 1, value => \&urlspec }, ':key' => { name => \&string, value => \&anything }, }, }, 'name' => { mandatory => 1, value => \&string }, 'version' => { mandatory => 1, value => \&version }, 'abstract' => { mandatory => 1, value => \&string }, 'author' => { mandatory => 1, list => { value => \&string } }, 'license' => { mandatory => 1, value => \&license }, 'generated_by' => { mandatory => 1, value => \&string }, 'distribution_type' => { value => \&string }, 'dynamic_config' => { value => \&boolean }, 'requires' => $module_map1, 'recommends' => $module_map1, 'build_requires' => $module_map1, 'conflicts' => $module_map2, 'optional_features' => { 'map' => { ':key' => { name => \&string, 'map' => { description => { value => \&string }, requires => $module_map1, recommends => $module_map1, build_requires => $module_map1, conflicts => $module_map2, ':key' => { name => \&string, value => \&anything }, } } } }, 'provides' => { 'map' => { ':key' => { name => \&module, 'map' => { file => { mandatory => 1, value => \&file }, version => { value => \&version }, ':key' => { name => \&string, value => \&anything }, } } } }, 'no_index' => $no_index_1_3, 'private' => $no_index_1_3, 'keywords' => { list => { value => \&string } }, 'resources' => { 'map' => { license => { value => \&url }, homepage => { value => \&url }, bugtracker => { value => \&url }, repository => { value => \&url }, ':key' => { value => \&string, name => \&custom_1 }, } }, # additional user defined key/value pairs # note we can only validate the key name, as the structure is user defined ':key' => { name => \&string, value => \&anything }, }, # v1.2 is misleading, it seems to assume that a number of fields where created # within v1.1, when they were created within v1.2. This may have been an # original mistake, and that a v1.1 was retro fitted into the timeline, when # v1.2 was originally slated as v1.1. But I could be wrong ;) '1.2' => { 'meta-spec' => { mandatory => 1, 'map' => { version => { mandatory => 1, value => \&version}, url => { mandatory => 1, value => \&urlspec }, ':key' => { name => \&string, value => \&anything }, }, }, 'name' => { mandatory => 1, value => \&string }, 'version' => { mandatory => 1, value => \&version }, 'license' => { mandatory => 1, value => \&license }, 'generated_by' => { mandatory => 1, value => \&string }, 'author' => { mandatory => 1, list => { value => \&string } }, 'abstract' => { mandatory => 1, value => \&string }, 'distribution_type' => { value => \&string }, 'dynamic_config' => { value => \&boolean }, 'keywords' => { list => { value => \&string } }, 'private' => $no_index_1_2, '$no_index' => $no_index_1_2, 'requires' => $module_map1, 'recommends' => $module_map1, 'build_requires' => $module_map1, 'conflicts' => $module_map2, 'optional_features' => { 'map' => { ':key' => { name => \&string, 'map' => { description => { value => \&string }, requires => $module_map1, recommends => $module_map1, build_requires => $module_map1, conflicts => $module_map2, ':key' => { name => \&string, value => \&anything }, } } } }, 'provides' => { 'map' => { ':key' => { name => \&module, 'map' => { file => { mandatory => 1, value => \&file }, version => { value => \&version }, ':key' => { name => \&string, value => \&anything }, } } } }, 'resources' => { 'map' => { license => { value => \&url }, homepage => { value => \&url }, bugtracker => { value => \&url }, repository => { value => \&url }, ':key' => { value => \&string, name => \&custom_1 }, } }, # additional user defined key/value pairs # note we can only validate the key name, as the structure is user defined ':key' => { name => \&string, value => \&anything }, }, # note that the 1.1 spec only specifies 'version' as mandatory '1.1' => { 'name' => { value => \&string }, 'version' => { mandatory => 1, value => \&version }, 'license' => { value => \&license }, 'generated_by' => { value => \&string }, 'license_uri' => { value => \&url }, 'distribution_type' => { value => \&string }, 'dynamic_config' => { value => \&boolean }, 'private' => $no_index_1_1, 'requires' => $module_map1, 'recommends' => $module_map1, 'build_requires' => $module_map1, 'conflicts' => $module_map2, # additional user defined key/value pairs # note we can only validate the key name, as the structure is user defined ':key' => { name => \&string, value => \&anything }, }, # note that the 1.0 spec doesn't specify optional or mandatory fields # but we will treat version as mandatory since otherwise META 1.0 is # completely arbitrary and pointless '1.0' => { 'name' => { value => \&string }, 'version' => { mandatory => 1, value => \&version }, 'license' => { value => \&license }, 'generated_by' => { value => \&string }, 'license_uri' => { value => \&url }, 'distribution_type' => { value => \&string }, 'dynamic_config' => { value => \&boolean }, 'requires' => $module_map1, 'recommends' => $module_map1, 'build_requires' => $module_map1, 'conflicts' => $module_map2, # additional user defined key/value pairs # note we can only validate the key name, as the structure is user defined ':key' => { name => \&string, value => \&anything }, }, ); #--------------------------------------------------------------------------# # Code #--------------------------------------------------------------------------# #pod =method new #pod #pod my $cmv = CPAN::Meta::Validator->new( $struct ) #pod #pod The constructor must be passed a metadata structure. #pod #pod =cut sub new { my ($class,$data) = @_; # create an attributes hash my $self = { 'data' => $data, 'spec' => eval { $data->{'meta-spec'}{'version'} } || "1.0", 'errors' => undef, }; # create the object return bless $self, $class; } #pod =method is_valid #pod #pod if ( $cmv->is_valid ) { #pod ... #pod } #pod #pod Returns a boolean value indicating whether the metadata provided #pod is valid. #pod #pod =cut sub is_valid { my $self = shift; my $data = $self->{data}; my $spec_version = $self->{spec}; $self->check_map($definitions{$spec_version},$data); return ! $self->errors; } #pod =method errors #pod #pod warn( join "\n", $cmv->errors ); #pod #pod Returns a list of errors seen during validation. #pod #pod =cut sub errors { my $self = shift; return () unless(defined $self->{errors}); return @{$self->{errors}}; } #pod =begin :internals #pod #pod =head2 Check Methods #pod #pod =over #pod #pod =item * #pod #pod check_map($spec,$data) #pod #pod Checks whether a map (or hash) part of the data structure conforms to the #pod appropriate specification definition. #pod #pod =item * #pod #pod check_list($spec,$data) #pod #pod Checks whether a list (or array) part of the data structure conforms to #pod the appropriate specification definition. #pod #pod =item * #pod #pod =back #pod #pod =cut my $spec_error = "Missing validation action in specification. " . "Must be one of 'map', 'list', or 'value'"; sub check_map { my ($self,$spec,$data) = @_; if(ref($spec) ne 'HASH') { $self->_error( "Unknown META specification, cannot validate." ); return; } if(ref($data) ne 'HASH') { $self->_error( "Expected a map structure from string or file." ); return; } for my $key (keys %$spec) { next unless($spec->{$key}->{mandatory}); next if(defined $data->{$key}); push @{$self->{stack}}, $key; $self->_error( "Missing mandatory field, '$key'" ); pop @{$self->{stack}}; } for my $key (keys %$data) { push @{$self->{stack}}, $key; if($spec->{$key}) { if($spec->{$key}{value}) { $spec->{$key}{value}->($self,$key,$data->{$key}); } elsif($spec->{$key}{'map'}) { $self->check_map($spec->{$key}{'map'},$data->{$key}); } elsif($spec->{$key}{'list'}) { $self->check_list($spec->{$key}{'list'},$data->{$key}); } else { $self->_error( "$spec_error for '$key'" ); } } elsif ($spec->{':key'}) { $spec->{':key'}{name}->($self,$key,$key); if($spec->{':key'}{value}) { $spec->{':key'}{value}->($self,$key,$data->{$key}); } elsif($spec->{':key'}{'map'}) { $self->check_map($spec->{':key'}{'map'},$data->{$key}); } elsif($spec->{':key'}{'list'}) { $self->check_list($spec->{':key'}{'list'},$data->{$key}); } else { $self->_error( "$spec_error for ':key'" ); } } else { $self->_error( "Unknown key, '$key', found in map structure" ); } pop @{$self->{stack}}; } } sub check_list { my ($self,$spec,$data) = @_; if(ref($data) ne 'ARRAY') { $self->_error( "Expected a list structure" ); return; } if(defined $spec->{mandatory}) { if(!defined $data->[0]) { $self->_error( "Missing entries from mandatory list" ); } } for my $value (@$data) { push @{$self->{stack}}, $value || ""; if(defined $spec->{value}) { $spec->{value}->($self,'list',$value); } elsif(defined $spec->{'map'}) { $self->check_map($spec->{'map'},$value); } elsif(defined $spec->{'list'}) { $self->check_list($spec->{'list'},$value); } elsif ($spec->{':key'}) { $self->check_map($spec,$value); } else { $self->_error( "$spec_error associated with '$self->{stack}[-2]'" ); } pop @{$self->{stack}}; } } #pod =head2 Validator Methods #pod #pod =over #pod #pod =item * #pod #pod header($self,$key,$value) #pod #pod Validates that the header is valid. #pod #pod Note: No longer used as we now read the data structure, not the file. #pod #pod =item * #pod #pod url($self,$key,$value) #pod #pod Validates that a given value is in an acceptable URL format #pod #pod =item * #pod #pod urlspec($self,$key,$value) #pod #pod Validates that the URL to a META specification is a known one. #pod #pod =item * #pod #pod string_or_undef($self,$key,$value) #pod #pod Validates that the value is either a string or an undef value. Bit of a #pod catchall function for parts of the data structure that are completely user #pod defined. #pod #pod =item * #pod #pod string($self,$key,$value) #pod #pod Validates that a string exists for the given key. #pod #pod =item * #pod #pod file($self,$key,$value) #pod #pod Validate that a file is passed for the given key. This may be made more #pod thorough in the future. For now it acts like \&string. #pod #pod =item * #pod #pod exversion($self,$key,$value) #pod #pod Validates a list of versions, e.g. '<= 5, >=2, ==3, !=4, >1, <6, 0'. #pod #pod =item * #pod #pod version($self,$key,$value) #pod #pod Validates a single version string. Versions of the type '5.8.8' and '0.00_00' #pod are both valid. A leading 'v' like 'v1.2.3' is also valid. #pod #pod =item * #pod #pod boolean($self,$key,$value) #pod #pod Validates for a boolean value. Currently these values are '1', '0', 'true', #pod 'false', however the latter 2 may be removed. #pod #pod =item * #pod #pod license($self,$key,$value) #pod #pod Validates that a value is given for the license. Returns 1 if an known license #pod type, or 2 if a value is given but the license type is not a recommended one. #pod #pod =item * #pod #pod custom_1($self,$key,$value) #pod #pod Validates that the given key is in CamelCase, to indicate a user defined #pod keyword and only has characters in the class [-_a-zA-Z]. In version 1.X #pod of the spec, this was only explicitly stated for 'resources'. #pod #pod =item * #pod #pod custom_2($self,$key,$value) #pod #pod Validates that the given key begins with 'x_' or 'X_', to indicate a user #pod defined keyword and only has characters in the class [-_a-zA-Z] #pod #pod =item * #pod #pod identifier($self,$key,$value) #pod #pod Validates that key is in an acceptable format for the META specification, #pod for an identifier, i.e. any that matches the regular expression #pod qr/[a-z][a-z_]/i. #pod #pod =item * #pod #pod module($self,$key,$value) #pod #pod Validates that a given key is in an acceptable module name format, e.g. #pod 'Test::CPAN::Meta::Version'. #pod #pod =back #pod #pod =end :internals #pod #pod =cut sub header { my ($self,$key,$value) = @_; if(defined $value) { return 1 if($value && $value =~ /^--- #YAML:1.0/); } $self->_error( "file does not have a valid YAML header." ); return 0; } sub release_status { my ($self,$key,$value) = @_; if(defined $value) { my $version = $self->{data}{version} || ''; if ( $version =~ /_/ ) { return 1 if ( $value =~ /\A(?:testing|unstable)\z/ ); $self->_error( "'$value' for '$key' is invalid for version '$version'" ); } else { return 1 if ( $value =~ /\A(?:stable|testing|unstable)\z/ ); $self->_error( "'$value' for '$key' is invalid" ); } } else { $self->_error( "'$key' is not defined" ); } return 0; } # _uri_split taken from URI::Split by Gisle Aas, Copyright 2003 sub _uri_split { return $_[0] =~ m,(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?,; } sub url { my ($self,$key,$value) = @_; if(defined $value) { my ($scheme, $auth, $path, $query, $frag) = _uri_split($value); unless ( defined $scheme && length $scheme ) { $self->_error( "'$value' for '$key' does not have a URL scheme" ); return 0; } unless ( defined $auth && length $auth ) { $self->_error( "'$value' for '$key' does not have a URL authority" ); return 0; } return 1; } $value ||= ''; $self->_error( "'$value' for '$key' is not a valid URL." ); return 0; } sub urlspec { my ($self,$key,$value) = @_; if(defined $value) { return 1 if($value && $known_specs{$self->{spec}} eq $value); if($value && $known_urls{$value}) { $self->_error( 'META specification URL does not match version' ); return 0; } } $self->_error( 'Unknown META specification' ); return 0; } sub anything { return 1 } sub string { my ($self,$key,$value) = @_; if(defined $value) { return 1 if($value || $value =~ /^0$/); } $self->_error( "value is an undefined string" ); return 0; } sub string_or_undef { my ($self,$key,$value) = @_; return 1 unless(defined $value); return 1 if($value || $value =~ /^0$/); $self->_error( "No string defined for '$key'" ); return 0; } sub file { my ($self,$key,$value) = @_; return 1 if(defined $value); $self->_error( "No file defined for '$key'" ); return 0; } sub exversion { my ($self,$key,$value) = @_; if(defined $value && ($value || $value =~ /0/)) { my $pass = 1; for(split(",",$value)) { $self->version($key,$_) or ($pass = 0); } return $pass; } $value = '' unless(defined $value); $self->_error( "'$value' for '$key' is not a valid version." ); return 0; } sub version { my ($self,$key,$value) = @_; if(defined $value) { return 0 unless($value || $value =~ /0/); return 1 if($value =~ /^\s*((<|<=|>=|>|!=|==)\s*)?v?\d+((\.\d+((_|\.)\d+)?)?)/); } else { $value = ''; } $self->_error( "'$value' for '$key' is not a valid version." ); return 0; } sub boolean { my ($self,$key,$value) = @_; if(defined $value) { return 1 if($value =~ /^(0|1|true|false)$/); } else { $value = ''; } $self->_error( "'$value' for '$key' is not a boolean value." ); return 0; } my %v1_licenses = ( 'perl' => 'http://dev.perl.org/licenses/', 'gpl' => 'http://www.opensource.org/licenses/gpl-license.php', 'apache' => 'http://apache.org/licenses/LICENSE-2.0', 'artistic' => 'http://opensource.org/licenses/artistic-license.php', 'artistic_2' => 'http://opensource.org/licenses/artistic-license-2.0.php', 'lgpl' => 'http://www.opensource.org/licenses/lgpl-license.php', 'bsd' => 'http://www.opensource.org/licenses/bsd-license.php', 'gpl' => 'http://www.opensource.org/licenses/gpl-license.php', 'mit' => 'http://opensource.org/licenses/mit-license.php', 'mozilla' => 'http://opensource.org/licenses/mozilla1.1.php', 'open_source' => undef, 'unrestricted' => undef, 'restrictive' => undef, 'unknown' => undef, ); my %v2_licenses = map { $_ => 1 } qw( agpl_3 apache_1_1 apache_2_0 artistic_1 artistic_2 bsd freebsd gfdl_1_2 gfdl_1_3 gpl_1 gpl_2 gpl_3 lgpl_2_1 lgpl_3_0 mit mozilla_1_0 mozilla_1_1 openssl perl_5 qpl_1_0 ssleay sun zlib open_source restricted unrestricted unknown ); sub license { my ($self,$key,$value) = @_; my $licenses = $self->{spec} < 2 ? \%v1_licenses : \%v2_licenses; if(defined $value) { return 1 if($value && exists $licenses->{$value}); } else { $value = ''; } $self->_error( "License '$value' is invalid" ); return 0; } sub custom_1 { my ($self,$key) = @_; if(defined $key) { # a valid user defined key should be alphabetic # and contain at least one capital case letter. return 1 if($key && $key =~ /^[_a-z]+$/i && $key =~ /[A-Z]/); } else { $key = ''; } $self->_error( "Custom resource '$key' must be in CamelCase." ); return 0; } sub custom_2 { my ($self,$key) = @_; if(defined $key) { return 1 if($key && $key =~ /^x_/i); # user defined } else { $key = ''; } $self->_error( "Custom key '$key' must begin with 'x_' or 'X_'." ); return 0; } sub identifier { my ($self,$key) = @_; if(defined $key) { return 1 if($key && $key =~ /^([a-z][_a-z]+)$/i); # spec 2.0 defined } else { $key = ''; } $self->_error( "Key '$key' is not a legal identifier." ); return 0; } sub module { my ($self,$key) = @_; if(defined $key) { return 1 if($key && $key =~ /^[A-Za-z0-9_]+(::[A-Za-z0-9_]+)*$/); } else { $key = ''; } $self->_error( "Key '$key' is not a legal module name." ); return 0; } my @valid_phases = qw/ configure build test runtime develop /; sub phase { my ($self,$key) = @_; if(defined $key) { return 1 if( length $key && grep { $key eq $_ } @valid_phases ); return 1 if $key =~ /x_/i; } else { $key = ''; } $self->_error( "Key '$key' is not a legal phase." ); return 0; } my @valid_relations = qw/ requires recommends suggests conflicts /; sub relation { my ($self,$key) = @_; if(defined $key) { return 1 if( length $key && grep { $key eq $_ } @valid_relations ); return 1 if $key =~ /x_/i; } else { $key = ''; } $self->_error( "Key '$key' is not a legal prereq relationship." ); return 0; } sub _error { my $self = shift; my $mess = shift; $mess .= ' ('.join(' -> ',@{$self->{stack}}).')' if($self->{stack}); $mess .= " [Validation: $self->{spec}]"; push @{$self->{errors}}, $mess; } 1; # ABSTRACT: validate CPAN distribution metadata structures __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Validator - validate CPAN distribution metadata structures =head1 VERSION version 2.143240 =head1 SYNOPSIS my $struct = decode_json_file('META.json'); my $cmv = CPAN::Meta::Validator->new( $struct ); unless ( $cmv->is_valid ) { my $msg = "Invalid META structure. Errors found:\n"; $msg .= join( "\n", $cmv->errors ); die $msg; } =head1 DESCRIPTION This module validates a CPAN Meta structure against the version of the the specification claimed in the C field of the structure. =head1 METHODS =head2 new my $cmv = CPAN::Meta::Validator->new( $struct ) The constructor must be passed a metadata structure. =head2 is_valid if ( $cmv->is_valid ) { ... } Returns a boolean value indicating whether the metadata provided is valid. =head2 errors warn( join "\n", $cmv->errors ); Returns a list of errors seen during validation. =begin :internals =head2 Check Methods =over =item * check_map($spec,$data) Checks whether a map (or hash) part of the data structure conforms to the appropriate specification definition. =item * check_list($spec,$data) Checks whether a list (or array) part of the data structure conforms to the appropriate specification definition. =item * =back =head2 Validator Methods =over =item * header($self,$key,$value) Validates that the header is valid. Note: No longer used as we now read the data structure, not the file. =item * url($self,$key,$value) Validates that a given value is in an acceptable URL format =item * urlspec($self,$key,$value) Validates that the URL to a META specification is a known one. =item * string_or_undef($self,$key,$value) Validates that the value is either a string or an undef value. Bit of a catchall function for parts of the data structure that are completely user defined. =item * string($self,$key,$value) Validates that a string exists for the given key. =item * file($self,$key,$value) Validate that a file is passed for the given key. This may be made more thorough in the future. For now it acts like \&string. =item * exversion($self,$key,$value) Validates a list of versions, e.g. '<= 5, >=2, ==3, !=4, >1, <6, 0'. =item * version($self,$key,$value) Validates a single version string. Versions of the type '5.8.8' and '0.00_00' are both valid. A leading 'v' like 'v1.2.3' is also valid. =item * boolean($self,$key,$value) Validates for a boolean value. Currently these values are '1', '0', 'true', 'false', however the latter 2 may be removed. =item * license($self,$key,$value) Validates that a value is given for the license. Returns 1 if an known license type, or 2 if a value is given but the license type is not a recommended one. =item * custom_1($self,$key,$value) Validates that the given key is in CamelCase, to indicate a user defined keyword and only has characters in the class [-_a-zA-Z]. In version 1.X of the spec, this was only explicitly stated for 'resources'. =item * custom_2($self,$key,$value) Validates that the given key begins with 'x_' or 'X_', to indicate a user defined keyword and only has characters in the class [-_a-zA-Z] =item * identifier($self,$key,$value) Validates that key is in an acceptable format for the META specification, for an identifier, i.e. any that matches the regular expression qr/[a-z][a-z_]/i. =item * module($self,$key,$value) Validates that a given key is in an acceptable module name format, e.g. 'Test::CPAN::Meta::Version'. =back =end :internals =for Pod::Coverage anything boolean check_list custom_1 custom_2 exversion file identifier license module phase relation release_status string string_or_undef url urlspec version header check_map =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at 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 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!4T¡ ÏÏperl5/CPAN/Meta/History.pmnuÏÃ6Ç$# vi:tw=72 use 5.006; use strict; use warnings; package CPAN::Meta::History; # VERSION $CPAN::Meta::History::VERSION = '2.143240'; 1; # ABSTRACT: history of CPAN Meta Spec changes __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::History - history of CPAN Meta Spec changes =head1 VERSION version 2.143240 =head1 DESCRIPTION The CPAN Meta Spec has gone through several iterations. It was originally written in HTML and later revised into POD (though published in HTML generated from the POD). Fields were added, removed or changed, sometimes by design and sometimes to reflect real-world usage after the fact. This document reconstructs the history of the CPAN Meta Spec based on change logs, repository commit messages and the published HTML files. In some cases, particularly prior to version 1.2, the exact version when certain fields were introduced or changed is inconsistent between sources. When in doubt, the published HTML files for versions 1.0 to 1.4 as they existed when version 2 was developed are used as the definitive source. Starting with version 2, the specification document is part of the CPAN-Meta distribution and will be published on CPAN as L. Going forward, specification version numbers will be integers and decimal portions will correspond to a release date for the CPAN::Meta library. =head1 HISTORY =head2 Version 2 April 2010 =over =item * Revised spec examples as perl data structures rather than YAML =item * Switched to JSON serialization from YAML =item * Specified allowed version number formats =item * Replaced 'requires', 'build_requires', 'configure_requires', 'recommends' and 'conflicts' with new 'prereqs' data structure divided by I (configure, build, test, runtime, etc.) and I (requires, recommends, suggests, conflicts) =item * Added support for 'develop' phase for requirements for maintaining a list of authoring tools =item * Changed 'license' to a list and revised the set of valid licenses =item * Made 'dynamic_config' mandatory to reduce confusion =item * Changed 'resources' subkey 'repository' to a hash that clarifies repository type, url for browsing and url for checkout =item * Changed 'resources' subkey 'bugtracker' to a hash for either web or mailto resource =item * Changed specification of 'optional_features': =over =item * Added formal specification and usage guide instead of just example =item * Changed to use new prereqs data structure instead of individual keys =back =item * Clarified intended use of 'author' as generalized contact list =item * Added 'release_status' field to indicate stable, testing or unstable status to provide hints to indexers =item * Added 'description' field for a longer description of the distribution =item * Formalized use of "x_" or "X_" for all custom keys not listed in the official spec =back =head2 Version 1.4 June 2008 =over =item * Noted explicit support for 'perl' in prerequisites =item * Added 'configure_requires' prerequisite type =item * Changed 'optional_features' =over =item * Example corrected to show map of maps instead of list of maps (though descriptive text said 'map' even in v1.3) =item * Removed 'requires_packages', 'requires_os' and 'excluded_os' as valid subkeys =back =back =head2 Version 1.3 November 2006 =over =item * Added 'no_index' subkey 'directory' and removed 'dir' to match actual usage in the wild =item * Added a 'repository' subkey to 'resources' =back =head2 Version 1.2 August 2005 =over =item * Re-wrote and restructured spec in POD syntax =item * Changed 'name' to be mandatory =item * Changed 'generated_by' to be mandatory =item * Changed 'license' to be mandatory =item * Added version range specifications for prerequisites =item * Added required 'abstract' field =item * Added required 'author' field =item * Added required 'meta-spec' field to define 'version' (and 'url') of the CPAN Meta Spec used for metadata =item * Added 'provides' field =item * Added 'no_index' field and deprecated 'private' field. 'no_index' subkeys include 'file', 'dir', 'package' and 'namespace' =item * Added 'keywords' field =item * Added 'resources' field with subkeys 'homepage', 'license', and 'bugtracker' =item * Added 'optional_features' field as an alternate under 'recommends'. Includes 'description', 'requires', 'build_requires', 'conflicts', 'requires_packages', 'requires_os' and 'excluded_os' as valid subkeys =item * Removed 'license_uri' field =back =head2 Version 1.1 May 2003 =over =item * Changed 'version' to be mandatory =item * Added 'private' field =item * Added 'license_uri' field =back =head2 Version 1.0 March 2003 =over =item * Original release (in HTML format only) =item * Included 'name', 'version', 'license', 'distribution_type', 'requires', 'recommends', 'build_requires', 'conflicts', 'dynamic_config', 'generated_by' =back =head1 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!�A¼ÆŸÀŸÀperl5/CPAN/Meta/Converter.pmnuÏÃ6Ç$use 5.006; use strict; use warnings; package CPAN::Meta::Converter; # VERSION $CPAN::Meta::Converter::VERSION = '2.143240'; #pod =head1 SYNOPSIS #pod #pod my $struct = decode_json_file('META.json'); #pod #pod my $cmc = CPAN::Meta::Converter->new( $struct ); #pod #pod my $new_struct = $cmc->convert( version => "2" ); #pod #pod =head1 DESCRIPTION #pod #pod This module converts CPAN Meta structures from one form to another. The #pod primary use is to convert older structures to the most modern version of #pod the specification, but other transformations may be implemented in the #pod future as needed. (E.g. stripping all custom fields or stripping all #pod optional fields.) #pod #pod =cut use CPAN::Meta::Validator; use CPAN::Meta::Requirements; use Parse::CPAN::Meta 1.4400 (); # To help ExtUtils::MakeMaker bootstrap CPAN::Meta::Requirements on perls # before 5.10, we fall back to the EUMM bundled compatibility version module if # that's the only thing available. This shouldn't ever happen in a normal CPAN # install of CPAN::Meta::Requirements, as version.pm will be picked up from # prereqs and be available at runtime. BEGIN { eval "use version ()"; ## no critic if ( my $err = $@ ) { eval "use ExtUtils::MakeMaker::version" or die $err; ## no critic } } # Perl 5.10.0 didn't have "is_qv" in version.pm *_is_qv = version->can('is_qv') ? sub { $_[0]->is_qv } : sub { exists $_[0]->{qv} }; sub _dclone { my $ref = shift; # if an object is in the data structure and doesn't specify how to # turn itself into JSON, we just stringify the object. That does the # right thing for typical things that might be there, like version objects, # Path::Class objects, etc. no warnings 'once'; no warnings 'redefine'; local *UNIVERSAL::TO_JSON = sub { "$_[0]" }; my $json = Parse::CPAN::Meta->json_backend()->new ->utf8 ->allow_blessed ->convert_blessed; $json->decode($json->encode($ref)) } my %known_specs = ( '2' => 'http://search.cpan.org/perldoc?CPAN::Meta::Spec', '1.4' => 'http://module-build.sourceforge.net/META-spec-v1.4.html', '1.3' => 'http://module-build.sourceforge.net/META-spec-v1.3.html', '1.2' => 'http://module-build.sourceforge.net/META-spec-v1.2.html', '1.1' => 'http://module-build.sourceforge.net/META-spec-v1.1.html', '1.0' => 'http://module-build.sourceforge.net/META-spec-v1.0.html' ); my @spec_list = sort { $a <=> $b } keys %known_specs; my ($LOWEST, $HIGHEST) = @spec_list[0,-1]; #--------------------------------------------------------------------------# # converters # # called as $converter->($element, $field_name, $full_meta, $to_version) # # defined return value used for field # undef return value means field is skipped #--------------------------------------------------------------------------# sub _keep { $_[0] } sub _keep_or_one { defined($_[0]) ? $_[0] : 1 } sub _keep_or_zero { defined($_[0]) ? $_[0] : 0 } sub _keep_or_unknown { defined($_[0]) && length($_[0]) ? $_[0] : "unknown" } sub _generated_by { my $gen = shift; my $sig = __PACKAGE__ . " version " . (__PACKAGE__->VERSION || ""); return $sig unless defined $gen and length $gen; return $gen if $gen =~ /\Q$sig/; return "$gen, $sig"; } sub _listify { ! defined $_[0] ? undef : ref $_[0] eq 'ARRAY' ? $_[0] : [$_[0]] } sub _prefix_custom { my $key = shift; $key =~ s/^(?!x_) # Unless it already starts with x_ (?:x-?)? # Remove leading x- or x (if present) /x_/ix; # and prepend x_ return $key; } sub _ucfirst_custom { my $key = shift; $key = ucfirst $key unless $key =~ /[A-Z]/; return $key; } sub _no_prefix_ucfirst_custom { my $key = shift; $key =~ s/^x_//; return _ucfirst_custom($key); } sub _change_meta_spec { my ($element, undef, undef, $version) = @_; return { version => $version, url => $known_specs{$version}, }; } my @open_source = ( 'perl', 'gpl', 'apache', 'artistic', 'artistic_2', 'lgpl', 'bsd', 'gpl', 'mit', 'mozilla', 'open_source', ); my %is_open_source = map {; $_ => 1 } @open_source; my @valid_licenses_1 = ( @open_source, 'unrestricted', 'restrictive', 'unknown', ); my %license_map_1 = ( ( map { $_ => $_ } @valid_licenses_1 ), artistic2 => 'artistic_2', ); sub _license_1 { my ($element) = @_; return 'unknown' unless defined $element; if ( $license_map_1{lc $element} ) { return $license_map_1{lc $element}; } else { return 'unknown'; } } my @valid_licenses_2 = qw( agpl_3 apache_1_1 apache_2_0 artistic_1 artistic_2 bsd freebsd gfdl_1_2 gfdl_1_3 gpl_1 gpl_2 gpl_3 lgpl_2_1 lgpl_3_0 mit mozilla_1_0 mozilla_1_1 openssl perl_5 qpl_1_0 ssleay sun zlib open_source restricted unrestricted unknown ); # The "old" values were defined by Module::Build, and were often vague. I have # made the decisions below based on reading Module::Build::API and how clearly # it specifies the version of the license. my %license_map_2 = ( (map { $_ => $_ } @valid_licenses_2), apache => 'apache_2_0', # clearly stated as 2.0 artistic => 'artistic_1', # clearly stated as 1 artistic2 => 'artistic_2', # clearly stated as 2 gpl => 'open_source', # we don't know which GPL; punt lgpl => 'open_source', # we don't know which LGPL; punt mozilla => 'open_source', # we don't know which MPL; punt perl => 'perl_5', # clearly Perl 5 restrictive => 'restricted', ); sub _license_2 { my ($element) = @_; return [ 'unknown' ] unless defined $element; $element = [ $element ] unless ref $element eq 'ARRAY'; my @new_list; for my $lic ( @$element ) { next unless defined $lic; if ( my $new = $license_map_2{lc $lic} ) { push @new_list, $new; } } return @new_list ? \@new_list : [ 'unknown' ]; } my %license_downgrade_map = qw( agpl_3 open_source apache_1_1 apache apache_2_0 apache artistic_1 artistic artistic_2 artistic_2 bsd bsd freebsd open_source gfdl_1_2 open_source gfdl_1_3 open_source gpl_1 gpl gpl_2 gpl gpl_3 gpl lgpl_2_1 lgpl lgpl_3_0 lgpl mit mit mozilla_1_0 mozilla mozilla_1_1 mozilla openssl open_source perl_5 perl qpl_1_0 open_source ssleay open_source sun open_source zlib open_source open_source open_source restricted restrictive unrestricted unrestricted unknown unknown ); sub _downgrade_license { my ($element) = @_; if ( ! defined $element ) { return "unknown"; } elsif( ref $element eq 'ARRAY' ) { if ( @$element > 1) { if (grep { !$is_open_source{ $license_downgrade_map{lc $_} || 'unknown' } } @$element) { return 'unknown'; } else { return 'open_source'; } } elsif ( @$element == 1 ) { return $license_downgrade_map{lc $element->[0]} || "unknown"; } } elsif ( ! ref $element ) { return $license_downgrade_map{lc $element} || "unknown"; } return "unknown"; } my $no_index_spec_1_2 = { 'file' => \&_listify, 'dir' => \&_listify, 'package' => \&_listify, 'namespace' => \&_listify, }; my $no_index_spec_1_3 = { 'file' => \&_listify, 'directory' => \&_listify, 'package' => \&_listify, 'namespace' => \&_listify, }; my $no_index_spec_2 = { 'file' => \&_listify, 'directory' => \&_listify, 'package' => \&_listify, 'namespace' => \&_listify, ':custom' => \&_prefix_custom, }; sub _no_index_1_2 { my (undef, undef, $meta) = @_; my $no_index = $meta->{no_index} || $meta->{private}; return unless $no_index; # cleanup wrong format if ( ! ref $no_index ) { my $item = $no_index; $no_index = { dir => [ $item ], file => [ $item ] }; } elsif ( ref $no_index eq 'ARRAY' ) { my $list = $no_index; $no_index = { dir => [ @$list ], file => [ @$list ] }; } # common mistake: files -> file if ( exists $no_index->{files} ) { $no_index->{file} = delete $no_index->{file}; } # common mistake: modules -> module if ( exists $no_index->{modules} ) { $no_index->{module} = delete $no_index->{module}; } return _convert($no_index, $no_index_spec_1_2); } sub _no_index_directory { my ($element, $key, $meta, $version) = @_; return unless $element; # cleanup wrong format if ( ! ref $element ) { my $item = $element; $element = { directory => [ $item ], file => [ $item ] }; } elsif ( ref $element eq 'ARRAY' ) { my $list = $element; $element = { directory => [ @$list ], file => [ @$list ] }; } if ( exists $element->{dir} ) { $element->{directory} = delete $element->{dir}; } # common mistake: files -> file if ( exists $element->{files} ) { $element->{file} = delete $element->{file}; } # common mistake: modules -> module if ( exists $element->{modules} ) { $element->{module} = delete $element->{module}; } my $spec = $version == 2 ? $no_index_spec_2 : $no_index_spec_1_3; return _convert($element, $spec); } sub _is_module_name { my $mod = shift; return unless defined $mod && length $mod; return $mod =~ m{^[A-Za-z][A-Za-z0-9_]*(?:::[A-Za-z0-9_]+)*$}; } sub _clean_version { my ($element) = @_; return 0 if ! defined $element; $element =~ s{^\s*}{}; $element =~ s{\s*$}{}; $element =~ s{^\.}{0.}; return 0 if ! length $element; return 0 if ( $element eq 'undef' || $element eq '' ); my $v = eval { version->new($element) }; # XXX check defined $v and not just $v because version objects leak memory # in boolean context -- dagolden, 2012-02-03 if ( defined $v ) { return _is_qv($v) ? $v->normal : $element; } else { return 0; } } sub _bad_version_hook { my ($v) = @_; $v =~ s{[a-z]+$}{}; # strip trailing alphabetics my $vobj = eval { version->new($v) }; return defined($vobj) ? $vobj : version->new(0); # or give up } sub _version_map { my ($element) = @_; return unless defined $element; if ( ref $element eq 'HASH' ) { # XXX turn this into CPAN::Meta::Requirements with bad version hook # and then turn it back into a hash my $new_map = CPAN::Meta::Requirements->new( { bad_version_hook => \&_bad_version_hook } # punt ); while ( my ($k,$v) = each %$element ) { next unless _is_module_name($k); if ( !defined($v) || !length($v) || $v eq 'undef' || $v eq '' ) { $v = 0; } # some weird, old META have bad yml with module => module # so check if value is like a module name and not like a version if ( _is_module_name($v) && ! version::is_lax($v) ) { $new_map->add_minimum($k => 0); $new_map->add_minimum($v => 0); } $new_map->add_string_requirement($k => $v); } return $new_map->as_string_hash; } elsif ( ref $element eq 'ARRAY' ) { my $hashref = { map { $_ => 0 } @$element }; return _version_map($hashref); # cleanup any weird stuff } elsif ( ref $element eq '' && length $element ) { return { $element => 0 } } return; } sub _prereqs_from_1 { my (undef, undef, $meta) = @_; my $prereqs = {}; for my $phase ( qw/build configure/ ) { my $key = "${phase}_requires"; $prereqs->{$phase}{requires} = _version_map($meta->{$key}) if $meta->{$key}; } for my $rel ( qw/requires recommends conflicts/ ) { $prereqs->{runtime}{$rel} = _version_map($meta->{$rel}) if $meta->{$rel}; } return $prereqs; } my $prereqs_spec = { configure => \&_prereqs_rel, build => \&_prereqs_rel, test => \&_prereqs_rel, runtime => \&_prereqs_rel, develop => \&_prereqs_rel, ':custom' => \&_prefix_custom, }; my $relation_spec = { requires => \&_version_map, recommends => \&_version_map, suggests => \&_version_map, conflicts => \&_version_map, ':custom' => \&_prefix_custom, }; sub _cleanup_prereqs { my ($prereqs, $key, $meta, $to_version) = @_; return unless $prereqs && ref $prereqs eq 'HASH'; return _convert( $prereqs, $prereqs_spec, $to_version ); } sub _prereqs_rel { my ($relation, $key, $meta, $to_version) = @_; return unless $relation && ref $relation eq 'HASH'; return _convert( $relation, $relation_spec, $to_version ); } BEGIN { my @old_prereqs = qw( requires configure_requires recommends conflicts ); for ( @old_prereqs ) { my $sub = "_get_$_"; my ($phase,$type) = split qr/_/, $_; if ( ! defined $type ) { $type = $phase; $phase = 'runtime'; } no strict 'refs'; *{$sub} = sub { _extract_prereqs($_[2]->{prereqs},$phase,$type) }; } } sub _get_build_requires { my ($data, $key, $meta) = @_; my $test_h = _extract_prereqs($_[2]->{prereqs}, qw(test requires)) || {}; my $build_h = _extract_prereqs($_[2]->{prereqs}, qw(build requires)) || {}; my $test_req = CPAN::Meta::Requirements->from_string_hash($test_h); my $build_req = CPAN::Meta::Requirements->from_string_hash($build_h); $test_req->add_requirements($build_req)->as_string_hash; } sub _extract_prereqs { my ($prereqs, $phase, $type) = @_; return unless ref $prereqs eq 'HASH'; return scalar _version_map($prereqs->{$phase}{$type}); } sub _downgrade_optional_features { my (undef, undef, $meta) = @_; return unless exists $meta->{optional_features}; my $origin = $meta->{optional_features}; my $features = {}; for my $name ( keys %$origin ) { $features->{$name} = { description => $origin->{$name}{description}, requires => _extract_prereqs($origin->{$name}{prereqs},'runtime','requires'), configure_requires => _extract_prereqs($origin->{$name}{prereqs},'runtime','configure_requires'), build_requires => _extract_prereqs($origin->{$name}{prereqs},'runtime','build_requires'), recommends => _extract_prereqs($origin->{$name}{prereqs},'runtime','recommends'), conflicts => _extract_prereqs($origin->{$name}{prereqs},'runtime','conflicts'), }; for my $k (keys %{$features->{$name}} ) { delete $features->{$name}{$k} unless defined $features->{$name}{$k}; } } return $features; } sub _upgrade_optional_features { my (undef, undef, $meta) = @_; return unless exists $meta->{optional_features}; my $origin = $meta->{optional_features}; my $features = {}; for my $name ( keys %$origin ) { $features->{$name} = { description => $origin->{$name}{description}, prereqs => _prereqs_from_1(undef, undef, $origin->{$name}), }; delete $features->{$name}{prereqs}{configure}; } return $features; } my $optional_features_2_spec = { description => \&_keep, prereqs => \&_cleanup_prereqs, ':custom' => \&_prefix_custom, }; sub _feature_2 { my ($element, $key, $meta, $to_version) = @_; return unless $element && ref $element eq 'HASH'; _convert( $element, $optional_features_2_spec, $to_version ); } sub _cleanup_optional_features_2 { my ($element, $key, $meta, $to_version) = @_; return unless $element && ref $element eq 'HASH'; my $new_data = {}; for my $k ( keys %$element ) { $new_data->{$k} = _feature_2( $element->{$k}, $k, $meta, $to_version ); } return unless keys %$new_data; return $new_data; } sub _optional_features_1_4 { my ($element) = @_; return unless $element; $element = _optional_features_as_map($element); for my $name ( keys %$element ) { for my $drop ( qw/requires_packages requires_os excluded_os/ ) { delete $element->{$name}{$drop}; } } return $element; } sub _optional_features_as_map { my ($element) = @_; return unless $element; if ( ref $element eq 'ARRAY' ) { my %map; for my $feature ( @$element ) { my (@parts) = %$feature; $map{$parts[0]} = $parts[1]; } $element = \%map; } return $element; } sub _is_urlish { defined $_[0] && $_[0] =~ m{\A[-+.a-z0-9]+:.+}i } sub _url_or_drop { my ($element) = @_; return $element if _is_urlish($element); return; } sub _url_list { my ($element) = @_; return unless $element; $element = _listify( $element ); $element = [ grep { _is_urlish($_) } @$element ]; return unless @$element; return $element; } sub _author_list { my ($element) = @_; return [ 'unknown' ] unless $element; $element = _listify( $element ); $element = [ map { defined $_ && length $_ ? $_ : 'unknown' } @$element ]; return [ 'unknown' ] unless @$element; return $element; } my $resource2_upgrade = { license => sub { return _is_urlish($_[0]) ? _listify( $_[0] ) : undef }, homepage => \&_url_or_drop, bugtracker => sub { my ($item) = @_; return unless $item; if ( $item =~ m{^mailto:(.*)$} ) { return { mailto => $1 } } elsif( _is_urlish($item) ) { return { web => $item } } else { return } }, repository => sub { return _is_urlish($_[0]) ? { url => $_[0] } : undef }, ':custom' => \&_prefix_custom, }; sub _upgrade_resources_2 { my (undef, undef, $meta, $version) = @_; return unless exists $meta->{resources}; return _convert($meta->{resources}, $resource2_upgrade); } my $bugtracker2_spec = { web => \&_url_or_drop, mailto => \&_keep, ':custom' => \&_prefix_custom, }; sub _repo_type { my ($element, $key, $meta, $to_version) = @_; return $element if defined $element; return unless exists $meta->{url}; my $repo_url = $meta->{url}; for my $type ( qw/git svn/ ) { return $type if $repo_url =~ m{\A$type}; } return; } my $repository2_spec = { web => \&_url_or_drop, url => \&_url_or_drop, type => \&_repo_type, ':custom' => \&_prefix_custom, }; my $resources2_cleanup = { license => \&_url_list, homepage => \&_url_or_drop, bugtracker => sub { ref $_[0] ? _convert( $_[0], $bugtracker2_spec ) : undef }, repository => sub { my $data = shift; ref $data ? _convert( $data, $repository2_spec ) : undef }, ':custom' => \&_prefix_custom, }; sub _cleanup_resources_2 { my ($resources, $key, $meta, $to_version) = @_; return unless $resources && ref $resources eq 'HASH'; return _convert($resources, $resources2_cleanup, $to_version); } my $resource1_spec = { license => \&_url_or_drop, homepage => \&_url_or_drop, bugtracker => \&_url_or_drop, repository => \&_url_or_drop, ':custom' => \&_keep, }; sub _resources_1_3 { my (undef, undef, $meta, $version) = @_; return unless exists $meta->{resources}; return _convert($meta->{resources}, $resource1_spec); } *_resources_1_4 = *_resources_1_3; sub _resources_1_2 { my (undef, undef, $meta) = @_; my $resources = $meta->{resources} || {}; if ( $meta->{license_url} && ! $resources->{license} ) { $resources->{license} = $meta->{license_url} if _is_urlish($meta->{license_url}); } return unless keys %$resources; return _convert($resources, $resource1_spec); } my $resource_downgrade_spec = { license => sub { return ref $_[0] ? $_[0]->[0] : $_[0] }, homepage => \&_url_or_drop, bugtracker => sub { return $_[0]->{web} }, repository => sub { return $_[0]->{url} || $_[0]->{web} }, ':custom' => \&_no_prefix_ucfirst_custom, }; sub _downgrade_resources { my (undef, undef, $meta, $version) = @_; return unless exists $meta->{resources}; return _convert($meta->{resources}, $resource_downgrade_spec); } sub _release_status { my ($element, undef, $meta) = @_; return $element if $element && $element =~ m{\A(?:stable|testing|unstable)\z}; return _release_status_from_version(undef, undef, $meta); } sub _release_status_from_version { my (undef, undef, $meta) = @_; my $version = $meta->{version} || ''; return ( $version =~ /_/ ) ? 'testing' : 'stable'; } my $provides_spec = { file => \&_keep, version => \&_keep, }; my $provides_spec_2 = { file => \&_keep, version => \&_keep, ':custom' => \&_prefix_custom, }; sub _provides { my ($element, $key, $meta, $to_version) = @_; return unless defined $element && ref $element eq 'HASH'; my $spec = $to_version == 2 ? $provides_spec_2 : $provides_spec; my $new_data = {}; for my $k ( keys %$element ) { $new_data->{$k} = _convert($element->{$k}, $spec, $to_version); $new_data->{$k}{version} = _clean_version($element->{$k}{version}) if exists $element->{$k}{version}; } return $new_data; } sub _convert { my ($data, $spec, $to_version, $is_fragment) = @_; my $new_data = {}; for my $key ( keys %$spec ) { next if $key eq ':custom' || $key eq ':drop'; next unless my $fcn = $spec->{$key}; if ( $is_fragment && $key eq 'generated_by' ) { $fcn = \&_keep; } die "spec for '$key' is not a coderef" unless ref $fcn && ref $fcn eq 'CODE'; my $new_value = $fcn->($data->{$key}, $key, $data, $to_version); $new_data->{$key} = $new_value if defined $new_value; } my $drop_list = $spec->{':drop'}; my $customizer = $spec->{':custom'} || \&_keep; for my $key ( keys %$data ) { next if $drop_list && grep { $key eq $_ } @$drop_list; next if exists $spec->{$key}; # we handled it $new_data->{ $customizer->($key) } = $data->{$key}; } return $new_data; } #--------------------------------------------------------------------------# # define converters for each conversion #--------------------------------------------------------------------------# # each converts from prior version # special ":custom" field is used for keys not recognized in spec my %up_convert = ( '2-from-1.4' => { # PRIOR MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_2, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # CHANGED TO MANDATORY 'dynamic_config' => \&_keep_or_one, # ADDED MANDATORY 'release_status' => \&_release_status_from_version, # PRIOR OPTIONAL 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_upgrade_optional_features, 'provides' => \&_provides, 'resources' => \&_upgrade_resources_2, # ADDED OPTIONAL 'description' => \&_keep, 'prereqs' => \&_prereqs_from_1, # drop these deprecated fields, but only after we convert ':drop' => [ qw( build_requires configure_requires conflicts distribution_type license_url private recommends requires ) ], # other random keys need x_ prefixing ':custom' => \&_prefix_custom, }, '1.4-from-1.3' => { # PRIOR MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_optional_features_1_4, 'provides' => \&_provides, 'recommends' => \&_version_map, 'requires' => \&_version_map, 'resources' => \&_resources_1_4, # ADDED OPTIONAL 'configure_requires' => \&_keep, # drop these deprecated fields, but only after we convert ':drop' => [ qw( license_url private )], # other random keys are OK if already valid ':custom' => \&_keep }, '1.3-from-1.2' => { # PRIOR MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_optional_features_as_map, 'provides' => \&_provides, 'recommends' => \&_version_map, 'requires' => \&_version_map, 'resources' => \&_resources_1_3, # drop these deprecated fields, but only after we convert ':drop' => [ qw( license_url private )], # other random keys are OK if already valid ':custom' => \&_keep }, '1.2-from-1.1' => { # PRIOR MANDATORY 'version' => \&_keep, # CHANGED TO MANDATORY 'license' => \&_license_1, 'name' => \&_keep, 'generated_by' => \&_generated_by, # ADDED MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'meta-spec' => \&_change_meta_spec, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'recommends' => \&_version_map, 'requires' => \&_version_map, # ADDED OPTIONAL 'keywords' => \&_keep, 'no_index' => \&_no_index_1_2, 'optional_features' => \&_optional_features_as_map, 'provides' => \&_provides, 'resources' => \&_resources_1_2, # drop these deprecated fields, but only after we convert ':drop' => [ qw( license_url private )], # other random keys are OK if already valid ':custom' => \&_keep }, '1.1-from-1.0' => { # CHANGED TO MANDATORY 'version' => \&_keep, # IMPLIED MANDATORY 'name' => \&_keep, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'recommends' => \&_version_map, 'requires' => \&_version_map, # ADDED OPTIONAL 'license_url' => \&_url_or_drop, 'private' => \&_keep, # other random keys are OK if already valid ':custom' => \&_keep }, ); my %down_convert = ( '1.4-from-2' => { # MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_downgrade_license, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # OPTIONAL 'build_requires' => \&_get_build_requires, 'configure_requires' => \&_get_configure_requires, 'conflicts' => \&_get_conflicts, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_downgrade_optional_features, 'provides' => \&_provides, 'recommends' => \&_get_recommends, 'requires' => \&_get_requires, 'resources' => \&_downgrade_resources, # drop these unsupported fields (after conversion) ':drop' => [ qw( description prereqs release_status )], # custom keys will be left unchanged ':custom' => \&_keep }, '1.3-from-1.4' => { # MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_optional_features_as_map, 'provides' => \&_provides, 'recommends' => \&_version_map, 'requires' => \&_version_map, 'resources' => \&_resources_1_3, # drop these unsupported fields, but only after we convert ':drop' => [ qw( configure_requires )], # other random keys are OK if already valid ':custom' => \&_keep, }, '1.2-from-1.3' => { # MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_1_2, 'optional_features' => \&_optional_features_as_map, 'provides' => \&_provides, 'recommends' => \&_version_map, 'requires' => \&_version_map, 'resources' => \&_resources_1_3, # other random keys are OK if already valid ':custom' => \&_keep, }, '1.1-from-1.2' => { # MANDATORY 'version' => \&_keep, # IMPLIED MANDATORY 'name' => \&_keep, 'meta-spec' => \&_change_meta_spec, # OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'private' => \&_keep, 'recommends' => \&_version_map, 'requires' => \&_version_map, # drop unsupported fields ':drop' => [ qw( abstract author provides no_index keywords resources )], # other random keys are OK if already valid ':custom' => \&_keep, }, '1.0-from-1.1' => { # IMPLIED MANDATORY 'name' => \&_keep, 'meta-spec' => \&_change_meta_spec, 'version' => \&_keep, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'recommends' => \&_version_map, 'requires' => \&_version_map, # other random keys are OK if already valid ':custom' => \&_keep, }, ); my %cleanup = ( '2' => { # PRIOR MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_2, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # CHANGED TO MANDATORY 'dynamic_config' => \&_keep_or_one, # ADDED MANDATORY 'release_status' => \&_release_status, # PRIOR OPTIONAL 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_cleanup_optional_features_2, 'provides' => \&_provides, 'resources' => \&_cleanup_resources_2, # ADDED OPTIONAL 'description' => \&_keep, 'prereqs' => \&_cleanup_prereqs, # drop these deprecated fields, but only after we convert ':drop' => [ qw( build_requires configure_requires conflicts distribution_type license_url private recommends requires ) ], # other random keys need x_ prefixing ':custom' => \&_prefix_custom, }, '1.4' => { # PRIOR MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_optional_features_1_4, 'provides' => \&_provides, 'recommends' => \&_version_map, 'requires' => \&_version_map, 'resources' => \&_resources_1_4, # ADDED OPTIONAL 'configure_requires' => \&_keep, # other random keys are OK if already valid ':custom' => \&_keep }, '1.3' => { # PRIOR MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'meta-spec' => \&_change_meta_spec, 'name' => \&_keep, 'version' => \&_keep, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'keywords' => \&_keep, 'no_index' => \&_no_index_directory, 'optional_features' => \&_optional_features_as_map, 'provides' => \&_provides, 'recommends' => \&_version_map, 'requires' => \&_version_map, 'resources' => \&_resources_1_3, # other random keys are OK if already valid ':custom' => \&_keep }, '1.2' => { # PRIOR MANDATORY 'version' => \&_keep, # CHANGED TO MANDATORY 'license' => \&_license_1, 'name' => \&_keep, 'generated_by' => \&_generated_by, # ADDED MANDATORY 'abstract' => \&_keep_or_unknown, 'author' => \&_author_list, 'meta-spec' => \&_change_meta_spec, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'recommends' => \&_version_map, 'requires' => \&_version_map, # ADDED OPTIONAL 'keywords' => \&_keep, 'no_index' => \&_no_index_1_2, 'optional_features' => \&_optional_features_as_map, 'provides' => \&_provides, 'resources' => \&_resources_1_2, # other random keys are OK if already valid ':custom' => \&_keep }, '1.1' => { # CHANGED TO MANDATORY 'version' => \&_keep, # IMPLIED MANDATORY 'name' => \&_keep, 'meta-spec' => \&_change_meta_spec, # PRIOR OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'recommends' => \&_version_map, 'requires' => \&_version_map, # ADDED OPTIONAL 'license_url' => \&_url_or_drop, 'private' => \&_keep, # other random keys are OK if already valid ':custom' => \&_keep }, '1.0' => { # IMPLIED MANDATORY 'name' => \&_keep, 'meta-spec' => \&_change_meta_spec, 'version' => \&_keep, # IMPLIED OPTIONAL 'build_requires' => \&_version_map, 'conflicts' => \&_version_map, 'distribution_type' => \&_keep, 'dynamic_config' => \&_keep_or_one, 'generated_by' => \&_generated_by, 'license' => \&_license_1, 'recommends' => \&_version_map, 'requires' => \&_version_map, # other random keys are OK if already valid ':custom' => \&_keep, }, ); # for a given field in a spec version, what fields will it feed # into in the *latest* spec (i.e. v2); meta-spec omitted because # we always expect a meta-spec to be generated my %fragments_generate = ( '2' => { 'abstract' => 'abstract', 'author' => 'author', 'generated_by' => 'generated_by', 'license' => 'license', 'name' => 'name', 'version' => 'version', 'dynamic_config' => 'dynamic_config', 'release_status' => 'release_status', 'keywords' => 'keywords', 'no_index' => 'no_index', 'optional_features' => 'optional_features', 'provides' => 'provides', 'resources' => 'resources', 'description' => 'description', 'prereqs' => 'prereqs', }, '1.4' => { 'abstract' => 'abstract', 'author' => 'author', 'generated_by' => 'generated_by', 'license' => 'license', 'name' => 'name', 'version' => 'version', 'build_requires' => 'prereqs', 'conflicts' => 'prereqs', 'distribution_type' => 'distribution_type', 'dynamic_config' => 'dynamic_config', 'keywords' => 'keywords', 'no_index' => 'no_index', 'optional_features' => 'optional_features', 'provides' => 'provides', 'recommends' => 'prereqs', 'requires' => 'prereqs', 'resources' => 'resources', 'configure_requires' => 'prereqs', }, ); # this is not quite true but will work well enough # as 1.4 is a superset of earlier ones $fragments_generate{$_} = $fragments_generate{'1.4'} for qw/1.3 1.2 1.1 1.0/; #--------------------------------------------------------------------------# # Code #--------------------------------------------------------------------------# #pod =method new #pod #pod my $cmc = CPAN::Meta::Converter->new( $struct ); #pod #pod The constructor should be passed a valid metadata structure but invalid #pod structures are accepted. If no meta-spec version is provided, version 1.0 will #pod be assumed. #pod #pod Optionally, you can provide a C argument after C<$struct>: #pod #pod my $cmc = CPAN::Meta::Converter->new( $struct, default_version => "1.4" ); #pod #pod This is only needed when converting a metadata fragment that does not include a #pod C field. #pod #pod =cut sub new { my ($class,$data,%args) = @_; # create an attributes hash my $self = { 'data' => $data, 'spec' => _extract_spec_version($data, $args{default_version}), }; # create the object return bless $self, $class; } sub _extract_spec_version { my ($data, $default) = @_; my $spec = $data->{'meta-spec'}; # is meta-spec there and valid? return( $default || "1.0" ) unless defined $spec && ref $spec eq 'HASH'; # before meta-spec? # does the version key look like a valid version? my $v = $spec->{version}; if ( defined $v && $v =~ /^\d+(?:\.\d+)?$/ ) { return $v if defined $v && grep { $v eq $_ } keys %known_specs; # known spec return $v+0 if defined $v && grep { $v == $_ } keys %known_specs; # 2.0 => 2 } # otherwise, use heuristics: look for 1.x vs 2.0 fields return "2" if exists $data->{prereqs}; return "1.4" if exists $data->{configure_requires}; return( $default || "1.2" ); # when meta-spec was first defined } #pod =method convert #pod #pod my $new_struct = $cmc->convert( version => "2" ); #pod #pod Returns a new hash reference with the metadata converted to a different form. #pod C will die if any conversion/standardization still results in an #pod invalid structure. #pod #pod Valid parameters include: #pod #pod =over #pod #pod =item * #pod #pod C -- Indicates the desired specification version (e.g. "1.0", "1.1" ... "1.4", "2"). #pod Defaults to the latest version of the CPAN Meta Spec. #pod #pod =back #pod #pod Conversion proceeds through each version in turn. For example, a version 1.2 #pod structure might be converted to 1.3 then 1.4 then finally to version 2. The #pod conversion process attempts to clean-up simple errors and standardize data. #pod For example, if C is given as a scalar, it will converted to an array #pod reference containing the item. (Converting a structure to its own version will #pod also clean-up and standardize.) #pod #pod When data are cleaned and standardized, missing or invalid fields will be #pod replaced with sensible defaults when possible. This may be lossy or imprecise. #pod For example, some badly structured META.yml files on CPAN have prerequisite #pod modules listed as both keys and values: #pod #pod requires => { 'Foo::Bar' => 'Bam::Baz' } #pod #pod These would be split and each converted to a prerequisite with a minimum #pod version of zero. #pod #pod When some mandatory fields are missing or invalid, the conversion will attempt #pod to provide a sensible default or will fill them with a value of 'unknown'. For #pod example a missing or unrecognized C field will result in a C #pod field of 'unknown'. Fields that may get an 'unknown' include: #pod #pod =for :list #pod * abstract #pod * author #pod * license #pod #pod =cut sub convert { my ($self, %args) = @_; my $args = { %args }; my $new_version = $args->{version} || $HIGHEST; my $is_fragment = $args->{is_fragment}; my ($old_version) = $self->{spec}; my $converted = _dclone($self->{data}); if ( $old_version == $new_version ) { $converted = _convert( $converted, $cleanup{$old_version}, $old_version, $is_fragment ); unless ( $args->{is_fragment} ) { my $cmv = CPAN::Meta::Validator->new( $converted ); unless ( $cmv->is_valid ) { my $errs = join("\n", $cmv->errors); die "Failed to clean-up $old_version metadata. Errors:\n$errs\n"; } } return $converted; } elsif ( $old_version > $new_version ) { my @vers = sort { $b <=> $a } keys %known_specs; for my $i ( 0 .. $#vers-1 ) { next if $vers[$i] > $old_version; last if $vers[$i+1] < $new_version; my $spec_string = "$vers[$i+1]-from-$vers[$i]"; $converted = _convert( $converted, $down_convert{$spec_string}, $vers[$i+1], $is_fragment ); unless ( $args->{is_fragment} ) { my $cmv = CPAN::Meta::Validator->new( $converted ); unless ( $cmv->is_valid ) { my $errs = join("\n", $cmv->errors); die "Failed to downconvert metadata to $vers[$i+1]. Errors:\n$errs\n"; } } } return $converted; } else { my @vers = sort { $a <=> $b } keys %known_specs; for my $i ( 0 .. $#vers-1 ) { next if $vers[$i] < $old_version; last if $vers[$i+1] > $new_version; my $spec_string = "$vers[$i+1]-from-$vers[$i]"; $converted = _convert( $converted, $up_convert{$spec_string}, $vers[$i+1], $is_fragment ); unless ( $args->{is_fragment} ) { my $cmv = CPAN::Meta::Validator->new( $converted ); unless ( $cmv->is_valid ) { my $errs = join("\n", $cmv->errors); die "Failed to upconvert metadata to $vers[$i+1]. Errors:\n$errs\n"; } } } return $converted; } } #pod =method upgrade_fragment #pod #pod my $new_struct = $cmc->upgrade_fragment; #pod #pod Returns a new hash reference with the metadata converted to the latest version #pod of the CPAN Meta Spec. No validation is done on the result -- you must #pod validate after merging fragments into a complete metadata document. #pod #pod =cut sub upgrade_fragment { my ($self) = @_; my ($old_version) = $self->{spec}; my %expected = map {; $_ => 1 } grep { defined } map { $fragments_generate{$old_version}{$_} } keys %{ $self->{data} }; my $converted = $self->convert( version => $HIGHEST, is_fragment => 1 ); for my $key ( keys %$converted ) { next if $key =~ /^x_/i || $key eq 'meta-spec'; delete $converted->{$key} unless $expected{$key}; } return $converted; } 1; # ABSTRACT: Convert CPAN distribution metadata structures =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Converter - Convert CPAN distribution metadata structures =head1 VERSION version 2.143240 =head1 SYNOPSIS my $struct = decode_json_file('META.json'); my $cmc = CPAN::Meta::Converter->new( $struct ); my $new_struct = $cmc->convert( version => "2" ); =head1 DESCRIPTION This module converts CPAN Meta structures from one form to another. The primary use is to convert older structures to the most modern version of the specification, but other transformations may be implemented in the future as needed. (E.g. stripping all custom fields or stripping all optional fields.) =head1 METHODS =head2 new my $cmc = CPAN::Meta::Converter->new( $struct ); The constructor should be passed a valid metadata structure but invalid structures are accepted. If no meta-spec version is provided, version 1.0 will be assumed. Optionally, you can provide a C argument after C<$struct>: my $cmc = CPAN::Meta::Converter->new( $struct, default_version => "1.4" ); This is only needed when converting a metadata fragment that does not include a C field. =head2 convert my $new_struct = $cmc->convert( version => "2" ); Returns a new hash reference with the metadata converted to a different form. C will die if any conversion/standardization still results in an invalid structure. Valid parameters include: =over =item * C -- Indicates the desired specification version (e.g. "1.0", "1.1" ... "1.4", "2"). Defaults to the latest version of the CPAN Meta Spec. =back Conversion proceeds through each version in turn. For example, a version 1.2 structure might be converted to 1.3 then 1.4 then finally to version 2. The conversion process attempts to clean-up simple errors and standardize data. For example, if C is given as a scalar, it will converted to an array reference containing the item. (Converting a structure to its own version will also clean-up and standardize.) When data are cleaned and standardized, missing or invalid fields will be replaced with sensible defaults when possible. This may be lossy or imprecise. For example, some badly structured META.yml files on CPAN have prerequisite modules listed as both keys and values: requires => { 'Foo::Bar' => 'Bam::Baz' } These would be split and each converted to a prerequisite with a minimum version of zero. When some mandatory fields are missing or invalid, the conversion will attempt to provide a sensible default or will fill them with a value of 'unknown'. For example a missing or unrecognized C field will result in a C field of 'unknown'. Fields that may get an 'unknown' include: =over 4 =item * abstract =item * author =item * license =back =head2 upgrade_fragment my $new_struct = $cmc->upgrade_fragment; Returns a new hash reference with the metadata converted to the latest version of the CPAN Meta Spec. No validation is done on the result -- you must validate after merging fragments into a complete metadata document. =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at 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 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 __END__ # vim: ts=2 sts=2 sw=2 et: PK!< $l:M:M%perl5/CPAN/Meta/Requirements/Range.pmnuÏÃ6Ç$use v5.10; use strict; use warnings; package CPAN::Meta::Requirements::Range; # ABSTRACT: a set of version requirements for a CPAN dist our $VERSION = '2.143'; use Carp (); #pod =head1 SYNOPSIS #pod #pod use CPAN::Meta::Requirements::Range; #pod #pod my $range = CPAN::Meta::Requirements::Range->with_minimum(1); #pod #pod $range = $range->with_maximum('v2.2'); #pod #pod my $stringified = $range->as_string; #pod #pod =head1 DESCRIPTION #pod #pod A CPAN::Meta::Requirements::Range object models a set of version constraints like #pod those specified in the F or F files in CPAN distributions, #pod and as defined by L; #pod It can be built up by adding more and more constraints, and it will reduce them #pod to the simplest representation. #pod #pod Logically impossible constraints will be identified immediately by thrown #pod exceptions. #pod #pod =cut use Carp (); package CPAN::Meta::Requirements::Range::_Base; # To help ExtUtils::MakeMaker bootstrap CPAN::Meta::Requirements on perls # before 5.10, we fall back to the EUMM bundled compatibility version module if # that's the only thing available. This shouldn't ever happen in a normal CPAN # install of CPAN::Meta::Requirements, as version.pm will be picked up from # prereqs and be available at runtime. BEGIN { eval "use version ()"; ## no critic if ( my $err = $@ ) { eval "use ExtUtils::MakeMaker::version" or die $err; ## no critic } } # from version::vpp sub _find_magic_vstring { my $value = shift; my $tvalue = ''; require B; my $sv = B::svref_2object(\$value); my $magic = ref($sv) eq 'B::PVMG' ? $sv->MAGIC : undef; while ( $magic ) { if ( $magic->TYPE eq 'V' ) { $tvalue = $magic->PTR; $tvalue =~ s/^v?(.+)$/v$1/; last; } else { $magic = $magic->MOREMAGIC; } } return $tvalue; } # Perl 5.10.0 didn't have "is_qv" in version.pm *_is_qv = version->can('is_qv') ? sub { $_[0]->is_qv } : sub { exists $_[0]->{qv} }; # construct once, reuse many times my $V0 = version->new(0); # safe if given an unblessed reference sub _isa_version { UNIVERSAL::isa( $_[0], 'UNIVERSAL' ) && $_[0]->isa('version') } sub _version_object { my ($self, $version, $module, $bad_version_hook) = @_; my ($vobj, $err); if (not defined $version or (!ref($version) && $version eq '0')) { return $V0; } elsif ( ref($version) eq 'version' || ( ref($version) && _isa_version($version) ) ) { $vobj = $version; } else { # hack around version::vpp not handling <3 character vstring literals if ( $INC{'version/vpp.pm'} || $INC{'ExtUtils/MakeMaker/version/vpp.pm'} ) { my $magic = _find_magic_vstring( $version ); $version = $magic if length $magic; } # pad to 3 characters if before 5.8.1 and appears to be a v-string if ( $] < 5.008001 && $version !~ /\A[0-9]/ && substr($version,0,1) ne 'v' && length($version) < 3 ) { $version .= "\0" x (3 - length($version)); } eval { local $SIG{__WARN__} = sub { die "Invalid version: $_[0]" }; # avoid specific segfault on some older version.pm versions die "Invalid version: $version" if $version eq 'version'; $vobj = version->new($version); }; if ( my $err = $@ ) { $vobj = eval { $bad_version_hook->($version, $module) } if ref $bad_version_hook eq 'CODE'; unless (eval { $vobj->isa("version") }) { $err =~ s{ at .* line \d+.*$}{}; die "Can't convert '$version': $err"; } } } # ensure no leading '.' if ( $vobj =~ m{\A\.} ) { $vobj = version->new("0$vobj"); } # ensure normal v-string form if ( _is_qv($vobj) ) { $vobj = version->new($vobj->normal); } return $vobj; } #pod =method with_string_requirement #pod #pod $req->with_string_requirement('>= 1.208, <= 2.206'); #pod $req->with_string_requirement(v1.208); #pod #pod This method parses the passed in string and adds the appropriate requirement. #pod A version can be a Perl "v-string". It understands version ranges as described #pod in the L. For example: #pod #pod =over 4 #pod #pod =item 1.3 #pod #pod =item >= 1.3 #pod #pod =item <= 1.3 #pod #pod =item == 1.3 #pod #pod =item != 1.3 #pod #pod =item > 1.3 #pod #pod =item < 1.3 #pod #pod =item >= 1.3, != 1.5, <= 2.0 #pod #pod A version number without an operator is equivalent to specifying a minimum #pod (C=>). Extra whitespace is allowed. #pod #pod =back #pod #pod =cut my %methods_for_op = ( '==' => [ qw(with_exact_version) ], '!=' => [ qw(with_exclusion) ], '>=' => [ qw(with_minimum) ], '<=' => [ qw(with_maximum) ], '>' => [ qw(with_minimum with_exclusion) ], '<' => [ qw(with_maximum with_exclusion) ], ); sub with_string_requirement { my ($self, $req, $module, $bad_version_hook) = @_; $module //= 'module'; unless ( defined $req && length $req ) { $req = 0; Carp::carp("Undefined requirement for $module treated as '0'"); } my $magic = _find_magic_vstring( $req ); if (length $magic) { return $self->with_minimum($magic, $module, $bad_version_hook); } my @parts = split qr{\s*,\s*}, $req; for my $part (@parts) { my ($op, $ver) = $part =~ m{\A\s*(==|>=|>|<=|<|!=)\s*(.*)\z}; if (! defined $op) { $self = $self->with_minimum($part, $module, $bad_version_hook); } else { Carp::croak("illegal requirement string: $req") unless my $methods = $methods_for_op{ $op }; $self = $self->$_($ver, $module, $bad_version_hook) for @$methods; } } return $self; } #pod =method with_range #pod #pod $range->with_range($other_range) #pod #pod This creates a new range object that is a merge two others. #pod #pod =cut sub with_range { my ($self, $other, $module, $bad_version_hook) = @_; for my $modifier($other->_as_modifiers) { my ($method, $arg) = @$modifier; $self = $self->$method($arg, $module, $bad_version_hook); } return $self; } package CPAN::Meta::Requirements::Range; our @ISA = 'CPAN::Meta::Requirements::Range::_Base'; sub _clone { return (bless { } => $_[0]) unless ref $_[0]; my ($s) = @_; my %guts = ( (exists $s->{minimum} ? (minimum => version->new($s->{minimum})) : ()), (exists $s->{maximum} ? (maximum => version->new($s->{maximum})) : ()), (exists $s->{exclusions} ? (exclusions => [ map { version->new($_) } @{ $s->{exclusions} } ]) : ()), ); bless \%guts => ref($s); } #pod =method with_exact_version #pod #pod $range->with_exact_version( $version ); #pod #pod This sets the version required to I the given #pod version. No other version would be considered acceptable. #pod #pod This method returns the version range object. #pod #pod =cut sub with_exact_version { my ($self, $version, $module, $bad_version_hook) = @_; $module //= 'module'; $self = $self->_clone; $version = $self->_version_object($version, $module, $bad_version_hook); unless ($self->accepts($version)) { $self->_reject_requirements( $module, "exact specification $version outside of range " . $self->as_string ); } return CPAN::Meta::Requirements::Range::_Exact->_new($version); } sub _simplify { my ($self, $module) = @_; if (defined $self->{minimum} and defined $self->{maximum}) { if ($self->{minimum} == $self->{maximum}) { if (grep { $_ == $self->{minimum} } @{ $self->{exclusions} || [] }) { $self->_reject_requirements( $module, "minimum and maximum are both $self->{minimum}, which is excluded", ); } return CPAN::Meta::Requirements::Range::_Exact->_new($self->{minimum}); } if ($self->{minimum} > $self->{maximum}) { $self->_reject_requirements( $module, "minimum $self->{minimum} exceeds maximum $self->{maximum}", ); } } # eliminate irrelevant exclusions if ($self->{exclusions}) { my %seen; @{ $self->{exclusions} } = grep { (! defined $self->{minimum} or $_ >= $self->{minimum}) and (! defined $self->{maximum} or $_ <= $self->{maximum}) and ! $seen{$_}++ } @{ $self->{exclusions} }; } return $self; } #pod =method with_minimum #pod #pod $range->with_minimum( $version ); #pod #pod This adds a new minimum version requirement. If the new requirement is #pod redundant to the existing specification, this has no effect. #pod #pod Minimum requirements are inclusive. C<$version> is required, along with any #pod greater version number. #pod #pod This method returns the version range object. #pod #pod =cut sub with_minimum { my ($self, $minimum, $module, $bad_version_hook) = @_; $module //= 'module'; $self = $self->_clone; $minimum = $self->_version_object( $minimum, $module, $bad_version_hook ); if (defined (my $old_min = $self->{minimum})) { $self->{minimum} = (sort { $b cmp $a } ($minimum, $old_min))[0]; } else { $self->{minimum} = $minimum; } return $self->_simplify($module); } #pod =method with_maximum #pod #pod $range->with_maximum( $version ); #pod #pod This adds a new maximum version requirement. If the new requirement is #pod redundant to the existing specification, this has no effect. #pod #pod Maximum requirements are inclusive. No version strictly greater than the given #pod version is allowed. #pod #pod This method returns the version range object. #pod #pod =cut sub with_maximum { my ($self, $maximum, $module, $bad_version_hook) = @_; $module //= 'module'; $self = $self->_clone; $maximum = $self->_version_object( $maximum, $module, $bad_version_hook ); if (defined (my $old_max = $self->{maximum})) { $self->{maximum} = (sort { $a cmp $b } ($maximum, $old_max))[0]; } else { $self->{maximum} = $maximum; } return $self->_simplify($module); } #pod =method with_exclusion #pod #pod $range->with_exclusion( $version ); #pod #pod This adds a new excluded version. For example, you might use these three #pod method calls: #pod #pod $range->with_minimum( '1.00' ); #pod $range->with_maximum( '1.82' ); #pod #pod $range->with_exclusion( '1.75' ); #pod #pod Any version between 1.00 and 1.82 inclusive would be acceptable, except for #pod 1.75. #pod #pod This method returns the requirements object. #pod #pod =cut sub with_exclusion { my ($self, $exclusion, $module, $bad_version_hook) = @_; $module //= 'module'; $self = $self->_clone; $exclusion = $self->_version_object( $exclusion, $module, $bad_version_hook ); push @{ $self->{exclusions} ||= [] }, $exclusion; return $self->_simplify($module); } sub _as_modifiers { my ($self) = @_; my @mods; push @mods, [ with_minimum => $self->{minimum} ] if exists $self->{minimum}; push @mods, [ with_maximum => $self->{maximum} ] if exists $self->{maximum}; push @mods, map {; [ with_exclusion => $_ ] } @{$self->{exclusions} || []}; return @mods; } #pod =method as_struct #pod #pod $range->as_struct( $module ); #pod #pod This returns a data structure containing the version requirements. This should #pod not be used for version checks (see L instead). #pod #pod =cut sub as_struct { my ($self) = @_; return 0 if ! keys %$self; my @exclusions = @{ $self->{exclusions} || [] }; my @parts; for my $tuple ( [ qw( >= > minimum ) ], [ qw( <= < maximum ) ], ) { my ($op, $e_op, $k) = @$tuple; if (exists $self->{$k}) { my @new_exclusions = grep { $_ != $self->{ $k } } @exclusions; if (@new_exclusions == @exclusions) { push @parts, [ $op, "$self->{ $k }" ]; } else { push @parts, [ $e_op, "$self->{ $k }" ]; @exclusions = @new_exclusions; } } } push @parts, map {; [ "!=", "$_" ] } @exclusions; return \@parts; } #pod =method as_string #pod #pod $range->as_string; #pod #pod This returns a string containing the version requirements in the format #pod described in L. This should only be used for informational #pod purposes such as error messages and should not be interpreted or used for #pod comparison (see L instead). #pod #pod =cut sub as_string { my ($self) = @_; my @parts = @{ $self->as_struct }; return $parts[0][1] if @parts == 1 and $parts[0][0] eq '>='; return join q{, }, map {; join q{ }, @$_ } @parts; } sub _reject_requirements { my ($self, $module, $error) = @_; Carp::croak("illegal requirements for $module: $error") } #pod =method accepts #pod #pod my $bool = $range->accepts($version); #pod #pod Given a version, this method returns true if the version specification #pod accepts the provided version. In other words, given: #pod #pod '>= 1.00, < 2.00' #pod #pod We will accept 1.00 and 1.75 but not 0.50 or 2.00. #pod #pod =cut sub accepts { my ($self, $version) = @_; return if defined $self->{minimum} and $version < $self->{minimum}; return if defined $self->{maximum} and $version > $self->{maximum}; return if defined $self->{exclusions} and grep { $version == $_ } @{ $self->{exclusions} }; return 1; } #pod =method is_simple #pod #pod This method returns true if and only if the range is an inclusive minimum #pod -- that is, if their string expression is just the version number. #pod #pod =cut sub is_simple { my ($self) = @_; # XXX: This is a complete hack, but also entirely correct. return if $self->as_string =~ /\s/; return 1; } package CPAN::Meta::Requirements::Range::_Exact; our @ISA = 'CPAN::Meta::Requirements::Range::_Base'; our $VERSION = '2.141'; BEGIN { eval "use version ()"; ## no critic if ( my $err = $@ ) { eval "use ExtUtils::MakeMaker::version" or die $err; ## no critic } } sub _new { bless { version => $_[1] } => $_[0] } sub accepts { return $_[0]{version} == $_[1] } sub _reject_requirements { my ($self, $module, $error) = @_; Carp::croak("illegal requirements for $module: $error") } sub _clone { (ref $_[0])->_new( version->new( $_[0]{version} ) ) } sub with_exact_version { my ($self, $version, $module, $bad_version_hook) = @_; $module //= 'module'; $version = $self->_version_object($version, $module, $bad_version_hook); return $self->_clone if $self->accepts($version); $self->_reject_requirements( $module, "can't be exactly $version when exact requirement is already $self->{version}", ); } sub with_minimum { my ($self, $minimum, $module, $bad_version_hook) = @_; $module //= 'module'; $minimum = $self->_version_object( $minimum, $module, $bad_version_hook ); return $self->_clone if $self->{version} >= $minimum; $self->_reject_requirements( $module, "minimum $minimum exceeds exact specification $self->{version}", ); } sub with_maximum { my ($self, $maximum, $module, $bad_version_hook) = @_; $module //= 'module'; $maximum = $self->_version_object( $maximum, $module, $bad_version_hook ); return $self->_clone if $self->{version} <= $maximum; $self->_reject_requirements( $module, "maximum $maximum below exact specification $self->{version}", ); } sub with_exclusion { my ($self, $exclusion, $module, $bad_version_hook) = @_; $module //= 'module'; $exclusion = $self->_version_object( $exclusion, $module, $bad_version_hook ); return $self->_clone unless $exclusion == $self->{version}; $self->_reject_requirements( $module, "tried to exclude $exclusion, which is already exactly specified", ); } sub as_string { return "== $_[0]{version}" } sub as_struct { return [ [ '==', "$_[0]{version}" ] ] } sub _as_modifiers { return [ with_exact_version => $_[0]{version} ] } 1; # vim: ts=2 sts=2 sw=2 et: __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Requirements::Range - a set of version requirements for a CPAN dist =head1 VERSION version 2.143 =head1 SYNOPSIS use CPAN::Meta::Requirements::Range; my $range = CPAN::Meta::Requirements::Range->with_minimum(1); $range = $range->with_maximum('v2.2'); my $stringified = $range->as_string; =head1 DESCRIPTION A CPAN::Meta::Requirements::Range object models a set of version constraints like those specified in the F or F files in CPAN distributions, and as defined by L; It can be built up by adding more and more constraints, and it will reduce them to the simplest representation. Logically impossible constraints will be identified immediately by thrown exceptions. =head1 METHODS =head2 with_string_requirement $req->with_string_requirement('>= 1.208, <= 2.206'); $req->with_string_requirement(v1.208); This method parses the passed in string and adds the appropriate requirement. A version can be a Perl "v-string". It understands version ranges as described in the L. For example: =over 4 =item 1.3 =item >= 1.3 =item <= 1.3 =item == 1.3 =item != 1.3 =item > 1.3 =item < 1.3 =item >= 1.3, != 1.5, <= 2.0 A version number without an operator is equivalent to specifying a minimum (C=>). Extra whitespace is allowed. =back =head2 with_range $range->with_range($other_range) This creates a new range object that is a merge two others. =head2 with_exact_version $range->with_exact_version( $version ); This sets the version required to I the given version. No other version would be considered acceptable. This method returns the version range object. =head2 with_minimum $range->with_minimum( $version ); This adds a new minimum version requirement. If the new requirement is redundant to the existing specification, this has no effect. Minimum requirements are inclusive. C<$version> is required, along with any greater version number. This method returns the version range object. =head2 with_maximum $range->with_maximum( $version ); This adds a new maximum version requirement. If the new requirement is redundant to the existing specification, this has no effect. Maximum requirements are inclusive. No version strictly greater than the given version is allowed. This method returns the version range object. =head2 with_exclusion $range->with_exclusion( $version ); This adds a new excluded version. For example, you might use these three method calls: $range->with_minimum( '1.00' ); $range->with_maximum( '1.82' ); $range->with_exclusion( '1.75' ); Any version between 1.00 and 1.82 inclusive would be acceptable, except for 1.75. This method returns the requirements object. =head2 as_struct $range->as_struct( $module ); This returns a data structure containing the version requirements. This should not be used for version checks (see L instead). =head2 as_string $range->as_string; This returns a string containing the version requirements in the format described in L. This should only be used for informational purposes such as error messages and should not be interpreted or used for comparison (see L instead). =head2 accepts my $bool = $range->accepts($version); Given a version, this method returns true if the version specification accepts the provided version. In other words, given: '>= 1.00, < 2.00' We will accept 1.00 and 1.75 but not 0.50 or 2.00. =head2 is_simple This method returns true if and only if the range is an inclusive minimum -- that is, if their string expression is just the version number. =head1 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!¶ÚÖh}.}.perl5/CPAN/Meta/Prereqs.pmnuÏÃ6Ç$use 5.006; use strict; use warnings; package CPAN::Meta::Prereqs; # VERSION $CPAN::Meta::Prereqs::VERSION = '2.143240'; #pod =head1 DESCRIPTION #pod #pod A CPAN::Meta::Prereqs object represents the prerequisites for a CPAN #pod distribution or one of its optional features. Each set of prereqs is #pod organized by phase and type, as described in L. #pod #pod =cut use Carp qw(confess); use Scalar::Util qw(blessed); use CPAN::Meta::Requirements 2.121; #pod =method new #pod #pod my $prereq = CPAN::Meta::Prereqs->new( \%prereq_spec ); #pod #pod This method returns a new set of Prereqs. The input should look like the #pod contents of the C field described in L, meaning #pod something more or less like this: #pod #pod my $prereq = CPAN::Meta::Prereqs->new({ #pod runtime => { #pod requires => { #pod 'Some::Module' => '1.234', #pod ..., #pod }, #pod ..., #pod }, #pod ..., #pod }); #pod #pod You can also construct an empty set of prereqs with: #pod #pod my $prereqs = CPAN::Meta::Prereqs->new; #pod #pod This empty set of prereqs is useful for accumulating new prereqs before finally #pod dumping the whole set into a structure or string. #pod #pod =cut sub __legal_phases { qw(configure build test runtime develop) } sub __legal_types { qw(requires recommends suggests conflicts) } # expect a prereq spec from META.json -- rjbs, 2010-04-11 sub new { my ($class, $prereq_spec) = @_; $prereq_spec ||= {}; my %is_legal_phase = map {; $_ => 1 } $class->__legal_phases; my %is_legal_type = map {; $_ => 1 } $class->__legal_types; my %guts; PHASE: for my $phase (keys %$prereq_spec) { next PHASE unless $phase =~ /\Ax_/i or $is_legal_phase{$phase}; my $phase_spec = $prereq_spec->{ $phase }; next PHASE unless keys %$phase_spec; TYPE: for my $type (keys %$phase_spec) { next TYPE unless $type =~ /\Ax_/i or $is_legal_type{$type}; my $spec = $phase_spec->{ $type }; next TYPE unless keys %$spec; $guts{prereqs}{$phase}{$type} = CPAN::Meta::Requirements->from_string_hash( $spec ); } } return bless \%guts => $class; } #pod =method requirements_for #pod #pod my $requirements = $prereqs->requirements_for( $phase, $type ); #pod #pod This method returns a L object for the given #pod phase/type combination. If no prerequisites are registered for that #pod combination, a new CPAN::Meta::Requirements object will be returned, and it may #pod be added to as needed. #pod #pod If C<$phase> or C<$type> are undefined or otherwise invalid, an exception will #pod be raised. #pod #pod =cut sub requirements_for { my ($self, $phase, $type) = @_; confess "requirements_for called without phase" unless defined $phase; confess "requirements_for called without type" unless defined $type; unless ($phase =~ /\Ax_/i or grep { $phase eq $_ } $self->__legal_phases) { confess "requested requirements for unknown phase: $phase"; } unless ($type =~ /\Ax_/i or grep { $type eq $_ } $self->__legal_types) { confess "requested requirements for unknown type: $type"; } my $req = ($self->{prereqs}{$phase}{$type} ||= CPAN::Meta::Requirements->new); $req->finalize if $self->is_finalized; return $req; } #pod =method with_merged_prereqs #pod #pod my $new_prereqs = $prereqs->with_merged_prereqs( $other_prereqs ); #pod #pod my $new_prereqs = $prereqs->with_merged_prereqs( \@other_prereqs ); #pod #pod This method returns a new CPAN::Meta::Prereqs objects in which all the #pod other prerequisites given are merged into the current set. This is primarily #pod provided for combining a distribution's core prereqs with the prereqs of one of #pod its optional features. #pod #pod The new prereqs object has no ties to the originals, and altering it further #pod will not alter them. #pod #pod =cut sub with_merged_prereqs { my ($self, $other) = @_; my @other = blessed($other) ? $other : @$other; my @prereq_objs = ($self, @other); my %new_arg; for my $phase ($self->__legal_phases) { for my $type ($self->__legal_types) { my $req = CPAN::Meta::Requirements->new; for my $prereq (@prereq_objs) { my $this_req = $prereq->requirements_for($phase, $type); next unless $this_req->required_modules; $req->add_requirements($this_req); } next unless $req->required_modules; $new_arg{ $phase }{ $type } = $req->as_string_hash; } } return (ref $self)->new(\%new_arg); } #pod =method merged_requirements #pod #pod my $new_reqs = $prereqs->merged_requirements( \@phases, \@types ); #pod my $new_reqs = $prereqs->merged_requirements( \@phases ); #pod my $new_reqs = $preerqs->merged_requirements(); #pod #pod This method joins together all requirements across a number of phases #pod and types into a new L object. If arguments #pod are omitted, it defaults to "runtime", "build" and "test" for phases #pod and "requires" and "recommends" for types. #pod #pod =cut sub merged_requirements { my ($self, $phases, $types) = @_; $phases = [qw/runtime build test/] unless defined $phases; $types = [qw/requires recommends/] unless defined $types; confess "merged_requirements phases argument must be an arrayref" unless ref $phases eq 'ARRAY'; confess "merged_requirements types argument must be an arrayref" unless ref $types eq 'ARRAY'; my $req = CPAN::Meta::Requirements->new; for my $phase ( @$phases ) { unless ($phase =~ /\Ax_/i or grep { $phase eq $_ } $self->__legal_phases) { confess "requested requirements for unknown phase: $phase"; } for my $type ( @$types ) { unless ($type =~ /\Ax_/i or grep { $type eq $_ } $self->__legal_types) { confess "requested requirements for unknown type: $type"; } $req->add_requirements( $self->requirements_for($phase, $type) ); } } $req->finalize if $self->is_finalized; return $req; } #pod =method as_string_hash #pod #pod This method returns a hashref containing structures suitable for dumping into a #pod distmeta data structure. It is made up of hashes and strings, only; there will #pod be no Prereqs, CPAN::Meta::Requirements, or C objects inside it. #pod #pod =cut sub as_string_hash { my ($self) = @_; my %hash; for my $phase ($self->__legal_phases) { for my $type ($self->__legal_types) { my $req = $self->requirements_for($phase, $type); next unless $req->required_modules; $hash{ $phase }{ $type } = $req->as_string_hash; } } return \%hash; } #pod =method is_finalized #pod #pod This method returns true if the set of prereqs has been marked "finalized," and #pod cannot be altered. #pod #pod =cut sub is_finalized { $_[0]{finalized} } #pod =method finalize #pod #pod Calling C on a Prereqs object will close it for further modification. #pod Attempting to make any changes that would actually alter the prereqs will #pod result in an exception being thrown. #pod #pod =cut sub finalize { my ($self) = @_; $self->{finalized} = 1; for my $phase (keys %{ $self->{prereqs} }) { $_->finalize for values %{ $self->{prereqs}{$phase} }; } } #pod =method clone #pod #pod my $cloned_prereqs = $prereqs->clone; #pod #pod This method returns a Prereqs object that is identical to the original object, #pod but can be altered without affecting the original object. Finalization does #pod not survive cloning, meaning that you may clone a finalized set of prereqs and #pod then modify the clone. #pod #pod =cut sub clone { my ($self) = @_; my $clone = (ref $self)->new( $self->as_string_hash ); } 1; # ABSTRACT: a set of distribution prerequisites by phase and type __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta::Prereqs - a set of distribution prerequisites by phase and type =head1 VERSION version 2.143240 =head1 DESCRIPTION A CPAN::Meta::Prereqs object represents the prerequisites for a CPAN distribution or one of its optional features. Each set of prereqs is organized by phase and type, as described in L. =head1 METHODS =head2 new my $prereq = CPAN::Meta::Prereqs->new( \%prereq_spec ); This method returns a new set of Prereqs. The input should look like the contents of the C field described in L, meaning something more or less like this: my $prereq = CPAN::Meta::Prereqs->new({ runtime => { requires => { 'Some::Module' => '1.234', ..., }, ..., }, ..., }); You can also construct an empty set of prereqs with: my $prereqs = CPAN::Meta::Prereqs->new; This empty set of prereqs is useful for accumulating new prereqs before finally dumping the whole set into a structure or string. =head2 requirements_for my $requirements = $prereqs->requirements_for( $phase, $type ); This method returns a L object for the given phase/type combination. If no prerequisites are registered for that combination, a new CPAN::Meta::Requirements object will be returned, and it may be added to as needed. If C<$phase> or C<$type> are undefined or otherwise invalid, an exception will be raised. =head2 with_merged_prereqs my $new_prereqs = $prereqs->with_merged_prereqs( $other_prereqs ); my $new_prereqs = $prereqs->with_merged_prereqs( \@other_prereqs ); This method returns a new CPAN::Meta::Prereqs objects in which all the other prerequisites given are merged into the current set. This is primarily provided for combining a distribution's core prereqs with the prereqs of one of its optional features. The new prereqs object has no ties to the originals, and altering it further will not alter them. =head2 merged_requirements my $new_reqs = $prereqs->merged_requirements( \@phases, \@types ); my $new_reqs = $prereqs->merged_requirements( \@phases ); my $new_reqs = $preerqs->merged_requirements(); This method joins together all requirements across a number of phases and types into a new L object. If arguments are omitted, it defaults to "runtime", "build" and "test" for phases and "requires" and "recommends" for types. =head2 as_string_hash This method returns a hashref containing structures suitable for dumping into a distmeta data structure. It is made up of hashes and strings, only; there will be no Prereqs, CPAN::Meta::Requirements, or C objects inside it. =head2 is_finalized This method returns true if the set of prereqs has been marked "finalized," and cannot be altered. =head2 finalize Calling C on a Prereqs object will close it for further modification. Attempting to make any changes that would actually alter the prereqs will result in an exception being thrown. =head2 clone my $cloned_prereqs = $prereqs->clone; This method returns a Prereqs object that is identical to the original object, but can be altered without affecting the original object. Finalization does not survive cloning, meaning that you may clone a finalized set of prereqs and then modify the clone. =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at 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 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!ÉoOÞqÞqperl5/CPAN/Meta.pmnuÏÃ6Ç$use 5.006; use strict; use warnings; package CPAN::Meta; # VERSION $CPAN::Meta::VERSION = '2.143240'; #pod =head1 SYNOPSIS #pod #pod use v5.10; #pod use strict; #pod use warnings; #pod use CPAN::Meta; #pod use Module::Load; #pod #pod my $meta = CPAN::Meta->load_file('META.json'); #pod #pod printf "testing requirements for %s version %s\n", #pod $meta->name, #pod $meta->version; #pod #pod my $prereqs = $meta->effective_prereqs; #pod #pod for my $phase ( qw/configure runtime build test/ ) { #pod say "Requirements for $phase:"; #pod my $reqs = $prereqs->requirements_for($phase, "requires"); #pod for my $module ( sort $reqs->required_modules ) { #pod my $status; #pod if ( eval { load $module unless $module eq 'perl'; 1 } ) { #pod my $version = $module eq 'perl' ? $] : $module->VERSION; #pod $status = $reqs->accepts_module($module, $version) #pod ? "$version ok" : "$version not ok"; #pod } else { #pod $status = "missing" #pod }; #pod say " $module ($status)"; #pod } #pod } #pod #pod =head1 DESCRIPTION #pod #pod Software distributions released to the CPAN include a F or, for #pod older distributions, F, which describes the distribution, its #pod contents, and the requirements for building and installing the distribution. #pod The data structure stored in the F file is described in #pod L. #pod #pod CPAN::Meta provides a simple class to represent this distribution metadata (or #pod I), along with some helpful methods for interrogating that data. #pod #pod The documentation below is only for the methods of the CPAN::Meta object. For #pod information on the meaning of individual fields, consult the spec. #pod #pod =cut use Carp qw(carp croak); use CPAN::Meta::Feature; use CPAN::Meta::Prereqs; use CPAN::Meta::Converter; use CPAN::Meta::Validator; use Parse::CPAN::Meta 1.4414 (); BEGIN { *_dclone = \&CPAN::Meta::Converter::_dclone } #pod =head1 STRING DATA #pod #pod The following methods return a single value, which is the value for the #pod corresponding entry in the distmeta structure. Values should be either undef #pod or strings. #pod #pod =for :list #pod * abstract #pod * description #pod * dynamic_config #pod * generated_by #pod * name #pod * release_status #pod * version #pod #pod =cut BEGIN { my @STRING_READERS = qw( abstract description dynamic_config generated_by name release_status version ); no strict 'refs'; for my $attr (@STRING_READERS) { *$attr = sub { $_[0]{ $attr } }; } } #pod =head1 LIST DATA #pod #pod These methods return lists of string values, which might be represented in the #pod distmeta structure as arrayrefs or scalars: #pod #pod =for :list #pod * authors #pod * keywords #pod * licenses #pod #pod The C and C methods may also be called as C and #pod C, respectively, to match the field name in the distmeta structure. #pod #pod =cut BEGIN { my @LIST_READERS = qw( author keywords license ); no strict 'refs'; for my $attr (@LIST_READERS) { *$attr = sub { my $value = $_[0]{ $attr }; croak "$attr must be called in list context" unless wantarray; return @{ _dclone($value) } if ref $value; return $value; }; } } sub authors { $_[0]->author } sub licenses { $_[0]->license } #pod =head1 MAP DATA #pod #pod These readers return hashrefs of arbitrary unblessed data structures, each #pod described more fully in the specification: #pod #pod =for :list #pod * meta_spec #pod * resources #pod * provides #pod * no_index #pod * prereqs #pod * optional_features #pod #pod =cut BEGIN { my @MAP_READERS = qw( meta-spec resources provides no_index prereqs optional_features ); no strict 'refs'; for my $attr (@MAP_READERS) { (my $subname = $attr) =~ s/-/_/; *$subname = sub { my $value = $_[0]{ $attr }; return _dclone($value) if $value; return {}; }; } } #pod =head1 CUSTOM DATA #pod #pod A list of custom keys are available from the C method and #pod particular keys may be retrieved with the C method. #pod #pod say $meta->custom($_) for $meta->custom_keys; #pod #pod If a custom key refers to a data structure, a deep clone is returned. #pod #pod =cut sub custom_keys { return grep { /^x_/i } keys %{$_[0]}; } sub custom { my ($self, $attr) = @_; my $value = $self->{$attr}; return _dclone($value) if ref $value; return $value; } #pod =method new #pod #pod my $meta = CPAN::Meta->new($distmeta_struct, \%options); #pod #pod Returns a valid CPAN::Meta object or dies if the supplied metadata hash #pod reference fails to validate. Older-format metadata will be up-converted to #pod version 2 if they validate against the original stated specification. #pod #pod It takes an optional hashref of options. Valid options include: #pod #pod =over #pod #pod =item * #pod #pod lazy_validation -- if true, new will attempt to convert the given metadata #pod to version 2 before attempting to validate it. This means than any #pod fixable errors will be handled by CPAN::Meta::Converter before validation. #pod (Note that this might result in invalid optional data being silently #pod dropped.) The default is false. #pod #pod =back #pod #pod =cut sub _new { my ($class, $struct, $options) = @_; my $self; if ( $options->{lazy_validation} ) { # try to convert to a valid structure; if succeeds, then return it my $cmc = CPAN::Meta::Converter->new( $struct ); $self = $cmc->convert( version => 2 ); # valid or dies return bless $self, $class; } else { # validate original struct my $cmv = CPAN::Meta::Validator->new( $struct ); unless ( $cmv->is_valid) { die "Invalid metadata structure. Errors: " . join(", ", $cmv->errors) . "\n"; } } # up-convert older spec versions my $version = $struct->{'meta-spec'}{version} || '1.0'; if ( $version == 2 ) { $self = $struct; } else { my $cmc = CPAN::Meta::Converter->new( $struct ); $self = $cmc->convert( version => 2 ); } return bless $self, $class; } sub new { my ($class, $struct, $options) = @_; my $self = eval { $class->_new($struct, $options) }; croak($@) if $@; return $self; } #pod =method create #pod #pod my $meta = CPAN::Meta->create($distmeta_struct, \%options); #pod #pod This is same as C, except that C and C fields #pod will be generated if not provided. This means the metadata structure is #pod assumed to otherwise follow the latest L. #pod #pod =cut sub create { my ($class, $struct, $options) = @_; my $version = __PACKAGE__->VERSION || 2; $struct->{generated_by} ||= __PACKAGE__ . " version $version" ; $struct->{'meta-spec'}{version} ||= int($version); my $self = eval { $class->_new($struct, $options) }; croak ($@) if $@; return $self; } #pod =method load_file #pod #pod my $meta = CPAN::Meta->load_file($distmeta_file, \%options); #pod #pod Given a pathname to a file containing metadata, this deserializes the file #pod according to its file suffix and constructs a new C object, just #pod like C. It will die if the deserialized version fails to validate #pod against its stated specification version. #pod #pod It takes the same options as C but C defaults to #pod true. #pod #pod =cut sub load_file { my ($class, $file, $options) = @_; $options->{lazy_validation} = 1 unless exists $options->{lazy_validation}; croak "load_file() requires a valid, readable filename" unless -r $file; my $self; eval { my $struct = Parse::CPAN::Meta->load_file( $file ); $self = $class->_new($struct, $options); }; croak($@) if $@; return $self; } #pod =method load_yaml_string #pod #pod my $meta = CPAN::Meta->load_yaml_string($yaml, \%options); #pod #pod This method returns a new CPAN::Meta object using the first document in the #pod given YAML string. In other respects it is identical to C. #pod #pod =cut sub load_yaml_string { my ($class, $yaml, $options) = @_; $options->{lazy_validation} = 1 unless exists $options->{lazy_validation}; my $self; eval { my ($struct) = Parse::CPAN::Meta->load_yaml_string( $yaml ); $self = $class->_new($struct, $options); }; croak($@) if $@; return $self; } #pod =method load_json_string #pod #pod my $meta = CPAN::Meta->load_json_string($json, \%options); #pod #pod This method returns a new CPAN::Meta object using the structure represented by #pod the given JSON string. In other respects it is identical to C. #pod #pod =cut sub load_json_string { my ($class, $json, $options) = @_; $options->{lazy_validation} = 1 unless exists $options->{lazy_validation}; my $self; eval { my $struct = Parse::CPAN::Meta->load_json_string( $json ); $self = $class->_new($struct, $options); }; croak($@) if $@; return $self; } #pod =method load_string #pod #pod my $meta = CPAN::Meta->load_string($string, \%options); #pod #pod If you don't know if a string contains YAML or JSON, this method will use #pod L to guess. In other respects it is identical to #pod C. #pod #pod =cut sub load_string { my ($class, $string, $options) = @_; $options->{lazy_validation} = 1 unless exists $options->{lazy_validation}; my $self; eval { my $struct = Parse::CPAN::Meta->load_string( $string ); $self = $class->_new($struct, $options); }; croak($@) if $@; return $self; } #pod =method save #pod #pod $meta->save($distmeta_file, \%options); #pod #pod Serializes the object as JSON and writes it to the given file. The only valid #pod option is C, which defaults to '2'. On Perl 5.8.1 or later, the file #pod is saved with UTF-8 encoding. #pod #pod For C 2 (or higher), the filename should end in '.json'. L #pod is the default JSON backend. Using another JSON backend requires L 2.5 or #pod later and you must set the C<$ENV{PERL_JSON_BACKEND}> to a supported alternate #pod backend like L. #pod #pod For C less than 2, the filename should end in '.yml'. #pod L is used to generate an older metadata structure, which #pod is serialized to YAML. CPAN::Meta::YAML is the default YAML backend. You may #pod set the C<$ENV{PERL_YAML_BACKEND}> to a supported alternative backend, though #pod this is not recommended due to subtle incompatibilities between YAML parsers on #pod CPAN. #pod #pod =cut sub save { my ($self, $file, $options) = @_; my $version = $options->{version} || '2'; my $layer = $] ge '5.008001' ? ':utf8' : ''; if ( $version ge '2' ) { carp "'$file' should end in '.json'" unless $file =~ m{\.json$}; } else { carp "'$file' should end in '.yml'" unless $file =~ m{\.yml$}; } my $data = $self->as_string( $options ); open my $fh, ">$layer", $file or die "Error opening '$file' for writing: $!\n"; print {$fh} $data; close $fh or die "Error closing '$file': $!\n"; return 1; } #pod =method meta_spec_version #pod #pod This method returns the version part of the C entry in the distmeta #pod structure. It is equivalent to: #pod #pod $meta->meta_spec->{version}; #pod #pod =cut sub meta_spec_version { my ($self) = @_; return $self->meta_spec->{version}; } #pod =method effective_prereqs #pod #pod my $prereqs = $meta->effective_prereqs; #pod #pod my $prereqs = $meta->effective_prereqs( \@feature_identifiers ); #pod #pod This method returns a L object describing all the #pod prereqs for the distribution. If an arrayref of feature identifiers is given, #pod the prereqs for the identified features are merged together with the #pod distribution's core prereqs before the CPAN::Meta::Prereqs object is returned. #pod #pod =cut sub effective_prereqs { my ($self, $features) = @_; $features ||= []; my $prereq = CPAN::Meta::Prereqs->new($self->prereqs); return $prereq unless @$features; my @other = map {; $self->feature($_)->prereqs } @$features; return $prereq->with_merged_prereqs(\@other); } #pod =method should_index_file #pod #pod ... if $meta->should_index_file( $filename ); #pod #pod This method returns true if the given file should be indexed. It decides this #pod by checking the C and C keys in the C property of #pod the distmeta structure. Note that neither the version format nor #pod C are considered. #pod #pod C<$filename> should be given in unix format. #pod #pod =cut sub should_index_file { my ($self, $filename) = @_; for my $no_index_file (@{ $self->no_index->{file} || [] }) { return if $filename eq $no_index_file; } for my $no_index_dir (@{ $self->no_index->{directory} }) { $no_index_dir =~ s{$}{/} unless $no_index_dir =~ m{/\z}; return if index($filename, $no_index_dir) == 0; } return 1; } #pod =method should_index_package #pod #pod ... if $meta->should_index_package( $package ); #pod #pod This method returns true if the given package should be indexed. It decides #pod this by checking the C and C keys in the C #pod property of the distmeta structure. Note that neither the version format nor #pod C are considered. #pod #pod =cut sub should_index_package { my ($self, $package) = @_; for my $no_index_pkg (@{ $self->no_index->{package} || [] }) { return if $package eq $no_index_pkg; } for my $no_index_ns (@{ $self->no_index->{namespace} }) { return if index($package, "${no_index_ns}::") == 0; } return 1; } #pod =method features #pod #pod my @feature_objects = $meta->features; #pod #pod This method returns a list of L objects, one for each #pod optional feature described by the distribution's metadata. #pod #pod =cut sub features { my ($self) = @_; my $opt_f = $self->optional_features; my @features = map {; CPAN::Meta::Feature->new($_ => $opt_f->{ $_ }) } keys %$opt_f; return @features; } #pod =method feature #pod #pod my $feature_object = $meta->feature( $identifier ); #pod #pod This method returns a L object for the optional feature #pod with the given identifier. If no feature with that identifier exists, an #pod exception will be raised. #pod #pod =cut sub feature { my ($self, $ident) = @_; croak "no feature named $ident" unless my $f = $self->optional_features->{ $ident }; return CPAN::Meta::Feature->new($ident, $f); } #pod =method as_struct #pod #pod my $copy = $meta->as_struct( \%options ); #pod #pod This method returns a deep copy of the object's metadata as an unblessed hash #pod reference. It takes an optional hashref of options. If the hashref contains #pod a C argument, the copied metadata will be converted to the version #pod of the specification and returned. For example: #pod #pod my $old_spec = $meta->as_struct( {version => "1.4"} ); #pod #pod =cut sub as_struct { my ($self, $options) = @_; my $struct = _dclone($self); if ( $options->{version} ) { my $cmc = CPAN::Meta::Converter->new( $struct ); $struct = $cmc->convert( version => $options->{version} ); } return $struct; } #pod =method as_string #pod #pod my $string = $meta->as_string( \%options ); #pod #pod This method returns a serialized copy of the object's metadata as a character #pod string. (The strings are B UTF-8 encoded.) It takes an optional hashref #pod of options. If the hashref contains a C argument, the copied metadata #pod will be converted to the version of the specification and returned. For #pod example: #pod #pod my $string = $meta->as_string( {version => "1.4"} ); #pod #pod For C greater than or equal to 2, the string will be serialized as #pod JSON. For C less than 2, the string will be serialized as YAML. In #pod both cases, the same rules are followed as in the C method for choosing #pod a serialization backend. #pod #pod =cut sub as_string { my ($self, $options) = @_; my $version = $options->{version} || '2'; my $struct; if ( $self->meta_spec_version ne $version ) { my $cmc = CPAN::Meta::Converter->new( $self->as_struct ); $struct = $cmc->convert( version => $version ); } else { $struct = $self->as_struct; } my ($data, $backend); if ( $version ge '2' ) { $backend = Parse::CPAN::Meta->json_backend(); $data = $backend->new->pretty->canonical->encode($struct); } else { $backend = Parse::CPAN::Meta->yaml_backend(); $data = eval { no strict 'refs'; &{"$backend\::Dump"}($struct) }; if ( $@ ) { croak $backend->can('errstr') ? $backend->errstr : $@ } } return $data; } # Used by JSON::PP, etc. for "convert_blessed" sub TO_JSON { return { %{ $_[0] } }; } 1; # ABSTRACT: the distribution metadata for a CPAN dist __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Meta - the distribution metadata for a CPAN dist =head1 VERSION version 2.143240 =head1 SYNOPSIS use v5.10; use strict; use warnings; use CPAN::Meta; use Module::Load; my $meta = CPAN::Meta->load_file('META.json'); printf "testing requirements for %s version %s\n", $meta->name, $meta->version; my $prereqs = $meta->effective_prereqs; for my $phase ( qw/configure runtime build test/ ) { say "Requirements for $phase:"; my $reqs = $prereqs->requirements_for($phase, "requires"); for my $module ( sort $reqs->required_modules ) { my $status; if ( eval { load $module unless $module eq 'perl'; 1 } ) { my $version = $module eq 'perl' ? $] : $module->VERSION; $status = $reqs->accepts_module($module, $version) ? "$version ok" : "$version not ok"; } else { $status = "missing" }; say " $module ($status)"; } } =head1 DESCRIPTION Software distributions released to the CPAN include a F or, for older distributions, F, which describes the distribution, its contents, and the requirements for building and installing the distribution. The data structure stored in the F file is described in L. CPAN::Meta provides a simple class to represent this distribution metadata (or I), along with some helpful methods for interrogating that data. The documentation below is only for the methods of the CPAN::Meta object. For information on the meaning of individual fields, consult the spec. =head1 METHODS =head2 new my $meta = CPAN::Meta->new($distmeta_struct, \%options); Returns a valid CPAN::Meta object or dies if the supplied metadata hash reference fails to validate. Older-format metadata will be up-converted to version 2 if they validate against the original stated specification. It takes an optional hashref of options. Valid options include: =over =item * lazy_validation -- if true, new will attempt to convert the given metadata to version 2 before attempting to validate it. This means than any fixable errors will be handled by CPAN::Meta::Converter before validation. (Note that this might result in invalid optional data being silently dropped.) The default is false. =back =head2 create my $meta = CPAN::Meta->create($distmeta_struct, \%options); This is same as C, except that C and C fields will be generated if not provided. This means the metadata structure is assumed to otherwise follow the latest L. =head2 load_file my $meta = CPAN::Meta->load_file($distmeta_file, \%options); Given a pathname to a file containing metadata, this deserializes the file according to its file suffix and constructs a new C object, just like C. It will die if the deserialized version fails to validate against its stated specification version. It takes the same options as C but C defaults to true. =head2 load_yaml_string my $meta = CPAN::Meta->load_yaml_string($yaml, \%options); This method returns a new CPAN::Meta object using the first document in the given YAML string. In other respects it is identical to C. =head2 load_json_string my $meta = CPAN::Meta->load_json_string($json, \%options); This method returns a new CPAN::Meta object using the structure represented by the given JSON string. In other respects it is identical to C. =head2 load_string my $meta = CPAN::Meta->load_string($string, \%options); If you don't know if a string contains YAML or JSON, this method will use L to guess. In other respects it is identical to C. =head2 save $meta->save($distmeta_file, \%options); Serializes the object as JSON and writes it to the given file. The only valid option is C, which defaults to '2'. On Perl 5.8.1 or later, the file is saved with UTF-8 encoding. For C 2 (or higher), the filename should end in '.json'. L is the default JSON backend. Using another JSON backend requires L 2.5 or later and you must set the C<$ENV{PERL_JSON_BACKEND}> to a supported alternate backend like L. For C less than 2, the filename should end in '.yml'. L is used to generate an older metadata structure, which is serialized to YAML. CPAN::Meta::YAML is the default YAML backend. You may set the C<$ENV{PERL_YAML_BACKEND}> to a supported alternative backend, though this is not recommended due to subtle incompatibilities between YAML parsers on CPAN. =head2 meta_spec_version This method returns the version part of the C entry in the distmeta structure. It is equivalent to: $meta->meta_spec->{version}; =head2 effective_prereqs my $prereqs = $meta->effective_prereqs; my $prereqs = $meta->effective_prereqs( \@feature_identifiers ); This method returns a L object describing all the prereqs for the distribution. If an arrayref of feature identifiers is given, the prereqs for the identified features are merged together with the distribution's core prereqs before the CPAN::Meta::Prereqs object is returned. =head2 should_index_file ... if $meta->should_index_file( $filename ); This method returns true if the given file should be indexed. It decides this by checking the C and C keys in the C property of the distmeta structure. Note that neither the version format nor C are considered. C<$filename> should be given in unix format. =head2 should_index_package ... if $meta->should_index_package( $package ); This method returns true if the given package should be indexed. It decides this by checking the C and C keys in the C property of the distmeta structure. Note that neither the version format nor C are considered. =head2 features my @feature_objects = $meta->features; This method returns a list of L objects, one for each optional feature described by the distribution's metadata. =head2 feature my $feature_object = $meta->feature( $identifier ); This method returns a L object for the optional feature with the given identifier. If no feature with that identifier exists, an exception will be raised. =head2 as_struct my $copy = $meta->as_struct( \%options ); This method returns a deep copy of the object's metadata as an unblessed hash reference. It takes an optional hashref of options. If the hashref contains a C argument, the copied metadata will be converted to the version of the specification and returned. For example: my $old_spec = $meta->as_struct( {version => "1.4"} ); =head2 as_string my $string = $meta->as_string( \%options ); This method returns a serialized copy of the object's metadata as a character string. (The strings are B UTF-8 encoded.) It takes an optional hashref of options. If the hashref contains a C argument, the copied metadata will be converted to the version of the specification and returned. For example: my $string = $meta->as_string( {version => "1.4"} ); For C greater than or equal to 2, the string will be serialized as JSON. For C less than 2, the string will be serialized as YAML. In both cases, the same rules are followed as in the C method for choosing a serialization backend. =head1 STRING DATA The following methods return a single value, which is the value for the corresponding entry in the distmeta structure. Values should be either undef or strings. =over 4 =item * abstract =item * description =item * dynamic_config =item * generated_by =item * name =item * release_status =item * version =back =head1 LIST DATA These methods return lists of string values, which might be represented in the distmeta structure as arrayrefs or scalars: =over 4 =item * authors =item * keywords =item * licenses =back The C and C methods may also be called as C and C, respectively, to match the field name in the distmeta structure. =head1 MAP DATA These readers return hashrefs of arbitrary unblessed data structures, each described more fully in the specification: =over 4 =item * meta_spec =item * resources =item * provides =item * no_index =item * prereqs =item * optional_features =back =head1 CUSTOM DATA A list of custom keys are available from the C method and particular keys may be retrieved with the C method. say $meta->custom($_) for $meta->custom_keys; If a custom key refers to a data structure, a deep clone is returned. =for Pod::Coverage TO_JSON abstract author authors custom custom_keys description dynamic_config generated_by keywords license licenses meta_spec name no_index optional_features prereqs provides release_status resources version =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at 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 =over 4 =item * L =item * L =back =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L git clone https://github.com/Perl-Toolchain-Gang/CPAN-Meta.git =head1 AUTHORS =over 4 =item * David Golden =item * Ricardo Signes =back =head1 CONTRIBUTORS =for stopwords Ansgar Burchardt Avar Arnfjord Bjarmason Christopher J. Madsen Chuck Adams Cory G Watson Damyan Ivanov Eric Wilhelm Graham Knop Gregor Hermann Karen Etheridge Kenichi Ishigaki Ken Williams Lars Dieckow Leon Timmermans majensen Mark Fowler Matt S Trout Michael G. Schwern moznion Olaf Alders Olivier Mengue Randy Sims =over 4 =item * Ansgar Burchardt =item * Avar Arnfjord Bjarmason =item * Christopher J. Madsen =item * Chuck Adams =item * Cory G Watson =item * Damyan Ivanov =item * Eric Wilhelm =item * Graham Knop =item * Gregor Hermann =item * Karen Etheridge =item * Kenichi Ishigaki =item * Ken Williams =item * Lars Dieckow =item * Leon Timmermans =item * majensen =item * Mark Fowler =item * Matt S Trout =item * Michael G. Schwern =item * moznion =item * Olaf Alders =item * Olivier Mengue =item * Randy Sims =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by David Golden and Ricardo Signes. 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 PK!CPŒà¡>¡>perl5/POD2/PT_BR/local/lib.podnuÏÃ6Ç$=encoding utf8 =head1 NAME local::lib~[pt_br] - crie e use um diretório lib/ local para módulos perl com PERL5LIB =head1 SINOPSE No código - use local::lib; # configura um lib local em ~/perl5 use local::lib '~/foo'; # idem, mas ~/foo # Ou... use FindBin; use local::lib "$FindBin::Bin/../suporte"; # bibliotecas de suporte locais à aplicação Pela linha de comando (shell) - # Instala o LWP e suas dependências não encontradas no diretório '~/perl5' perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)' # Apenas exibe alguns comandos úteis para a shell $ perl -Mlocal::lib export PERL_MB_OPT='--install_base /home/username/perl5' export PERL_MM_OPT='INSTALL_BASE=/home/username/perl5' export PERL5LIB='/home/username/perl5/lib/perl5/i386-linux:/home/username/perl5/lib/perl5' export PATH="/home/username/perl5/bin:$PATH" =head2 A técnica de 'bootstrapping' Uma forma comum de instalar o local::lib é usando o que é conhecido como técnica de "bootstrapping". É uma boa abordagem caso seu administrador de sistemas não tenha instalado o local::lib. Nesse caso, você precisará instalar o local::lib em seu diretório de usuário. Caso você tenha privilégios de administrador, ainda assim deverá configurar suas variáveis de ambiente, como discutido no passo 4, abaixo. Sem elas, você ainda instalará módulos no CPAN do sistema e seus scripts Perl não utilizarão o caminho para o lib/ que você definiu com o local::lib. Por padrão, o local::lib instala os módulos do CPAN e a si próprio em ~/perl5. Usuários do Windows devem ler L. 1. Baixe e descompacte o local::lib do CPAN (procure por "Download" na página do CPAN sobre o local::lib). Faça isso como um usuário comum, não como root ou administrador. Descompacte o arquivo em seu diretório de usuário ou em qualquer outro local conveniente. 2. Execute isso: perl Makefile.PL --bootstrap Caso o sistema pergunte se deve configurar tudo que puder automaticamente, você provavelmente deve responder que sim (yes). Para instalar o local::lib em um diretório que não o padrão, você precisará especificá-lo ao chamar o bootstrap, da seguinte forma: perl Makefile.PL --bootstrap=~/foo 3. Execute isso: (local::lib assume que você possui o comando 'make' instalado em seu sistema) make test && make install 4. Agora precisamos configurar as variáveis de ambiente apropriadas para que o Perl use nosso recém-criado diretório lib/. Caso esteja usando bash ou outra shell Bourne, você pode fazer isso adicionando a seguinte linha em seu script de inicialização da shell: echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc Caso esteja usando a shell C, pode fazer da seguinte forma: /bin/csh echo $SHELL /bin/csh perl -I$HOME/perl5/lib/perl5 -Mlocal::lib >> ~/.cshrc Caso tenha passado para o bootstrap um diretório que não o padrão, você precisará indicá-lo na chamada ao local::lib, dessa forma: echo 'eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)' >>~/.bashrc Após atualizar seu arquivo de configuração da shell, certifique-se de processá-lo novamente para obter as modificações em sua shell atual. Shells Bourne usam C<. ~/.bashrc> para isso, enquanto shells C usam C. Se estiver em uma máquina lenta ou operando com grandes limitações de espaço em disco, você pode desativar a geração automática de manpages a partir do POD ao instalar módulos. Para isso, basta passar o argumento C<--no-manpages> durante o bootstrap: perl Makefile.PL --bootstrap --no-manpages Para evitar ter que fazer vários bootstraps para vários ambientes de módulos Perl na mesma conta de usuário - por exemplo se você usa o local::lib para desenvolver diferentes aplicativos independentes - você pode utilizar uma única instalação bootstrap do local::lib para instalar módulos em diretórios diferentes da seguinte forma: cd ~/meudir1 perl -Mlocal::lib=./ eval $(perl -Mlocal::lib=./) ### Para configurar o ambiente apenas nessa shell printenv ### Veja que o ~/meudir1 está na PERL5LIB perl -MCPAN -e install ... ### Os módulos que quiser cd ../meudir2 ... REPITA ... Para múltiplos ambientes destinados a múltiplos aplicativos, você pode precisar incluir uma versão modificada das instruções de C<< use FindBin >> no exemplo "No código" acima. Caso tenha feito algo como o que foi descrito acima, terá um conjunto de módulos Perl em C<< ~/meudir1/lib >>. Caso tenha um script em C<< ~/meudir1/scripts/meuscript.pl >>, você precisará indicar a ele onde encontrar os módulos que instalou para ele em C<< ~/meudir1/lib >>. Em C<< ~/meudir1/scripts/meuscript.pl >>: use strict; use warnings; use local::lib "$FindBin::Bin/.."; ### aponta para ~/meudir1 e o local::lib acha o lib/ use lib "$FindBin::Bin/../lib"; ### aponta para ~/meudir1/lib Coloque isso antes de qualquer bloco BEGIN { ... } que precise dos módulos instalados. =head2 Diferenças ao usar esse módulo em Win32 Para configurar as variáveis de ambiente apropriadas para sua sessão atual do C, você pode fazer assim: C:\>perl -Mlocal::lib set PERL_MB_OPT=--install_base C:\DOCUME~1\ADMINI~1\perl5 set PERL_MM_OPT=INSTALL_BASE=C:\DOCUME~1\ADMINI~1\perl5 set PERL5LIB=C:\DOCUME~1\ADMINI~1\perl5\lib\perl5;C:\DOCUME~1\ADMINI~1\perl5\lib\perl5\MSWin32-x86-multi-thread set PATH=C:\DOCUME~1\ADMINI~1\perl5\bin;%PATH% ### Para configurar o ambiente apenas dessa shell C:\>perl -Mlocal::lib > %TEMP%\tmp.bat && %TEMP%\tmp.bat && del %TEMP%\temp.bat ### em vez de $(perl -Mlocal::lib=./) Caso queira que as configurações do ambiente persistam, você precisará adicioná-las em Painel de Controle -> Sistema, ou usar o L. O "~" é transformado no diretório do perfil do usuário (o diretório com o nome do usuário dentro de "Documents and Settings" (Windows XP ou anterior) ou "Usuários" (Windows Vista e mais recentes)) a menos que $ENV{HOME} exista. Após isso, o nome do diretório é encurtado e os subdiretórios são criados (o que significa que o diretório deve existir). =head1 MOTIVAÇÃO A versão de um pacote Perl na sua máquina nem sempre é a que você precisa. Obviamente, a melhor coisa a fazer seria atualizá-la para a versão desejada. No entanto, você pode estar em uma situação que o impede de fazer isso. Talvez você não tenha privilégios de administrador do sistema; ou talvez esteja usando um sistema de gerenciamento de pacotes como o do Debian, e ainda não exista um pacote disponível na versão desejada. local::lib resolve esse problema possibilitando a criação de seu próprio diretório de pacotes Perl obtidos do CPAN (em sistemas multi-usuário, isso normalmente fica dentro do diretório de seu usuário). A instalação do Perl no sistema permanece inalterada; você simplesmente chama o Perl com opções especiais para que ele use os pacotes em seu diretório local em vez dos pacotes do sistema. O local::lib organiza as coisas para que versões dos pacotes Perl instalados localmente tenham precedência sobre as do sistema. Caso esteja usando um sistema de gerenciamento de pacote (como em sistemas Debian), não precisará se preocupar com conflitos entre o Debian e o CPAN. Sua versão local dos pacotes será instalada em um diretório completamente diferente das versões instaladas pelo gerenciador de pacotes do sistema. =head1 DESCRIÇÃO Este módulo oferece uma forma rápida e conveniente para criar um repositório de módulos locais ao usuário, dentro do diretório do mesmo. Ele também monta e exibe para o usuário uma lista de variáveis de ambiente utilizando a sintaxe da shell atual do usuário (conforme especificado pela variável de ambiente C), pronta para ser adicionada diretamente no arquivo de configuração da shell. Generalizando, o local::lib permite a criação e uso de um diretório contendo módulos Perl fora do C<@INC> do Perl. Isso facilita a produção de aplicações com uma versão específica de determinado módulo, ou coleção de módulos. Também é útil quando o mantenedor de um módulo não aplicou determinado patch que você precisa para seu aplicativo. Durante o C, o local::lib define valores apropriados para as seguintes variáveis de ambiente: =over 4 =item PERL_MB_OPT =item PERL_MM_OPT =item PERL5LIB =item PATH valores serão anexados ao PATH, em vez de substituí-lo. =back Esses valores são então disponibilizados para referência por qualquer outro código após o C. =head1 CRIANDO UM CONJUNTO AUTO-CONTIDO DE MÓDULOS Veja L para uma maneira de fazer isso - mas note que há uma série de ressalvas na abordagem, e a melhor forma é sempre fazer o 'build' contra uma versão limpa do perl (i.e. com 'site' e 'vendor' o mais vazios possível). =head1 MÉTODOS =head2 ensure_dir_structure_for =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: Nenhum =back Tenta criar o caminho fornecido, e todos os diretórios superiores necessários. Gera uma exceção em caso de falha. =head2 print_environment_vars_for =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: Nenhum =back Exibe na saída padrão as variáveis listadas acima, devidamente ajustadas para utilizar o caminho fornecido como diretório base. =head2 build_environment_vars_for =over 4 =item Argumentos: $caminho_do_diretorio, $interpolar =item Valor de Retorno: %variaveis_de_ambiente =back Retorna hash contendo as variáveis de ambiente listadas acima, devidamente ajustadas para utilizar o caminho fornecido como diretório base. =head2 setup_env_hash_for =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: Nenhum =back Constrói as chaves no C<%ENV> para o caminho fornecido, chamando C. =head2 install_base_perl_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_base_de_instalacao =back Retorna um caminho de diretório indicando onde instalar os módulos Perl para essa instalação local de bibliotecas. Adiciona os diretórios C e C ao final do caminho fornecido. =head2 install_base_arch_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_base_de_instalacao_arch =back Retorna um caminho de diretório indicando onde instalar os módulos Perl de arquiteturas específicas para essa instalação local de bibliotecas. Baseia-se no valor de retorno do método L, adicionando o valor de C<$Config{archname}>. =head2 install_base_bin_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_base_de_instalacao_bin =back Retorna um caminho de diretório indicando onde instalar programas executáveis para essa instalação local de bibliotecas. Baseia-se no valor de retorno do método L, adicionando o diretório C. =head2 resolve_empty_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_base_de_instalacao =back Cria e retorna o caminho de diretório raiz em que a instalação local de módulos deve ser feita. O padrão é C<~/perl5>. =head2 resolve_home_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_para_home =back Procura pelo diretório padrão (home) do usuário. Gera uma exceção caso não encontre resultado definitivo. =head2 resolve_relative_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_absoluto =back Transforma o caminho fornecido em um caminho absoluto. =head2 resolve_path =over 4 =item Argumentos: $caminho_do_diretorio =item Valor de Retorno: $caminho_absoluto =back Invoca os seguintes métodos em sequência, passando o resultado do método anterior para o seguinte, na tentativa de descobrir onde configurar o ambiente para a instalação local de bibliotecas: L, L, L. Passa o caminho de diretório fornecido para L que retorna um resultado que é passado para L, que então tem seu resultado passado para L. O resultado dessa chamada final é então retornado pelo L. =head1 UM AVISO SOBRE UNINST=1 Tenha cuidado ao usar o local::lib em conjunto com "make install UNINST=1". A idéia dessa opção é desinstalar a versão anterior de um módulo antes de instalar a mais recente. No entanto ela não possui uma verificação de segurança de que a versão antiga e a nova referem-se ao mesmo diretório. Usada em combinação com o local::lib, você pode potencialmente apagar uma versão globalmente acessível de um módulo e instalar a versão mais nova no diretório local. Apenas utilize "make install UNINST=1" junto com o local::lib se você entende essas possíveis consequências. =head1 LIMITAÇÕES As ferramentas auxiliares do perl não conseguem lidar com nomes de diretórios contendo espaços, então não é possível fazer seu bootstrap do local::lib em um diretório com espaços. O que você pode fazer é mover seu local::lib para um diretório com espaços B ter instalado todos os módulos dentro dele. Mas esteja ciente que você não poderá atualizar ou instalar outros módulos do CPAN nesse diretório local após a mudança. A detecção da shell é relativamente básica. Neste momento, qualquer coisa com csh no nome será tratada como a C shell ou compatível, e todo o resto será tratado como Bourne, exceto em sistemas Win32. Caso a variável de ambiente C não esteja disponível, assumiremos tratar-se de uma shell compatível com a Bourne. A técnica de bootstrap é um hack e usará o CPAN.pm para o ExtUtils::MakeMaker mesmo que você tenha o CPANPLUS instalado. Destrói qualquer valor pré-existente nas variáveis de ambiente PERL5LIB, PERL_MM_OPT e PERL_MB_OPT. Provavelmente deveria auto-configurar o CPAN caso isso ainda não tenha sido feito. Correções (patches) são muito bem-vindos para quaisquer dos itens acima. Em sistemas Win32, não há uma forma de escrever no registro as variáveis de ambiente criadas, para que elas persistam a uma reinicialização. =head1 SOLUÇÃO DE PROBLEMAS Se você configurou o local::lib para instalar módulos do CPAN em algum lugar do seu 'home', e mais tarde tentou instalar um módulo fazendo C, mas ele falhou com um erro como: C e em algum lugar no seu log de instalação houver um erro dizendo C<'INSTALL_BASE' is not a known MakeMaker parameter name>, então você de alguma forma perdeu seu ExtUtils::MakeMaker atualizado. Para remediar a situação, execute novamente o procedimento de bootstrap descrito acima. Então, execute C Finalmente, execute novamente o C e ele deve instalar sem problemas. =head1 AMBIENTE =over 4 =item SHELL =item COMSPEC O local::lib procura pela variável de ambiente C do usuário ao processar e exibir os comandos a serem adicionados no arquivo de configuração da shell. Em sistemas Win32, C também será examinado. =back =head1 SUPORTE IRC: Acesse #local-lib em irc.perl.org. =head1 AUTOR DA TRADUÇÃO Breno G. de Oliveira, C<< >>, após ter perdido uma aposta para o L durante a Copa de 2010. =head1 COPYRIGHT Copyright (c) 2007 - 2010 L e L do local::lib como listados em L. =head1 LICENÇA Esta biblioteca é software livre e pode ser distribuída sob os mesmo termos do perl. PK!�–( ï@ï@perl5/POD2/DE/local/lib.podnuÏÃ6Ç$=encoding utf8 =head1 NAME local::lib~[de] - Erschaffen und benutzen von Perl Modulen in einem lokalen lib/ Verzeichnis mit PERL5LIB =head1 SYNOPSIS Im Code - use local::lib; # Benutzt das Verzeichnis ~/perl5 zum anlegen des lokalen lib/ Verzeichnisses use local::lib '~/foo'; # das selbe, aber mit ~/foo # Oder... use FindBin; use local::lib "$FindBin::Bin/../support"; # Applikationsspezifische Sammlung von Modulen Von der Shell - # Installiert LWP und alle notwendigen Abhängigkeiten in das '~/perl5' Verzeichnis perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)' # Gibt die Shell Kommandos aus um die Umgebung vorzubereiten $ perl -Mlocal::lib export PERL_MB_OPT='--install_base /home/username/perl5' export PERL_MM_OPT='INSTALL_BASE=/home/username/perl5' export PERL5LIB='/home/username/perl5/lib/perl5/i386-linux:/home/username/perl5/lib/perl5' export PATH="/home/username/perl5/bin:$PATH" =head2 Die Bootstrapping Methode Ein typischer Weg um local::lib zu benutzen ist die sogenannte "Bootstrapping" Methode. Diese Methode wird benutzt wenn noch kein local::lib auf dem System installiert ist. In diesem Fall kannst du einfach local::lib direkt in deinem Home-Verzeichnis installieren. Selbst wenn du administrative Rechte hast, ist es wichtig das die Umgebungsvariablen von Schritt 4 in deinem Shell Startup Skript gesetzt werden. Ohne diesen Schritt werden die Module von CPAN weiterhin im System installiert und auch Perl Skripte die du startest würden das von local::lib erstellte lib/ Verzeichnis nicht nutzen. Standardmäßig installiert sich local::lib in ~/perl5. Windows Benutzern müssen ausserdem dies hier lesen: L. 1. Lade das Tar-Archiv von CPAN runter (Suche nach "Download" auf der CPAN Seite von local::lib) und entpacke es in einem beliebigem Verzeichnis. Um das obige Problem zu vermeiden, sollte man dies als normaler User tun und nicht als root oder Administrator. 2. Starte in dem entstandenen Verzeichnis folgenden Befehl: perl Makefile.PL --bootstrap Wenn das System dir vorschlägt gewisse Dinge eigenständig zu konfigurieren ist es in fast allen Fällen vollkommen in Ordnung einfach "yes" zu antworten. Falls du local::lib nicht in das Standard Verzeichnis installieren willst, musst du dieses Verzeichnis als Parameter angeben: perl Makefile.PL --bootstrap=~/foo 3. Danach folgenden Befehl starten: (local::lib erwartet make auf dem System) make test && make install 4. Nun müssen wir die benötigten Umgebungsvariablen, damit Perl unser neu generiertes lib/ Verzeichnis benutzt. Wenn du bash oder eine andere Bourne Shell benutzt, kannst du es über diesen Weg zu deinem Shell Startup Skript hinzufügen: echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc Wenn du C Shell benutzt, du kannst das gleiche hiermit erreichen: /bin/csh echo $SHELL /bin/csh perl -I$HOME/perl5/lib/perl5 -Mlocal::lib >> ~/.cshrc Wenn du beim bootstrappen ein anderes Verzeichnis benutzt als das Standardverzeichnis, dann musst du dieses Verzeichnis als Parameter beim Laden des Modules local::lib angeben: echo 'eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)' >>~/.bashrc Nachdem diese Änderungen in deinem Shell Startup Skript gemacht wurden, ist es nun wichtig das diese Umgebungsvariablen auch gesetzt sind in deiner aktuellen Umgebung. In Bourne Shells macht man dies z.B. mit C<. ~/.bashrc>, und in C Shell würde man es mit: C mit. Wenn du eine sehr langsames System hast, oder du unter drakonischen Regulierungen des Plattenplatz leben musst, kann man die automatische Generierung der manpages vom POD bei der Installation des Moduls deaktivieren beim bootstrapping mit dem C<--no-manpages> Parameter: perl Makefile.PL --bootstrap --no-manpages Um zu vermeiden das man mehrere bootstraps macht um z.B. für verschiedene Applikationen eigene local::lib Installationen zu nutzen, kann man eine dieser Umgebungen benutzen um einfach in beliebigen anderen Verzeichnis Module zu installieren und somit weitere eigenständige lib/ Umgebungen zu bekommen: cd ~/mydir1 perl -Mlocal::lib=./ eval $(perl -Mlocal::lib=./) ### Um die Umgebungsvariablen für die ### aktuelle Shell zusetzen printenv ### Hier kannst du sehen das ~/mydir1 ### in der PERL5LIB Umgebungsvariable ### steht perl -MCPAN -e install ... ### welche Module auch immer ... cd ../mydir2 ... WIEDERHOLEN ... Für mehrere Umgebungen in dieser Form brauch man eine Modifikation in der Benutzung von C<< use FindBin >> in dem "Im Code" Beispiel oben. Wenn du sowas machst, und du hast damit z.B. Perl Module nach C<< ~/mydir1/lib >> installiert und du hast ein Script in C<< ~/mydir1/scripts/myscript.pl >>, du musst dort angeben das die Module die es braucht im Verzeichnis C<< ~/mydir1/lib >> liegen. In C<< ~/mydir1/scripts/myscript.pl >> steht dann: use strict; use warnings; use local::lib "$FindBin::Bin/.."; ### zeigt auf ~/mydir1 und local::lib ### findet dort lib use lib "$FindBin::Bin/../lib"; ### zeigt auf ~/mydir1/lib Setze das vor jeden BEGIN { ... } Block der die Module braucht die du installiert hast. =head2 Unterschiede bei Benutzung dieses Module mit Win32 Um die nötigen Umgebungsvariablen für diese Variablen in der derzeitigen Sitzung mit C zu setzen, kann man folgendes kommando nutzen: C:\>perl -Mlocal::lib set PERL_MB_OPT=--install_base C:\DOCUME~1\ADMINI~1\perl5 set PERL_MM_OPT=INSTALL_BASE=C:\DOCUME~1\ADMINI~1\perl5 set PERL5LIB=C:\DOCUME~1\ADMINI~1\perl5\lib\perl5;C:\DOCUME~1\ADMINI~1\perl5\lib\perl5\MSWin32-x86-multi-thread set PATH=C:\DOCUME~1\ADMINI~1\perl5\bin;%PATH% ### Um die Umgebungsvariablen für diese Shell alleine zu setzen C:\>perl -Mlocal::lib > %TEMP%\tmp.bat && %TEMP%\tmp.bat && del %TEMP%\temp.bat ### anstelle von $(perl -Mlocal::lib=./) in bash. Wenn du willst das die Umgebungsvariablen dauerhaft gesetzt sind, musst du diese in Systemsteuerung / System dauerhaft selber eintragen oder L benutzen. Die "~" wird übersetzt zu dem Benutzer Profil Verzeichnis (das Verzeichnis was beim User als "Dokumente und Einstellungen" bekannt ist unter Windows XP und vorher oder das "Benutzer" Verzeichnis bei Windows Vista und später), solange $ENV{HOME} nicht gesetzt ist. Das Verzeichnis wird hierbei zu dem korrekten Kurznamen umgewandelt, und muss daher definitiv existieren, und wird um die nötigen Unterverzeichnise erweitert. =head1 GRUNDPRINZIP Die Version von den Perl Paketen die man benötigt für spezifische Aufgaben sind sehr häufig nicht die richtigen oder korrekten Versionen auf dem System vorinstalliert. Ein Updaten von diesen Modulen ist in vielen Fällen einfach nicht möglich weil die nötigen Rechte fehlen. Ausserdem ist es generell nicht gut eigenständig die Versionen der Module auf dem System auszutauschen, weil natürlich der Rest des Systems genau die Version erwartet die von der Systemverwaltung auch installiert wurde. local::lib löst dieses Problem, es erlaubt dir dein komplett eigenes Verzeichnis für deine CPAN Module zu haben und bist so nicht genötigt die Module vom System zu nutzen oder andersrum andere User nicht mit individuellen Modulwünschen zu Überarbeitung ihres Codes zu zwingen, weil bestimmte Module zentral für alle auf neuere Version upgedatet werden. Die Installation findet hierbei dann z.B. im Home Verzeichnis statt. Es werden nur Umgebungsvariablen gesetzt die das installierte Perl dazu bewegen die im Homeverzeichnis installierten Module zu benutzen, zusätzlich und vorgezogen zu denen auf dem System. Daher muss man sich wenn man ein Paket System benutzt, wie z.b. Debian, garnicht mehr Sorgen machen, irgendwas auf dem System zu verletzten nur durch die Installation von Perl Modulen. =head1 BESCHREIBUNG Dieses Modul bietet eine schnelle und legitime Art und Weise ein sogenanntes bootstrapping zu machen um in einem User Homeverzeichnis eine Sammlung von Modulen zu installieren. Es erstellt auch die nötigen Umgebungsvariablen die benötigt werden um diese Module zu nutzen, passend zu der Shell die der User in der Umgebungsvariable C angegeben hat, um dann direkt passend in die entsprechenden Konfigurationsdateien der Shell einfügt zu werden. Weitergehend ist local::lib in der Lage Module zu nutzen die nicht im standardmäßigen C<@INC> Pfad von Perl enthalten sind. Das macht es einfacher für bestimmte Applikationen ein bestimmtes Set von Modulen zu installieren ohne die anderen Module auf dem System in irgendeiner Art anzufassen. Damit es z.B. auch sicherer Module zu installieren die vom Maintainer noch nicht als Release verfügbar sind. Beim Import setzt local::lib die folgenden Umgebungsvariablen zu den nötigen Werten: =over 4 =item PERL_MB_OPT =item PERL_MM_OPT =item PERL5LIB =item PATH Am PATH wird natürlich angehangen, und nicht ersetzt. =back Diese Werte sind dann verfügbar für jeden Code der danach importiert wurde. =head1 ERSTELLEN EINES EIGENSTÄNDIGE SAMMLUNG VON MODULEN Mit L besteht eine Möglichkeit dieses zutun, aber beachte das hier eine Menge von Fallstricken und Problemen existieren, und man sollte immer darauf achten das man auf einem Perl aufbaut was sowenig wie möglich verändert wurde (d.h. site und vendor Verzeichnis so leer wie möglich). =head1 METHODEN =head2 ensure_dir_structure_for =over 4 =item Parameter: $path =item Rückgabewert: Keiner =back Versucht den angegebenen Pfad anzulegen, mit allen nötigen drüberliegenden Verzeichnissen. Im Fehlerfall wird eine Exception geworfen. =head2 print_environment_vars_for =over 4 =item Parameter: $pfad =item Rückgabewert: Keiner =back Gibt die Umgebungsvariablen aus, die benötigt werden um den angegebenen Pfad als Basis Verzeichnis zu nutzen. =head2 build_environment_vars_for =over 4 =item Parameter: $pfad, $interpolate =item Rückgabewert: \%umgebungs_variablen =back Gibt ein Hash zurück mit den Variablen die nötig sind in den Umgebungsvariablen um eine Installation in dem gegebenen Pfad zu benutzen. =head2 setup_env_hash_for =over 4 =item Parameter: $pfad =item Rückgabewert: Keiner =back Setzt die C<%ENV> Einträge basierend auf dem Aufruf von L. =head2 install_base_perl_path =over 4 =item Parameter: $pfad =item Rückgabewert: $module_installations_pfad =back Gibt den Pfad zurück der benutzt wird um Perl Module zu installieren bei dem gegebenen Pfad als Basis. Prinzipiell wird nur C und C als Pfadelemente angehangen. =head2 install_base_arch_path =over 4 =item Parameter: $pfad =item Rückgabewert: $architektur_module_installations_pfad =back Gibt den Pfad zurück der benutzt wird um die Architektur-abhängigen Perl Module zu installieren basirend auf dem angegebenen Pfad als Basis. Basierend auf dem was L zurückgibt, and appends the value of C<$Config{archname}>.asis. =head2 install_base_bin_path =over 4 =item Parameter: $pfad =item Rückgabewert: $ausfuehrbare_programme_installations_pfad =back Gibt den Pfad zurück, wo ausführbare Programme installiert werden, basierend auf der Basis des angegebenen Pfad. Basierend auf L Rückgabewert, hängt diese Methode noch C an. =head2 resolve_empty_path =over 4 =item Parameter: $pfad =item Rückgabewert: $basis_pfad =back Erstellt und gibt zurück den Pfad der benutzt wird als Basis zur Installation der Module. Standardmäßig dies ist C<~/perl5>. =head2 resolve_home_path( $path ) =over 4 =item Parameter: $pfad =item Rückgabewert: $home =back Versucht das Home Verzeichnis vom aktullen User zu finden. Es wird eine Exception geworfen, wenn kein Home Verzeichnis ermittelt werden konnte. =head2 resolve_relative_path =over 4 =item Parameter: $pfad =item Rückgabewert: $absoluter_pfad =back Macht aus dem angegebenen Pfad einen absoluten Pfad. =head2 resolve_path =over 4 =item Parameter: $pfad =item Rückgabewert: $absoluter_pfad =back Hierbei wird der Pfad durch die folgende Methoden gegeben, wobei der Rückgabewert der ersten an die nächste weitergeben wird, um die Umgebung zu konfigurieren für die lokale Bibliotheks Installation: L, L, L. Der daraus resultierende Pfad wird zu L übergeben, dessen Resultat dann weitergegeben wird an L, wessen Resultat dann weitergegeben wird an L. Dieses Resultat wird dann final an L übergeben, welches dann den Rückgabewert stellt. =head1 EINE WARNUNG VOR UNINST=1 Wenn man local::lib in Kombination mit "make install UNINST=1" benutzt, muss man vorsichtig sein über die Tatsache das der Prozess über die Neuinstallation eine nicht ausreichende Sicherheit hat bezüglich wo er nun installieren muss. Hierdurch mann es passieren das beim deinstallieren eines Modul u.U. das globale Modul deinstalliert wird (wenn die Rechte vorhanden sind) aber die neue Version nur in der lokalen Version installiert ist. Es ist hier also sehr wichtig das man "make install UNINST=1" und local::lib nur gleichzeitig benutzt wenn man sehr sicher darüber ist welche Konsequenzen einem entgegenkommen. =head1 EINSCHRÄNKUNGEN Die Werkzeuge von perl, die benutzt werden um die Pakete zu installieren (die sogenannte toolchain), sind leider nicht in der Lage sauber mit Verzeichnissen umzugehen die Leerzeichen enthalten und können daher local::lib nicht direkt in ein solches Verzeichnis installieren. Was du machen kannst ist B der Installation von local::lib und der Module die du in deiner local::lib haben willst, das gesamte Verzeichnis dahin zu bewegen. local::lib kann mit dem Verzeichnis mit Leerzeichen umgehen. Bitte aufpassen das natürlich eine weitere Installation oder ein Erneuern von Paketen mit dem CPAN Programm nicht mehr möglich ist. Die Shell Erkennung ist sehr primitiv. Derzeit ist es so das alles was "csh" im Namen hat auch als C Shell eingeordnet wird, und alles andere wird als Bourne Shell betrachet, ausser auf Win32 Systemen. Wenn die C Variable nicht gesetzt ist, eine Bourne Shell wird angenommen. Bootstrap ist leider ein Hack, und wird auf jedenfall CPAN.pm benutzen für ExtUtils::MakeMaker, auch wenn CPANPLUS installiert ist. Es setzt definitiv PERL5LIB, PERL_MM_OPT und PERL_MB_OPT neu und vernichtet jeden Wert der vorher gesetzt war. Es sollte vielleicht eine automatische Korrektur der CPAN Config machen, wenn das nicht schon gemacht wurde. "Patches Welcome" - Patches sind immer willkommen beim Autor oder den anderen Mitwirkenden. Auf Win32 Systemen werden die Umgebungsvariablen nicht direkt in die Registrierung geschrieben damit sie auch nach dem Neustarten erhalten bleiben. =head1 FEHLERANALYSE Wenn du local::lib konfiguriert hast CPAN Module in deinem Home Verzeichnis zu installieren, und du danach versuchst mit C ein Modul zu installieren, und dabei einen Fehler bekommst, wie: C und in der installationsausgabe steht irgendwo ein Fehler der sagt C<'INSTALL_BASE' is not a known MakeMaker parameter name>, dann hast du aus irgendeinem Grund dein neue Version von ExtUtils::MakeMaker verloren. Um dies zu korrigieren, einfach nochmal die bootstrapping Methode laufen lassen, wie oben beschrieben. Dann starte C Abschliessend dann nochmal mit C installieren und die Probleme sollten verschwunden sein. =head1 UMGEBUNGSVARIABLEN =over 4 =item SHELL =item COMSPEC local::lib schaut in die C Umgebungsvariable um die korrekten Kommandos zu der Shell Konfiguration hinzuzufügen. Auf Win32 Systemen, C wird auch analysiert. =back =head1 SUPPORT IRC: Wir sind im Channel #local-lib auf dem Server irc.perl.org. =head1 AUTOR DER ÜBERSETZUNG Torsten Raudssus http://www.raudssus.de/ =head1 URHEBERRECHT Copyright (c) 2007 - 2010 von den local::lib L und L aufgelistet in L. =head1 LIZENZ Diese Sammlung ist freie Software und kann unter der selben Lizenz verbreitet werden wie Perl selber. =cut 1; PK!çÚ® /"/"perl5/Types/Serialiser.pmnuÏÃ6Ç$=head1 NAME Types::Serialiser - simple data types for common serialisation formats =encoding utf-8 =head1 SYNOPSIS =head1 DESCRIPTION This module provides some extra datatypes that are used by common serialisation formats such as JSON or CBOR. The idea is to have a repository of simple/small constants and containers that can be shared by different implementations so they become interoperable between each other. =cut package Types::Serialiser; use common::sense; # required to suppress annoying warnings our $VERSION = '1.0'; =head1 SIMPLE SCALAR CONSTANTS Simple scalar constants are values that are overloaded to act like simple Perl values, but have (class) type to differentiate them from normal Perl scalars. This is necessary because these have different representations in the serialisation formats. =head2 BOOLEANS (Types::Serialiser::Boolean class) This type has only two instances, true and false. A natural representation for these in Perl is C<1> and C<0>, but serialisation formats need to be able to differentiate between them and mere numbers. =over 4 =item $Types::Serialiser::true, Types::Serialiser::true This value represents the "true" value. In most contexts is acts like the number C<1>. It is up to you whether you use the variable form (C<$Types::Serialiser::true>) or the constant form (C). The constant is represented as a reference to a scalar containing C<1> - implementations are allowed to directly test for this. =item $Types::Serialiser::false, Types::Serialiser::false This value represents the "false" value. In most contexts is acts like the number C<0>. It is up to you whether you use the variable form (C<$Types::Serialiser::false>) or the constant form (C). The constant is represented as a reference to a scalar containing C<0> - implementations are allowed to directly test for this. =item $is_bool = Types::Serialiser::is_bool $value Returns true iff the C<$value> is either C<$Types::Serialiser::true> or C<$Types::Serialiser::false>. For example, you could differentiate between a perl true value and a C by using this: $value && Types::Serialiser::is_bool $value =item $is_true = Types::Serialiser::is_true $value Returns true iff C<$value> is C<$Types::Serialiser::true>. =item $is_false = Types::Serialiser::is_false $value Returns false iff C<$value> is C<$Types::Serialiser::false>. =back =head2 ERROR (Types::Serialiser::Error class) This class has only a single instance, C. It is used to signal an encoding or decoding error. In CBOR for example, and object that couldn't be encoded will be represented by a CBOR undefined value, which is represented by the error value in Perl. =over 4 =item $Types::Serialiser::error, Types::Serialiser::error This value represents the "error" value. Accessing values of this type will throw an exception. The constant is represented as a reference to a scalar containing C - implementations are allowed to directly test for this. =item $is_error = Types::Serialiser::is_error $value Returns false iff C<$value> is C<$Types::Serialiser::error>. =back =cut BEGIN { # for historical reasons, and to avoid extra dependencies in JSON::PP, # we alias *Types::Serialiser::Boolean with JSON::PP::Boolean. package JSON::PP::Boolean; *Types::Serialiser::Boolean:: = *JSON::PP::Boolean::; } { # this must done before blessing to work around bugs # in perl < 5.18 (it seems to be fixed in 5.18). package Types::Serialiser::BooleanBase; use overload "0+" => sub { ${$_[0]} }, "++" => sub { $_[0] = ${$_[0]} + 1 }, "--" => sub { $_[0] = ${$_[0]} - 1 }, fallback => 1; @Types::Serialiser::Boolean::ISA = Types::Serialiser::BooleanBase::; } our $true = do { bless \(my $dummy = 1), Types::Serialiser::Boolean:: }; our $false = do { bless \(my $dummy = 0), Types::Serialiser::Boolean:: }; our $error = do { bless \(my $dummy ), Types::Serialiser::Error:: }; sub true () { $true } sub false () { $false } sub error () { $error } sub is_bool ($) { UNIVERSAL::isa $_[0], Types::Serialiser::Boolean:: } sub is_true ($) { $_[0] && UNIVERSAL::isa $_[0], Types::Serialiser::Boolean:: } sub is_false ($) { !$_[0] && UNIVERSAL::isa $_[0], Types::Serialiser::Boolean:: } sub is_error ($) { UNIVERSAL::isa $_[0], Types::Serialiser::Error:: } package Types::Serialiser::Error; sub error { require Carp; Carp::croak ("caught attempt to use the Types::Serialiser::error value"); }; use overload "0+" => \&error, "++" => \&error, "--" => \&error, fallback => 1; =head1 NOTES FOR XS USERS The recommended way to detect whether a scalar is one of these objects is to check whether the stash is the C or C stash, and then follow the scalar reference to see if it's C<1> (true), C<0> (false) or C (error). While it is possible to use an isa test, directly comparing stash pointers is faster and guaranteed to work. For historical reasons, the C stash is just an alias for C. When printed, the classname with usually be C, but isa tests and stash pointer comparison will normally work correctly (i.e. Types::Serialiser::true ISA JSON::PP::Boolean, but also ISA Types::Serialiser::Boolean). =head1 A GENERIC OBJECT SERIALIATION PROTOCOL This section explains the object serialisation protocol used by L. It is meant to be generic enough to support any kind of generic object serialiser. This protocol is called "the Types::Serialiser object serialisation protocol". =head2 ENCODING When the encoder encounters an object that it cannot otherwise encode (for example, L can encode a few special types itself, and will first attempt to use the special C serialisation protocol), it will look up the C method on the object. Note that the C method will normally be called I encoding, and I change the data structure that is being encoded in any way, or it might cause memory corruption or worse. If it exists, it will call it with two arguments: the object to serialise, and a constant string that indicates the name of the data model. For example L uses C, and the L and L modules (or any other JSON serialiser), would use C as second argument. The C method can then return zero or more values to identify the object instance. The serialiser is then supposed to encode the class name and all of these return values (which must be encodable in the format) using the relevant form for Perl objects. In CBOR for example, there is a registered tag number for encoded perl objects. The values that C returns must be serialisable with the serialiser that calls it. Therefore, it is recommended to use simple types such as strings and numbers, and maybe array references and hashes (basically, the JSON data model). You can always use a more complex format for a specific data model by checking the second argument, the data model. The "data model" is not the same as the "data format" - the data model indicates what types and kinds of return values can be returned from C. For example, in C it is permissible to return tagged CBOR values, while JSON does not support these at all, so C would be a valid (but too limited) data model name for C. similarly, a serialising format that supports more or less the same data model as JSON could use C as data model without losing anything. =head2 DECODING When the decoder then encounters such an encoded perl object, it should look up the C method on the stored classname, and invoke it with the classname, the constant string to identify the data model/data format, and all the return values returned by C. =head2 EXAMPLES See the C section in the L manpage for more details, an example implementation, and code examples. Here is an example C/C method pair: sub My::Object::FREEZE { my ($self, $model) = @_; ($self->{type}, $self->{id}, $self->{variant}) } sub My::Object::THAW { my ($class, $model, $type, $id, $variant) = @_; $class->new (type => $type, id => $id, variant => $variant) } =head1 BUGS The use of L makes this module much heavier than it should be (on my system, this module: 4kB RSS, overload: 260kB RSS). =head1 SEE ALSO Currently, L and L use these types. =head1 AUTHOR Marc Lehmann http://home.schmorp.de/ =cut 1 PK!²Wy­ÃÃperl5/Types/Serialiser/Error.pmnuÏÃ6Ç$=head1 NAME Types::Serialiser::Error - dummy module for Types::Serialiser =head1 SYNOPSIS # do not "use" yourself =head1 DESCRIPTION This module exists only to provide overload resolution for Storable and similar modules that assume that class name equals module name. See L for more info about this class. =cut use Types::Serialiser (); =head1 AUTHOR Marc Lehmann http://home.schmorp.de/ =cut 1 PK!ŸûŸyyperl5/HTML/Parse.pmnuÏÃ6Ç$package HTML::Parse; use 5.008; #ABSTRACT: Deprecated, a wrapper around HTML::TreeBuilder use warnings; use strict; our $VERSION = '5.07'; # VERSION from OurPkgVersion use vars qw(@ISA @EXPORT $IMPLICIT_TAGS $IGNORE_UNKNOWN $IGNORE_TEXT $WARN ); require Exporter; @ISA = qw(Exporter); @EXPORT = qw(parse_html parse_htmlfile); # Backwards compatability $IMPLICIT_TAGS = 1; $IGNORE_UNKNOWN = 1; $IGNORE_TEXT = 0; $WARN = 0; require HTML::TreeBuilder; sub parse_html { my $p = $_[1]; $p = _new_tree_maker() unless $p; $p->parse( $_[0] ); } sub parse_htmlfile { my ( $file, $p ) = @_; my ($HTML); open( $HTML, "<", $file ) or return; $p = _new_tree_maker() unless $p; $p->parse_file($HTML); } sub _new_tree_maker { my $p = HTML::TreeBuilder->new( implicit_tags => $IMPLICIT_TAGS, ignore_unknown => $IGNORE_UNKNOWN, ignore_text => $IGNORE_TEXT, 'warn' => $WARN, ); $p->strict_comment(1); $p; } 1; __END__ =pod =head1 NAME HTML::Parse - Deprecated, a wrapper around HTML::TreeBuilder =head1 VERSION This document describes version 5.07 of HTML::Parse, released August 31, 2017 as part of L. =head1 SYNOPSIS See the documentation for HTML::TreeBuilder =head1 DESCRIPTION Disclaimer: This module is provided only for backwards compatibility with earlier versions of this library. New code should I use this module, and should really use the HTML::Parser and HTML::TreeBuilder modules directly, instead. The C module provides functions to parse HTML documents. There are two functions exported by this module: =over 4 =item parse_html($html) or parse_html($html, $obj) This function is really just a synonym for $obj->parse($html) and $obj is assumed to be a subclass of C. Refer to L for more documentation. If $obj is not specified, the $obj will default to an internally created new C object configured with strict_comment() turned on. That class implements a parser that builds (and is) a HTML syntax tree with HTML::Element objects as nodes. The return value from parse_html() is $obj. =item parse_htmlfile($file, [$obj]) Same as parse_html(), but pulls the HTML to parse, from the named file. Returns C if the file could not be opened, or $obj otherwise. =back When a C object is created, the following variables control how parsing takes place: =over 4 =item $HTML::Parse::IMPLICIT_TAGS Setting this variable to true will instruct the parser to try to deduce implicit elements and implicit end tags. If this variable is false you get a parse tree that just reflects the text as it stands. Might be useful for quick & dirty parsing. Default is true. Implicit elements have the implicit() attribute set. =item $HTML::Parse::IGNORE_UNKNOWN This variable contols whether unknow tags should be represented as elements in the parse tree. Default is true. =item $HTML::Parse::IGNORE_TEXT Do not represent the text content of elements. This saves space if all you want is to examine the structure of the document. Default is false. =item $HTML::Parse::WARN Call warn() with an appropriate message for syntax errors. Default is false. =back =head1 REMEMBER! HTML::TreeBuilder objects should be explicitly destroyed when you're finished with them. See L. =head1 SEE ALSO L, L, L =head1 AUTHOR Current maintainers: =over =item * Christopher J. Madsen S >>> =item * Jeff Fearn S >>> =back Original HTML-Tree author: =over =item * Gisle Aas =back Former maintainers: =over =item * Sean M. Burke =item * Andy Lester =item * Pete Krawczyk S >>> =back You can follow or contribute to HTML-Tree's development at L<< https://github.com/kentfredric/HTML-Tree >>. =head1 COPYRIGHT AND LICENSE Copyright 1995-1998 Gisle Aas, 1999-2004 Sean M. Burke, 2005 Andy Lester, 2006 Pete Krawczyk, 2010 Jeff Fearn, 2012 Christopher J. Madsen. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The programs in this library are distributed in the hope that they will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. =cut PK!ÞCôˆžžperl5/HTML/Tree.pmnuÏÃ6Ç$package HTML::Tree; # ABSTRACT: build and scan parse-trees of HTML # HTML::Tree is basically just a happy alias to HTML::TreeBuilder. use warnings; use strict; our $VERSION = '5.07'; # VERSION from OurPkgVersion use HTML::TreeBuilder (); sub new { shift; unshift @_, 'HTML::TreeBuilder'; goto &HTML::TreeBuilder::new; } sub new_from_file { shift; unshift @_, 'HTML::TreeBuilder'; goto &HTML::TreeBuilder::new_from_file; } sub new_from_content { shift; unshift @_, 'HTML::TreeBuilder'; goto &HTML::TreeBuilder::new_from_content; } sub new_from_url { shift; unshift @_, 'HTML::TreeBuilder'; goto &HTML::TreeBuilder::new_from_url; } 1; __END__ =pod =head1 NAME HTML::Tree - build and scan parse-trees of HTML =head1 VERSION This document describes version 5.07 of HTML::Tree, released August 31, 2017 as part of L. =head1 SYNOPSIS use HTML::TreeBuilder; my $tree = HTML::TreeBuilder->new(); $tree->parse_file($filename); # Then do something with the tree, using HTML::Element # methods -- for example: $tree->dump # Finally: $tree->delete; =head1 DESCRIPTION HTML-Tree is a suite of Perl modules for making parse trees out of HTML source. It consists of mainly two modules, whose documentation you should refer to: L and L. HTML::TreeBuilder is the module that builds the parse trees. (It uses HTML::Parser to do the work of breaking the HTML up into tokens.) The tree that TreeBuilder builds for you is made up of objects of the class HTML::Element. If you find that you do not properly understand the documentation for HTML::TreeBuilder and HTML::Element, it may be because you are unfamiliar with tree-shaped data structures, or with object-oriented modules in general. Sean Burke has written some articles for I (C) that seek to provide that background. The full text of those articles is contained in this distribution, as: =over 4 =item L "User's View of Object-Oriented Modules" from TPJ17. =item L "Trees" from TPJ18 =item L "Scanning HTML" from TPJ19 =back Readers already familiar with object-oriented modules and tree-shaped data structures should read just the last article. Readers without that background should read the first, then the second, and then the third. =head1 METHODS All these methods simply redirect to the corresponding method in HTML::TreeBuilder. It's more efficient to use HTML::TreeBuilder directly, and skip loading HTML::Tree at all. =head2 new Redirects to L. =head2 new_from_file Redirects to L. =head2 new_from_content Redirects to L. =head2 new_from_url Redirects to L. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc HTML::Tree You can also look for information at: =over 4 =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * RT: CPAN's request tracker L =item * Search CPAN L =item * Stack Overflow L If you have a question about how to use HTML-Tree, Stack Overflow is the place to ask it. Make sure you tag it both C and C. =back =head1 SEE ALSO L, L, L, L, L The book I by Sean M. Burke published by O'Reilly and Associates, 2002. ISBN: 0-596-00178-9 It has several chapters to do with HTML processing in general, and HTML-Tree specifically. There's more info at: http://www.oreilly.com/catalog/perllwp/ http://www.amazon.com/exec/obidos/ASIN/0596001789 =head1 SOURCE REPOSITORY HTML-Tree is now maintained using Git. The main public repository is L<< https://github.com/kentfredric/HTML-Tree >>. The best way to send a patch is to make a pull request there. =head1 ACKNOWLEDGEMENTS Thanks to Gisle Aas, Sean Burke and Andy Lester for their original work. Thanks to Chicago Perl Mongers (http://chicago.pm.org) for their patches submitted to HTML::Tree as part of the Phalanx project (http://qa.perl.org/phalanx). Thanks to the following people for additional patches and documentation: Terrence Brannon, Gordon Lack, Chris Madsen and Ricardo Signes. =head1 AUTHOR Current maintainers: =over =item * Christopher J. Madsen S >>> =item * Jeff Fearn S >>> =back Original HTML-Tree author: =over =item * Gisle Aas =back Former maintainers: =over =item * Sean M. Burke =item * Andy Lester =item * Pete Krawczyk S >>> =back You can follow or contribute to HTML-Tree's development at L<< https://github.com/kentfredric/HTML-Tree >>. =head1 COPYRIGHT AND LICENSE Copyright 1995-1998 Gisle Aas, 1999-2004 Sean M. Burke, 2005 Andy Lester, 2006 Pete Krawczyk, 2010 Jeff Fearn, 2012 Christopher J. Madsen. (Except the articles contained in HTML::Tree::AboutObjects, HTML::Tree::AboutTrees, and HTML::Tree::Scanning, which are all copyright 2000 The Perl Journal.) Except for those three TPJ articles, the whole HTML-Tree distribution, of which this file is a part, is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Those three TPJ articles may be distributed under the same terms as Perl itself. The programs in this library are distributed in the hope that they will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. =cut PK!a@ÊÐî'î'perl5/HTML/Element/traverse.pmnuÏÃ6Ç$ # This is a .pm just to (try to) make some CPAN document converters # convert it happily as part of the dist's documentation tree. package HTML::Element::traverse; # ABSTRACT: discussion of HTML::Element's traverse method use warnings; use strict; our $VERSION = '5.07'; # VERSION from OurPkgVersion use HTML::Element (); 1; __END__ =pod =head1 NAME HTML::Element::traverse - discussion of HTML::Element's traverse method =head1 VERSION This document describes version 5.07 of HTML::Element::traverse, released August 31, 2017 as part of L. =head1 SYNOPSIS # $element->traverse is unnecessary and obscure. # Don't use it in new code. =head1 DESCRIPTION C provides a method C that traverses the tree and calls user-specified callbacks for each node, in pre- or post-order. However, use of the method is quite superfluous: if you want to recursively visit every node in the tree, it's almost always simpler to write a subroutine does just that, than it is to bundle up the pre- and/or post-order code in callbacks for the C method. =head1 EXAMPLES Suppose you want to traverse at/under a node $tree and give elements an 'id' attribute unless they already have one. You can use the C method: { my $counter = 'x0000'; $start_node->traverse( [ # Callbacks; # pre-order callback: sub { my $x = $_[0]; $x->attr('id', $counter++) unless defined $x->attr('id'); return HTML::Element::OK; # keep traversing }, # post-order callback: undef ], 1, # don't call the callbacks for text nodes ); } or you can just be simple and clear (and not have to understand the calling format for C) by writing a sub that traverses the tree by just calling itself: { my $counter = 'x0000'; sub give_id { my $x = $_[0]; $x->attr('id', $counter++) unless defined $x->attr('id'); foreach my $c ($x->content_list) { give_id($c) if ref $c; # ignore text nodes } }; give_id($start_node); } See, isn't that nice and clear? But, if you really need to know: =head1 THE TRAVERSE METHOD The C method is a general object-method for traversing a tree or subtree and calling user-specified callbacks. It accepts the following syntaxes: =over =item $h->traverse(\&callback) =item or $h->traverse(\&callback, $ignore_text) =item or $h->traverse( [\&pre_callback,\&post_callback] , $ignore_text) =back These all mean to traverse the element and all of its children. That is, this method starts at node $h, "pre-order visits" $h, traverses its children, and then will "post-order visit" $h. "Visiting" means that the callback routine is called, with these arguments: $_[0] : the node (element or text segment), $_[1] : a startflag, and $_[2] : the depth If the $ignore_text parameter is given and true, then the pre-order call I be happen for text content. The startflag is 1 when we enter a node (i.e., in pre-order calls) and 0 when we leave the node (in post-order calls). Note, however, that post-order calls don't happen for nodes that are text segments or are elements that are prototypically empty (like "br", "hr", etc.). If we visit text nodes (i.e., unless $ignore_text is given and true), then when text nodes are visited, we will also pass two extra arguments to the callback: $_[3] : the element that's the parent of this text node $_[4] : the index of this text node in its parent's content list Note that you can specify that the pre-order routine can be a different routine from the post-order one: $h->traverse( [\&pre_callback,\&post_callback], ...); You can also specify that no post-order calls are to be made, by providing a false value as the post-order routine: $h->traverse([ \&pre_callback,0 ], ...); And similarly for suppressing pre-order callbacks: $h->traverse([ 0,\&post_callback ], ...); Note that these two syntaxes specify the same operation: $h->traverse([\&foo,\&foo], ...); $h->traverse( \&foo , ...); The return values from calls to your pre- or post-order routines are significant, and are used to control recursion into the tree. These are the values you can return, listed in descending order of my estimation of their usefulness: =over =item HTML::Element::OK, 1, or any other true value ...to keep on traversing. Note that C et al are constants. So if you're running under C (as I hope you are), and you say: C the compiler will flag this as an error (an unallowable bareword, specifically), whereas if you spell PRUNE correctly, the compiler will not complain. =item undef, 0, '0', '', or HTML::Element::PRUNE ...to block traversing under the current element's content. (This is ignored if received from a post-order callback, since by then the recursion has already happened.) If this is returned by a pre-order callback, no post-order callback for the current node will happen. (Recall that if your callback exits with just C, it is returning undef -- at least in scalar context, and C always calls your callbacks in scalar context.) =item HTML::Element::ABORT ...to abort the whole traversal immediately. This is often useful when you're looking for just the first node in the tree that meets some criterion of yours. =item HTML::Element::PRUNE_UP ...to abort continued traversal into this node and its parent node. No post-order callback for the current or parent node will happen. =item HTML::Element::PRUNE_SOFTLY Like PRUNE, except that the post-order call for the current node is not blocked. =back Almost every task to do with extracting information from a tree can be expressed in terms of traverse operations (usually in only one pass, and usually paying attention to only pre-order, or to only post-order), or operations based on traversing. (In fact, many of the other methods in this class are basically calls to traverse() with particular arguments.) The source code for HTML::Element and HTML::TreeBuilder contain several examples of the use of the "traverse" method to gather information about the content of trees and subtrees. (Note: you should not change the structure of a tree I you are traversing it.) [End of documentation for the C method] =head2 Traversing with Recursive Anonymous Routines Now, if you've been reading I too much, maybe you even want a recursive lambda. Go ahead: { my $counter = 'x0000'; my $give_id; $give_id = sub { my $x = $_[0]; $x->attr('id', $counter++) unless defined $x->attr('id'); foreach my $c ($x->content_list) { $give_id->($c) if ref $c; # ignore text nodes } }; $give_id->($start_node); undef $give_id; } It's a bit nutty, and it's I more concise than a call to the C method! It is left as an exercise to the reader to figure out how to do the same thing without using a C<$give_id> symbol at all. It is also left as an exercise to the reader to figure out why I undefine C<$give_id>, above; and why I could achieved the same effect with any of: $give_id = 'I like pie!'; # or... $give_id = []; # or even; $give_id = sub { print "Mmmm pie!\n" }; But not: $give_id = sub { print "I'm $give_id and I like pie!\n" }; # nor... $give_id = \$give_id; # nor... $give_id = { 'pie' => \$give_id, 'mode' => 'a la' }; =head2 Doing Recursive Things Iteratively Note that you may at times see an iterative implementation of pre-order traversal, like so: { my @to_do = ($tree); # start-node while(@to_do) { my $this = shift @to_do; # "Visit" the node: $this->attr('id', $counter++) unless defined $this->attr('id'); unshift @to_do, grep ref $_, $this->content_list; # Put children on the stack -- they'll be visited next } } This can I be more efficient than just a normal recursive routine, but at the cost of being rather obscure. It gains efficiency by avoiding the overhead of function-calling, but since there are several method dispatches however you do it (to C and C), the overhead for a simple function call is insignificant. =head2 Pruning and Whatnot The C method does have the fairly neat features of the C, C and C signals. None of these can be implemented I straightforwardly with recursive routines, but it is quite possible. C-like behavior can be implemented either with using non-local returning with C/C: my $died_on; # if you need to know where... sub thing { ... visits $_[0]... ... maybe set $died_on to $_[0] and die "ABORT_TRAV" ... ... else call thing($child) for each child... ...any post-order visiting $_[0]... } eval { thing($node) }; if($@) { if($@ =~ m<^ABORT_TRAV>) { ...it died (aborted) on $died_on... } else { die $@; # some REAL error happened } } or you can just do it with flags: my($abort_flag, $died_on); sub thing { ... visits $_[0]... ... maybe set $abort_flag = 1; $died_on = $_[0]; return; foreach my $c ($_[0]->content_list) { thing($c); return if $abort_flag; } ...any post-order visiting $_[0]... return; } $abort_flag = $died_on = undef; thing($node); ...if defined $abort_flag, it died on $died_on =head1 SEE ALSO L =head1 AUTHOR Current maintainers: =over =item * Christopher J. Madsen S >>> =item * Jeff Fearn S >>> =back Original HTML-Tree author: =over =item * Gisle Aas =back Former maintainers: =over =item * Sean M. Burke =item * Andy Lester =item * Pete Krawczyk S >>> =back You can follow or contribute to HTML-Tree's development at L<< https://github.com/kentfredric/HTML-Tree >>. =head1 COPYRIGHT Copyright 2000,2001 Sean M. Burke =cut PK!±�ÿHÎFÎFperl5/HTML/TreeBuilder.pmnuÏÃ6Ç$package HTML::TreeBuilder; # ABSTRACT: Parser that builds a HTML syntax tree use warnings; use strict; use integer; # vroom vroom! use Carp (); our $VERSION = '5.07'; # VERSION from OurPkgVersion #--------------------------------------------------------------------------- # Make a 'DEBUG' constant... our $DEBUG; # Must be set BEFORE loading this file BEGIN { # We used to have things like # print $indent, "lalala" if $Debug; # But there were an awful lot of having to evaluate $Debug's value. # If we make that depend on a constant, like so: # sub DEBUG () { 1 } # or whatever value. # ... # print $indent, "lalala" if DEBUG; # Which at compile-time (thru the miracle of constant folding) turns into: # print $indent, "lalala"; # or, if DEBUG is a constant with a true value, then that print statement # is simply optimized away, and doesn't appear in the target code at all. # If you don't believe me, run: # perl -MO=Deparse,-uHTML::TreeBuilder -e 'BEGIN { \ # $HTML::TreeBuilder::DEBUG = 4} use HTML::TreeBuilder' # and see for yourself (substituting whatever value you want for $DEBUG # there). ## no critic if ( defined &DEBUG ) { # Already been defined! Do nothing. } elsif ( $] < 5.00404 ) { # Grudgingly accomodate ancient (pre-constant) versions. eval 'sub DEBUG { $Debug } '; } elsif ( !$DEBUG ) { eval 'sub DEBUG () {0}'; # Make it a constant. } elsif ( $DEBUG =~ m<^\d+$>s ) { eval 'sub DEBUG () { ' . $DEBUG . ' }'; # Make THAT a constant. } else { # WTF? warn "Non-numeric value \"$DEBUG\" in \$HTML::Element::DEBUG"; eval 'sub DEBUG () { $DEBUG }'; # I guess. } ## use critic } #--------------------------------------------------------------------------- use HTML::Entities (); use HTML::Tagset 3.02 (); use HTML::Element (); use HTML::Parser 3.46 (); our @ISA = qw(HTML::Element HTML::Parser); # This looks schizoid, I know. # It's not that we ARE an element AND a parser. # We ARE an element, but one that knows how to handle signals # (method calls) from Parser in order to elaborate its subtree. # Legacy aliases: *HTML::TreeBuilder::isKnown = \%HTML::Tagset::isKnown; *HTML::TreeBuilder::canTighten = \%HTML::Tagset::canTighten; *HTML::TreeBuilder::isHeadElement = \%HTML::Tagset::isHeadElement; *HTML::TreeBuilder::isBodyElement = \%HTML::Tagset::isBodyElement; *HTML::TreeBuilder::isPhraseMarkup = \%HTML::Tagset::isPhraseMarkup; *HTML::TreeBuilder::isHeadOrBodyElement = \%HTML::Tagset::isHeadOrBodyElement; *HTML::TreeBuilder::isList = \%HTML::Tagset::isList; *HTML::TreeBuilder::isTableElement = \%HTML::Tagset::isTableElement; *HTML::TreeBuilder::isFormElement = \%HTML::Tagset::isFormElement; *HTML::TreeBuilder::p_closure_barriers = \@HTML::Tagset::p_closure_barriers; #========================================================================== # Two little shortcut constructors: sub new_from_file { # or from a FH my $class = shift; Carp::croak("new_from_file takes only one argument") unless @_ == 1; Carp::croak("new_from_file is a class method only") if ref $class; my $new = $class->new(); defined $new->parse_file( $_[0] ) or Carp::croak("unable to parse file: $!"); return $new; } sub new_from_content { # from any number of scalars my $class = shift; Carp::croak("new_from_content is a class method only") if ref $class; my $new = $class->new(); foreach my $whunk (@_) { if ( ref($whunk) eq 'SCALAR' ) { $new->parse($$whunk); } else { $new->parse($whunk); } last if $new->{'_stunted'}; # might as well check that. } $new->eof(); return $new; } sub new_from_url { # should accept anything that LWP does. undef our $lwp_response; my $class = shift; Carp::croak("new_from_url takes only one argument") unless @_ == 1; Carp::croak("new_from_url is a class method only") if ref $class; my $url = shift; my $new = $class->new(); require LWP::UserAgent; # RECOMMEND PREREQ: LWP::UserAgent 5.815 LWP::UserAgent->VERSION( 5.815 ); # HTTP::Headers content_is_html method $lwp_response = LWP::UserAgent->new->get( $url ); Carp::croak("GET failed on $url: " . $lwp_response->status_line) unless $lwp_response->is_success; Carp::croak("$url returned " . $lwp_response->content_type . " not HTML") unless $lwp_response->content_is_html; $new->parse( $lwp_response->decoded_content ); $new->eof; undef $lwp_response; # Processed successfully return $new; } # TODO: document more fully? sub parse_content { # from any number of scalars my $tree = shift; my $retval; foreach my $whunk (@_) { if ( ref($whunk) eq 'SCALAR' ) { $retval = $tree->parse($$whunk); } else { $retval = $tree->parse($whunk); } last if $tree->{'_stunted'}; # might as well check that. } $tree->eof(); return $retval; } #--------------------------------------------------------------------------- sub new { # constructor! my $class = shift; $class = ref($class) || $class; # Initialize HTML::Element part my $self = $class->element_class->new('html'); { # A hack for certain strange versions of Parser: my $other_self = HTML::Parser->new(); %$self = ( %$self, %$other_self ); # copy fields # Yes, multiple inheritance is messy. Kids, don't try this at home. bless $other_self, "HTML::TreeBuilder::_hideyhole"; # whack it out of the HTML::Parser class, to avoid the destructor } # The root of the tree is special, as it has these funny attributes, # and gets reblessed into this class. # Initialize parser settings $self->{'_implicit_tags'} = 1; $self->{'_implicit_body_p_tag'} = 0; # If true, trying to insert text, or any of %isPhraseMarkup right # under 'body' will implicate a 'p'. If false, will just go there. $self->{'_tighten'} = 1; # whether ignorable WS in this tree should be deleted $self->{'_implicit'} = 1; # to delete, once we find a real open-"html" tag $self->{'_ignore_unknown'} = 1; $self->{'_ignore_text'} = 0; $self->{'_warn'} = 0; $self->{'_no_space_compacting'} = 0; $self->{'_store_comments'} = 0; $self->{'_store_declarations'} = 1; $self->{'_store_pis'} = 0; $self->{'_p_strict'} = 0; $self->{'_no_expand_entities'} = 0; # Parse attributes passed in as arguments if (@_) { my %attr = @_; for ( keys %attr ) { $self->{"_$_"} = $attr{$_}; } } $HTML::Element::encoded_content = $self->{'_no_expand_entities'}; # rebless to our class bless $self, $class; $self->{'_element_count'} = 1; # undocumented, informal, and maybe not exactly correct $self->{'_head'} = $self->insert_element( 'head', 1 ); $self->{'_pos'} = undef; # pull it back up $self->{'_body'} = $self->insert_element( 'body', 1 ); $self->{'_pos'} = undef; # pull it back up again return $self; } #========================================================================== sub _elem # universal accessor... { my ( $self, $elem, $val ) = @_; my $old = $self->{$elem}; $self->{$elem} = $val if defined $val; return $old; } # accessors.... sub implicit_tags { shift->_elem( '_implicit_tags', @_ ); } sub implicit_body_p_tag { shift->_elem( '_implicit_body_p_tag', @_ ); } sub p_strict { shift->_elem( '_p_strict', @_ ); } sub no_space_compacting { shift->_elem( '_no_space_compacting', @_ ); } sub ignore_unknown { shift->_elem( '_ignore_unknown', @_ ); } sub ignore_text { shift->_elem( '_ignore_text', @_ ); } sub ignore_ignorable_whitespace { shift->_elem( '_tighten', @_ ); } sub store_comments { shift->_elem( '_store_comments', @_ ); } sub store_declarations { shift->_elem( '_store_declarations', @_ ); } sub store_pis { shift->_elem( '_store_pis', @_ ); } sub warn { shift->_elem( '_warn', @_ ); } sub no_expand_entities { shift->_elem( '_no_expand_entities', @_ ); $HTML::Element::encoded_content = @_; } #========================================================================== sub warning { my $self = shift; CORE::warn("HTML::Parse: $_[0]\n") if $self->{'_warn'}; # should maybe say HTML::TreeBuilder instead } #========================================================================== { # To avoid having to rebuild these lists constantly... my $_Closed_by_structurals = [qw(p h1 h2 h3 h4 h5 h6 pre textarea)]; my $indent; sub start { return if $_[0]{'_stunted'}; # Accept a signal from HTML::Parser for start-tags. my ( $self, $tag, $attr ) = @_; # Parser passes more, actually: # $self->start($tag, $attr, $attrseq, $origtext) # But we can merrily ignore $attrseq and $origtext. if ( $tag eq 'x-html' ) { print "Ignoring open-x-html tag.\n" if DEBUG; # inserted by some lame code-generators. return; # bypass tweaking. } $tag =~ s{/$}{}s; # So turns into . Silently forgive. unless ( $tag =~ m/^[-_a-zA-Z0-9:%]+$/s ) { DEBUG and print "Start-tag name $tag is no good. Skipping.\n"; return; # This avoids having Element's new() throw an exception. } my $ptag = ( my $pos = $self->{'_pos'} || $self )->{'_tag'}; my $already_inserted; #my($indent); if (DEBUG) { # optimization -- don't figure out indenting unless we're in debug mode my @lineage = $pos->lineage; $indent = ' ' x ( 1 + @lineage ); print $indent, "Proposing a new \U$tag\E under ", join( '/', map $_->{'_tag'}, reverse( $pos, @lineage ) ) || 'Root', ".\n"; #} else { # $indent = ' '; } #print $indent, "POS: $pos ($ptag)\n" if DEBUG > 2; # $attr = {%$attr}; foreach my $k ( keys %$attr ) { # Make sure some stooge doesn't have "". # That happens every few million Web pages. $attr->{ ' ' . $k } = delete $attr->{$k} if length $k and substr( $k, 0, 1 ) eq '_'; # Looks bad, but is fine for round-tripping. } my $e = $self->element_class->new( $tag, %$attr ); # Make a new element object. # (Only rarely do we end up just throwing it away later in this call.) # Some prep -- custom messiness for those damned tables, and strict P's. if ( $self->{'_implicit_tags'} ) { # wallawallawalla! unless ( $HTML::TreeBuilder::isTableElement{$tag} ) { if ( $ptag eq 'table' ) { print $indent, " * Phrasal \U$tag\E right under TABLE makes implicit TR and TD\n" if DEBUG > 1; $self->insert_element( 'tr', 1 ); $pos = $self->insert_element( 'td', 1 ) ; # yes, needs updating } elsif ( $ptag eq 'tr' ) { print $indent, " * Phrasal \U$tag\E right under TR makes an implicit TD\n" if DEBUG > 1; $pos = $self->insert_element( 'td', 1 ) ; # yes, needs updating } $ptag = $pos->{'_tag'}; # yes, needs updating } # end of table-implication block. # Now maybe do a little dance to enforce P-strictness. # This seems like it should be integrated with the big # "ALL HOPE..." block, further below, but that doesn't # seem feasable. if ( $self->{'_p_strict'} and $HTML::TreeBuilder::isKnown{$tag} and not $HTML::Tagset::is_Possible_Strict_P_Content{$tag} ) { my $here = $pos; my $here_tag = $ptag; while (1) { if ( $here_tag eq 'p' ) { print $indent, " * Inserting $tag closes strict P.\n" if DEBUG > 1; $self->end( \q{p} ); # NB: same as \'q', but less confusing to emacs cperl-mode last; } #print("Lasting from $here_tag\n"), last if $HTML::TreeBuilder::isKnown{$here_tag} and not $HTML::Tagset::is_Possible_Strict_P_Content{ $here_tag}; # Don't keep looking up the tree if we see something that can't # be strict-P content. $here_tag = ( $here = $here->{'_parent'} || last )->{'_tag'}; } # end while $ptag = ( $pos = $self->{'_pos'} || $self ) ->{'_tag'}; # better update! } # end of strict-p block. } # And now, get busy... #---------------------------------------------------------------------- if ( !$self->{'_implicit_tags'} ) { # bimskalabim # do nothing print $indent, " * _implicit_tags is off. doing nothing\n" if DEBUG > 1; #---------------------------------------------------------------------- } elsif ( $HTML::TreeBuilder::isHeadOrBodyElement{$tag} ) { if ( $pos->is_inside('body') ) { # all is well print $indent, " * ambilocal element \U$tag\E is fine under BODY.\n" if DEBUG > 1; } elsif ( $pos->is_inside('head') ) { print $indent, " * ambilocal element \U$tag\E is fine under HEAD.\n" if DEBUG > 1; } else { # In neither head nor body! mmmmm... put under head? if ( $ptag eq 'html' ) { # expected case # TODO?? : would there ever be a case where _head would be # absent from a tree that would ever be accessed at this # point? die "Where'd my head go?" unless ref $self->{'_head'}; if ( $self->{'_head'}{'_implicit'} ) { print $indent, " * ambilocal element \U$tag\E makes an implicit HEAD.\n" if DEBUG > 1; # or rather, points us at it. $self->{'_pos'} = $self->{'_head'}; # to insert under... } else { $self->warning( "Ambilocal element <$tag> not under HEAD or BODY!?" ); # Put it under HEAD by default, I guess $self->{'_pos'} = $self->{'_head'}; # to insert under... } } else { # Neither under head nor body, nor right under html... pass thru? $self->warning( "Ambilocal element <$tag> neither under head nor body, nor right under html!?" ); } } #---------------------------------------------------------------------- } elsif ( $HTML::TreeBuilder::isBodyElement{$tag} ) { # Ensure that we are within if ( $ptag eq 'body' ) { # We're good. } elsif ( $HTML::TreeBuilder::isBodyElement{$ptag} # glarg and not $HTML::TreeBuilder::isHeadOrBodyElement{$ptag} ) { # Special case: Save ourselves a call to is_inside further down. # If our $ptag is an isBodyElement element (but not an # isHeadOrBodyElement element), then we must be under body! print $indent, " * Inferring that $ptag is under BODY.\n", if DEBUG > 3; # I think this and the test for 'body' trap everything # bodyworthy, except the case where the parent element is # under an unknown element that's a descendant of body. } elsif ( $pos->is_inside('head') ) { print $indent, " * body-element \U$tag\E minimizes HEAD, makes implicit BODY.\n" if DEBUG > 1; $ptag = ( $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating || die "Where'd my body go?" )->{'_tag'}; # yes, needs updating } elsif ( !$pos->is_inside('body') ) { print $indent, " * body-element \U$tag\E makes implicit BODY.\n" if DEBUG > 1; $ptag = ( $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating || die "Where'd my body go?" )->{'_tag'}; # yes, needs updating } # else we ARE under body, so okay. # Handle implicit endings and insert based on and position # ... ALL HOPE ABANDON ALL YE WHO ENTER HERE ... if ( $tag eq 'p' or $tag eq 'h1' or $tag eq 'h2' or $tag eq 'h3' or $tag eq 'h4' or $tag eq 'h5' or $tag eq 'h6' or $tag eq 'form' # Hm, should really be here?! ) { # Can't have

, or inside these $self->end( $_Closed_by_structurals, @HTML::TreeBuilder::p_closure_barriers # used to be just li! ); } elsif ( $tag eq 'ol' or $tag eq 'ul' or $tag eq 'dl' ) { # Can't have lists inside -- in the unlikely # event anyone tries to put them there! if ( $ptag eq 'h1' or $ptag eq 'h2' or $ptag eq 'h3' or $ptag eq 'h4' or $ptag eq 'h5' or $ptag eq 'h6' ) { $self->end( \$ptag ); } # TODO: Maybe keep closing up the tree until # the ptag isn't any of the above? # But anyone that says