PK!ɋ8/8/man/man1/cpan.1nu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN 1" .TH CPAN 1 "2022-04-03" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" cpan \- easily interact with CPAN from the command line .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& # with arguments and no switches, installs specified modules \& cpan module_name [ module_name ... ] \& \& # with switches, installs modules with extra behavior \& cpan [\-cfFimtTw] module_name [ module_name ... ] \& \& # use local::lib \& cpan \-I module_name [ module_name ... ] \& \& # one time mirror override for faster mirrors \& cpan \-p ... \& \& # with just the dot, install from the distribution in the \& # current directory \& cpan . \& \& # without arguments, starts CPAN.pm shell \& cpan \& \& # without arguments, but some switches \& cpan [\-ahpruvACDLOPX] .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This script provides a command interface (not a shell) to \s-1CPAN.\s0 At the moment it uses \s-1CPAN\s0.pm to do the work, but it is not a one-shot command runner for \s-1CPAN\s0.pm. .SS "Options" .IX Subsection "Options" .IP "\-a" 4 .IX Item "-a" Creates a \s-1CPAN\s0.pm autobundle with CPAN::Shell\->autobundle. .IP "\-A module [ module ... ]" 4 .IX Item "-A module [ module ... ]" Shows the primary maintainers for the specified modules. .IP "\-c module" 4 .IX Item "-c module" Runs a `make clean` in the specified module's directories. .IP "\-C module [ module ... ]" 4 .IX Item "-C module [ module ... ]" Show the \fIChanges\fR files for the specified modules .IP "\-D module [ module ... ]" 4 .IX Item "-D module [ module ... ]" Show the module details. This prints one line for each out-of-date module (meaning, modules locally installed but have newer versions on \s-1CPAN\s0). Each line has three columns: module name, local version, and \s-1CPAN\s0 version. .IP "\-f" 4 .IX Item "-f" Force the specified action, when it normally would have failed. Use this to install a module even if its tests fail. When you use this option, \&\-i is not optional for installing a module when you need to force it: .Sp .Vb 1 \& % cpan \-f \-i Module::Foo .Ve .IP "\-F" 4 .IX Item "-F" Turn off \s-1CPAN\s0.pm's attempts to lock anything. You should be careful with this since you might end up with multiple scripts trying to muck in the same directory. This isn't so much of a concern if you're loading a special config with \f(CW\*(C`\-j\*(C'\fR, and that config sets up its own work directories. .IP "\-g module [ module ... ]" 4 .IX Item "-g module [ module ... ]" Downloads to the current directory the latest distribution of the module. .IP "\-G module [ module ... ]" 4 .IX Item "-G module [ module ... ]" \&\s-1UNIMPLEMENTED\s0 .Sp Download to the current directory the latest distribution of the modules, unpack each distribution, and create a git repository for each distribution. .Sp If you want this feature, check out Yanick Champoux's \f(CW\*(C`Git::CPAN::Patch\*(C'\fR distribution. .IP "\-h" 4 .IX Item "-h" Print a help message and exit. When you specify \f(CW\*(C`\-h\*(C'\fR, it ignores all of the other options and arguments. .IP "\-i module [ module ... ]" 4 .IX Item "-i module [ module ... ]" Install the specified modules. With no other switches, this switch is implied. .IP "\-I" 4 .IX Item "-I" Load \f(CW\*(C`local::lib\*(C'\fR (think like \f(CW\*(C`\-I\*(C'\fR for loading lib paths). Too bad \&\f(CW\*(C`\-l\*(C'\fR was already taken. .IP "\-j Config.pm" 4 .IX Item "-j Config.pm" Load the file that has the \s-1CPAN\s0 configuration data. This should have the same format as the standard \fICPAN/Config.pm\fR file, which defines \&\f(CW$CPAN::Config\fR as an anonymous hash. .IP "\-J" 4 .IX Item "-J" Dump the configuration in the same format that \s-1CPAN\s0.pm uses. This is useful for checking the configuration as well as using the dump as a starting point for a new, custom configuration. .IP "\-l" 4 .IX Item "-l" List all installed modules with their versions .IP "\-L author [ author ... ]" 4 .IX Item "-L author [ author ... ]" List the modules by the specified authors. .IP "\-m" 4 .IX Item "-m" Make the specified modules. .IP "\-M mirror1,mirror2,..." 4 .IX Item "-M mirror1,mirror2,..." A comma-separated list of mirrors to use for just this run. The \f(CW\*(C`\-P\*(C'\fR option can find them for you automatically. .IP "\-n" 4 .IX Item "-n" Do a dry run, but don't actually install anything. (unimplemented) .IP "\-O" 4 .IX Item "-O" Show the out-of-date modules. .IP "\-p" 4 .IX Item "-p" Ping the configured mirrors and print a report .IP "\-P" 4 .IX Item "-P" Find the best mirrors you could be using and use them for the current session. .IP "\-r" 4 .IX Item "-r" Recompiles dynamically loaded modules with CPAN::Shell\->recompile. .IP "\-s" 4 .IX Item "-s" Drop in the \s-1CPAN\s0.pm shell. This command does this automatically if you don't specify any arguments. .IP "\-t module [ module ... ]" 4 .IX Item "-t module [ module ... ]" Run a `make test` on the specified modules. .IP "\-T" 4 .IX Item "-T" Do not test modules. Simply install them. .IP "\-u" 4 .IX Item "-u" Upgrade all installed modules. Blindly doing this can really break things, so keep a backup. .IP "\-v" 4 .IX Item "-v" Print the script version and \s-1CPAN\s0.pm version then exit. .IP "\-V" 4 .IX Item "-V" Print detailed information about the cpan client. .IP "\-w" 4 .IX Item "-w" \&\s-1UNIMPLEMENTED\s0 .Sp Turn on cpan warnings. This checks various things, like directory permissions, and tells you about problems you might have. .IP "\-x module [ module ... ]" 4 .IX Item "-x module [ module ... ]" Find close matches to the named modules that you think you might have mistyped. This requires the optional installation of Text::Levenshtein or Text::Levenshtein::Damerau. .IP "\-X" 4 .IX Item "-X" Dump all the namespaces to standard output. .SS "Examples" .IX Subsection "Examples" .Vb 2 \& # print a help message \& cpan \-h \& \& # print the version numbers \& cpan \-v \& \& # create an autobundle \& cpan \-a \& \& # recompile modules \& cpan \-r \& \& # upgrade all installed modules \& cpan \-u \& \& # install modules ( sole \-i is optional ) \& cpan \-i Netscape::Booksmarks Business::ISBN \& \& # force install modules ( must use \-i ) \& cpan \-fi CGI::Minimal URI \& \& # install modules but without testing them \& cpan \-Ti CGI::Minimal URI .Ve .SS "Environment variables" .IX Subsection "Environment variables" There are several components in \s-1CPAN\s0.pm that use environment variables. The build tools, ExtUtils::MakeMaker and Module::Build use some, while others matter to the levels above them. Some of these are specified by the Perl Toolchain Gang: .PP Lancaster Consensus: .PP Oslo Consensus: .IP "\s-1NONINTERACTIVE_TESTING\s0" 4 .IX Item "NONINTERACTIVE_TESTING" Assume no one is paying attention and skips prompts for distributions that do that correctly. \f(CWcpan(1)\fR sets this to \f(CW1\fR unless it already has a value (even if that value is false). .IP "\s-1PERL_MM_USE_DEFAULT\s0" 4 .IX Item "PERL_MM_USE_DEFAULT" Use the default answer for a prompted questions. \f(CWcpan(1)\fR sets this to \f(CW1\fR unless it already has a value (even if that value is false). .IP "\s-1CPAN_OPTS\s0" 4 .IX Item "CPAN_OPTS" As with \f(CW\*(C`PERL5OPT\*(C'\fR, a string of additional \f(CWcpan(1)\fR options to add to those you specify on the command line. .IP "\s-1CPANSCRIPT_LOGLEVEL\s0" 4 .IX Item "CPANSCRIPT_LOGLEVEL" The log level to use, with either the embedded, minimal logger or Log::Log4perl if it is installed. Possible values are the same as the \f(CW\*(C`Log::Log4perl\*(C'\fR levels: \f(CW\*(C`TRACE\*(C'\fR, \f(CW\*(C`DEBUG\*(C'\fR, \f(CW\*(C`INFO\*(C'\fR, \f(CW\*(C`WARN\*(C'\fR, \&\f(CW\*(C`ERROR\*(C'\fR, and \f(CW\*(C`FATAL\*(C'\fR. The default is \f(CW\*(C`INFO\*(C'\fR. .IP "\s-1GIT_COMMAND\s0" 4 .IX Item "GIT_COMMAND" The path to the \f(CW\*(C`git\*(C'\fR binary to use for the Git features. The default is \f(CW\*(C`/usr/local/bin/git\*(C'\fR. .SH "EXIT VALUES" .IX Header "EXIT VALUES" The script exits with zero if it thinks that everything worked, or a positive number if it thinks that something failed. Note, however, that in some cases it has to divine a failure by the output of things it does not control. For now, the exit codes are vague: .PP .Vb 1 \& 1 An unknown error \& \& 2 The was an external problem \& \& 4 There was an internal problem with the script \& \& 8 A module failed to install .Ve .SH "TO DO" .IX Header "TO DO" * one shot configuration values from the command line .SH "BUGS" .IX Header "BUGS" * none noted .SH "SEE ALSO" .IX Header "SEE ALSO" Most behaviour, including environment variables and configuration, comes directly from \s-1CPAN\s0.pm. .SH "SOURCE AVAILABILITY" .IX Header "SOURCE AVAILABILITY" This code is in Github in the \s-1CPAN\s0.pm repository: .PP .Vb 1 \& https://github.com/andk/cpanpm .Ve .PP The source used to be tracked separately in another GitHub repo, but the canonical source is now in the above repo. .SH "CREDITS" .IX Header "CREDITS" Japheth Cleaver added the bits to allow a forced install (\-f). .PP Jim Brandt suggest and provided the initial implementation for the up-to-date and Changes features. .PP Adam Kennedy pointed out that \fBexit()\fR causes problems on Windows where this script ends up with a .bat extension .SH "AUTHOR" .IX Header "AUTHOR" brian d foy, \f(CW\*(C`\*(C'\fR .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright (c) 2001\-2015, brian d foy, All Rights Reserved. .PP You may redistribute this under the same terms as Perl itself. PK!y¬man/man1/cpan-mirrors.1nu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN-MIRRORS 1" .TH CPAN-MIRRORS 1 "2018-09-22" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" cpan\-mirrors \- Find the fatest CPAN mirrors nearby .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& % cpan\-mirrors \& \& Testing Africa \& is.co.za \-> 733.72 ms \& wa.co.za \-> 601.56 ms \& ucu.ac.ug \-> 407.99 ms \& mirror.ac.za \-> 614.05 ms \& zol.co.zw \-> 612.57 ms \& \-\->median time: 612.57 ms \& Testing Oceania \& serversaustralia.com.au \-> 38.62 ms \& cpan.inspire.net.nz \-> 67.81 ms \& digitalpacific.com.au \-> 37.89 ms \& uber.com.au \-> 44.47 ms \& lagoon.nc \-> 67.49 ms \& \-\->median time: 44.47 ms \& Testing North America \& httpupdate40.cpanel.net \-> 254.00 ms \& httpupdate35.cpanel.net \-> 409.75 ms \& mirrors.sonic.net \-> 368.56 ms \& httpupdate8.cpanel.net \-> 409.10 ms \& cpan.cs.utah.edu \-> 408.00 ms \& \-\->median time: 408.00 ms \& Testing Asia \& vinahost.vn \-> 146.10 ms \& yazd.ac.ir \-> 469.29 ms \& mirrors\-ru.go\-parts.com \-> 367.09 ms \& sohu.com \-> 399.76 ms \& neolabs.kz \-> 610.92 ms \& \-\->median time: 399.76 ms \& Testing South America \& mmgdesigns.com.ar \-> 407.96 ms \& nbtelecom.com.br \-> 401.96 ms \& sunsite.dcc.uchile.cl \-> 415.69 ms \& linorg.usp.br \-> 424.65 ms \& unal.edu.co \-> 407.60 ms \& \-\->median time: 407.96 ms \& Testing Europe \& uk2.net \-> 409.37 ms \& ambiweb.de \-> 710.65 ms \& bibleonline.ru \-> 471.49 ms \& rol.ru \-> 469.70 ms \& rub.de \-> 346.57 ms \& \-\->median time: 469.70 ms \& Median result by continent: \& 44 ms Oceania \& 400 ms Asia \& 408 ms South America \& 408 ms North America \& 470 ms Europe \& 613 ms Africa \& Best continent is Oceania \& cpan.catalyst.net.nz = 78.8369178771973 ms \& cpan.inspire.net.nz = 69.4258213043213 ms \& cpan.mirrors.ilisys.com.au = 50.2209663391113 ms \& digitalpacific.com.au = 40.1251316070557 ms \& lagoon.nc = 88.8760089874268 ms \& nautile.nc = 65.7081604003906 ms \& optusnet.com.au = 41.4729118347168 ms \& serversaustralia.com.au = 46.1521148681641 ms \& uber.com.au = 48.2730865478516 ms \& waia.asn.au = 86.2929821014404 ms \& webtastix.net = 70.5790519714355 ms \& Best mirrors are digitalpacific.com.au \& optusnet.com.au \& serversaustralia.com.au \& uber.com.au \& cpan.mirrors.ilisys.com.au \& \& Best urls are \& http://cpan.mirror.digitalpacific.com.au/ \& http://mirror.optusnet.com.au/CPAN/ \& http://cpan.mirror.serversaustralia.com.au/ \& http://cpan.mirror.uber.com.au/ \& http://cpan.mirrors.ilisys.com.au/ .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" \&\s-1CPAN\s0 Mirrors come and go, and maybe you do too. The mirror that was fast then might not be fast now, especially if you changed hemispheres. .PP This program goes through the \fI\s-1MIRRORED.BY\s0\fR file and pings a selection of mirrors on each continent to find the fastest mirrors. From the best continent, it samples several mirrors to find the \s-1URL\s0 you should add to your configuration. .PP If you don't have a \fI\s-1MIRRORED.BY\s0\fR file, this program will download one for you. It looks through your existing \f(CW\*(C`urllist\*(C'\fR configuration and then default locations. It stores it in \f(CW\*(C`~/.cpan\*(C'\fR (or your configured location to store files). .SH "TO DO" .IX Header "TO DO" .IP "\(bu" 4 Add an option to update the \s-1CPAN\s0 configuration .IP "\(bu" 4 Add an option to give \s-1JSON\s0 output .SH "AUTHOR" .IX Header "AUTHOR" brian d foy \f(CW\*(C`\*(C'\fR .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP See PK!=؝!!man/man1/json_xs.1nu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "JSON_XS 1" .TH JSON_XS 1 "2018-11-15" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" json_xs \- JSON::XS commandline utility .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& json_xs [\-v] [\-f inputformat] [\-t outputformat] .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" \&\fIjson_xs\fR converts between some input and output formats (one of them is \&\s-1JSON\s0). .PP The default input format is \f(CW\*(C`json\*(C'\fR and the default output format is \&\f(CW\*(C`json\-pretty\*(C'\fR. .SH "OPTIONS" .IX Header "OPTIONS" .IP "\-v" 4 .IX Item "-v" Be slightly more verbose. .IP "\-f fromformat" 4 .IX Item "-f fromformat" Read a file in the given format from \s-1STDIN.\s0 .Sp \&\f(CW\*(C`fromformat\*(C'\fR can be one of: .RS 4 .IP "json \- a json text encoded, either utf\-8, utf16\-be/le, utf32\-be/le" 4 .IX Item "json - a json text encoded, either utf-8, utf16-be/le, utf32-be/le" .PD 0 .IP "cbor \- \s-1CBOR\s0 (\s-1RFC 7049,\s0 \s-1CBOR::XS\s0), a kind of binary \s-1JSON\s0" 4 .IX Item "cbor - CBOR (RFC 7049, CBOR::XS), a kind of binary JSON" .IP "storable \- a Storable frozen value" 4 .IX Item "storable - a Storable frozen value" .IP "storable-file \- a Storable file (Storable has two incompatible formats)" 4 .IX Item "storable-file - a Storable file (Storable has two incompatible formats)" .IP "bencode \- use Convert::Bencode, if available (used by torrent files, among others)" 4 .IX Item "bencode - use Convert::Bencode, if available (used by torrent files, among others)" .IP "clzf \- Compress::LZF format (requires that module to be installed)" 4 .IX Item "clzf - Compress::LZF format (requires that module to be installed)" .ie n .IP "eval \- evaluate the given code as (non\-utf\-8) Perl, basically the reverse of ""\-t dump""" 4 .el .IP "eval \- evaluate the given code as (non\-utf\-8) Perl, basically the reverse of ``\-t dump''" 4 .IX Item "eval - evaluate the given code as (non-utf-8) Perl, basically the reverse of -t dump" .IP "yaml \- \s-1YAML\s0 format (requires that module to be installed)" 4 .IX Item "yaml - YAML format (requires that module to be installed)" .IP "string \- do not attempt to decode the file data" 4 .IX Item "string - do not attempt to decode the file data" .ie n .IP "none \- nothing is read, creates an ""undef"" scalar \- mainly useful with ""\-e""" 4 .el .IP "none \- nothing is read, creates an \f(CWundef\fR scalar \- mainly useful with \f(CW\-e\fR" 4 .IX Item "none - nothing is read, creates an undef scalar - mainly useful with -e" .RE .RS 4 .RE .IP "\-t toformat" 4 .IX Item "-t toformat" .PD Write the file in the given format to \s-1STDOUT.\s0 .Sp \&\f(CW\*(C`toformat\*(C'\fR can be one of: .RS 4 .IP "json, json\-utf\-8 \- json, utf\-8 encoded" 4 .IX Item "json, json-utf-8 - json, utf-8 encoded" .PD 0 .IP "json-pretty \- as above, but pretty-printed" 4 .IX Item "json-pretty - as above, but pretty-printed" .IP "json\-utf\-16le, json\-utf\-16be \- little endian/big endian utf\-16" 4 .IX Item "json-utf-16le, json-utf-16be - little endian/big endian utf-16" .IP "json\-utf\-32le, json\-utf\-32be \- little endian/big endian utf\-32" 4 .IX Item "json-utf-32le, json-utf-32be - little endian/big endian utf-32" .IP "cbor \- \s-1CBOR\s0 (\s-1RFC 7049,\s0 \s-1CBOR::XS\s0), a kind of binary \s-1JSON\s0" 4 .IX Item "cbor - CBOR (RFC 7049, CBOR::XS), a kind of binary JSON" .IP "cbor-packed \- \s-1CBOR\s0 using extensions to make it smaller" 4 .IX Item "cbor-packed - CBOR using extensions to make it smaller" .IP "storable \- a Storable frozen value in network format" 4 .IX Item "storable - a Storable frozen value in network format" .IP "storable-file \- a Storable file in network format (Storable has two incompatible formats)" 4 .IX Item "storable-file - a Storable file in network format (Storable has two incompatible formats)" .IP "bencode \- use Convert::Bencode, if available (used by torrent files, among others)" 4 .IX Item "bencode - use Convert::Bencode, if available (used by torrent files, among others)" .IP "clzf \- Compress::LZF format" 4 .IX Item "clzf - Compress::LZF format" .IP "yaml \- \s-1YAML::XS\s0 format" 4 .IX Item "yaml - YAML::XS format" .IP "dump \- Data::Dump" 4 .IX Item "dump - Data::Dump" .IP "dumper \- Data::Dumper" 4 .IX Item "dumper - Data::Dumper" .IP "string \- writes the data out as if it were a string" 4 .IX Item "string - writes the data out as if it were a string" .ie n .IP "none \- nothing gets written, mainly useful together with ""\-e""" 4 .el .IP "none \- nothing gets written, mainly useful together with \f(CW\-e\fR" 4 .IX Item "none - nothing gets written, mainly useful together with -e" .PD Note that Data::Dumper doesn't handle self-referential data structures correctly \- use \*(L"dump\*(R" instead. .RE .RS 4 .RE .IP "\-e code" 4 .IX Item "-e code" Evaluate perl code after reading the data and before writing it out again \&\- can be used to filter, create or extract data. The data that has been written is in \f(CW$_\fR, and whatever is in there is written out afterwards. .SH "EXAMPLES" .IX Header "EXAMPLES" .Vb 1 \& json_xs \-t none pretty.json .Ve .PP Prettify the \s-1JSON\s0 file \fIsrc.json\fR to \fIdst.json\fR. .PP .Vb 1 \& json_xs \-f storable\-file {"announce\-list"}}\*(Aq \-t string .Ve .PP Print the tracker list inside a torrent file. .PP .Vb 1 \& lwp\-request http://cpantesters.perl.org/show/JSON\-XS.json | json_xs .Ve .PP Fetch the cpan-testers result summary \f(CW\*(C`JSON::XS\*(C'\fR and pretty-print it. .SH "AUTHOR" .IX Header "AUTHOR" Copyright (C) 2008 Marc Lehmann PK!EX:22man/man3/App::Cpan.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "App::Cpan 3" .TH App::Cpan 3 "2022-04-03" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" App::Cpan \- easily interact with CPAN from the command line .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& # with arguments and no switches, installs specified modules \& cpan module_name [ module_name ... ] \& \& # with switches, installs modules with extra behavior \& cpan [\-cfFimtTw] module_name [ module_name ... ] \& \& # use local::lib \& cpan \-I module_name [ module_name ... ] \& \& # one time mirror override for faster mirrors \& cpan \-p ... \& \& # with just the dot, install from the distribution in the \& # current directory \& cpan . \& \& # without arguments, starts CPAN.pm shell \& cpan \& \& # without arguments, but some switches \& cpan [\-ahpruvACDLOPX] .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This script provides a command interface (not a shell) to \s-1CPAN.\s0 At the moment it uses \s-1CPAN\s0.pm to do the work, but it is not a one-shot command runner for \s-1CPAN\s0.pm. .SS "Options" .IX Subsection "Options" .IP "\-a" 4 .IX Item "-a" Creates a \s-1CPAN\s0.pm autobundle with CPAN::Shell\->autobundle. .IP "\-A module [ module ... ]" 4 .IX Item "-A module [ module ... ]" Shows the primary maintainers for the specified modules. .IP "\-c module" 4 .IX Item "-c module" Runs a `make clean` in the specified module's directories. .IP "\-C module [ module ... ]" 4 .IX Item "-C module [ module ... ]" Show the \fIChanges\fR files for the specified modules .IP "\-D module [ module ... ]" 4 .IX Item "-D module [ module ... ]" Show the module details. This prints one line for each out-of-date module (meaning, modules locally installed but have newer versions on \s-1CPAN\s0). Each line has three columns: module name, local version, and \s-1CPAN\s0 version. .IP "\-f" 4 .IX Item "-f" Force the specified action, when it normally would have failed. Use this to install a module even if its tests fail. When you use this option, \&\-i is not optional for installing a module when you need to force it: .Sp .Vb 1 \& % cpan \-f \-i Module::Foo .Ve .IP "\-F" 4 .IX Item "-F" Turn off \s-1CPAN\s0.pm's attempts to lock anything. You should be careful with this since you might end up with multiple scripts trying to muck in the same directory. This isn't so much of a concern if you're loading a special config with \f(CW\*(C`\-j\*(C'\fR, and that config sets up its own work directories. .IP "\-g module [ module ... ]" 4 .IX Item "-g module [ module ... ]" Downloads to the current directory the latest distribution of the module. .IP "\-G module [ module ... ]" 4 .IX Item "-G module [ module ... ]" \&\s-1UNIMPLEMENTED\s0 .Sp Download to the current directory the latest distribution of the modules, unpack each distribution, and create a git repository for each distribution. .Sp If you want this feature, check out Yanick Champoux's \f(CW\*(C`Git::CPAN::Patch\*(C'\fR distribution. .IP "\-h" 4 .IX Item "-h" Print a help message and exit. When you specify \f(CW\*(C`\-h\*(C'\fR, it ignores all of the other options and arguments. .IP "\-i module [ module ... ]" 4 .IX Item "-i module [ module ... ]" Install the specified modules. With no other switches, this switch is implied. .IP "\-I" 4 .IX Item "-I" Load \f(CW\*(C`local::lib\*(C'\fR (think like \f(CW\*(C`\-I\*(C'\fR for loading lib paths). Too bad \&\f(CW\*(C`\-l\*(C'\fR was already taken. .IP "\-j Config.pm" 4 .IX Item "-j Config.pm" Load the file that has the \s-1CPAN\s0 configuration data. This should have the same format as the standard \fICPAN/Config.pm\fR file, which defines \&\f(CW$CPAN::Config\fR as an anonymous hash. .Sp If the file does not exist, \f(CW\*(C`cpan\*(C'\fR dies. .IP "\-J" 4 .IX Item "-J" Dump the configuration in the same format that \s-1CPAN\s0.pm uses. This is useful for checking the configuration as well as using the dump as a starting point for a new, custom configuration. .IP "\-l" 4 .IX Item "-l" List all installed modules with their versions .IP "\-L author [ author ... ]" 4 .IX Item "-L author [ author ... ]" List the modules by the specified authors. .IP "\-m" 4 .IX Item "-m" Make the specified modules. .IP "\-M mirror1,mirror2,..." 4 .IX Item "-M mirror1,mirror2,..." A comma-separated list of mirrors to use for just this run. The \f(CW\*(C`\-P\*(C'\fR option can find them for you automatically. .IP "\-n" 4 .IX Item "-n" Do a dry run, but don't actually install anything. (unimplemented) .IP "\-O" 4 .IX Item "-O" Show the out-of-date modules. .IP "\-p" 4 .IX Item "-p" Ping the configured mirrors and print a report .IP "\-P" 4 .IX Item "-P" Find the best mirrors you could be using and use them for the current session. .IP "\-r" 4 .IX Item "-r" Recompiles dynamically loaded modules with CPAN::Shell\->recompile. .IP "\-s" 4 .IX Item "-s" Drop in the \s-1CPAN\s0.pm shell. This command does this automatically if you don't specify any arguments. .IP "\-t module [ module ... ]" 4 .IX Item "-t module [ module ... ]" Run a `make test` on the specified modules. .IP "\-T" 4 .IX Item "-T" Do not test modules. Simply install them. .IP "\-u" 4 .IX Item "-u" Upgrade all installed modules. Blindly doing this can really break things, so keep a backup. .IP "\-v" 4 .IX Item "-v" Print the script version and \s-1CPAN\s0.pm version then exit. .IP "\-V" 4 .IX Item "-V" Print detailed information about the cpan client. .IP "\-w" 4 .IX Item "-w" \&\s-1UNIMPLEMENTED\s0 .Sp Turn on cpan warnings. This checks various things, like directory permissions, and tells you about problems you might have. .IP "\-x module [ module ... ]" 4 .IX Item "-x module [ module ... ]" Find close matches to the named modules that you think you might have mistyped. This requires the optional installation of Text::Levenshtein or Text::Levenshtein::Damerau. .IP "\-X" 4 .IX Item "-X" Dump all the namespaces to standard output. .SS "Examples" .IX Subsection "Examples" .Vb 2 \& # print a help message \& cpan \-h \& \& # print the version numbers \& cpan \-v \& \& # create an autobundle \& cpan \-a \& \& # recompile modules \& cpan \-r \& \& # upgrade all installed modules \& cpan \-u \& \& # install modules ( sole \-i is optional ) \& cpan \-i Netscape::Booksmarks Business::ISBN \& \& # force install modules ( must use \-i ) \& cpan \-fi CGI::Minimal URI \& \& # install modules but without testing them \& cpan \-Ti CGI::Minimal URI .Ve .SS "Environment variables" .IX Subsection "Environment variables" There are several components in \s-1CPAN\s0.pm that use environment variables. The build tools, ExtUtils::MakeMaker and Module::Build use some, while others matter to the levels above them. Some of these are specified by the Perl Toolchain Gang: .PP Lancaster Consensus: .PP Oslo Consensus: .IP "\s-1NONINTERACTIVE_TESTING\s0" 4 .IX Item "NONINTERACTIVE_TESTING" Assume no one is paying attention and skips prompts for distributions that do that correctly. \f(CWcpan(1)\fR sets this to \f(CW1\fR unless it already has a value (even if that value is false). .IP "\s-1PERL_MM_USE_DEFAULT\s0" 4 .IX Item "PERL_MM_USE_DEFAULT" Use the default answer for a prompted questions. \f(CWcpan(1)\fR sets this to \f(CW1\fR unless it already has a value (even if that value is false). .IP "\s-1CPAN_OPTS\s0" 4 .IX Item "CPAN_OPTS" As with \f(CW\*(C`PERL5OPT\*(C'\fR, a string of additional \f(CWcpan(1)\fR options to add to those you specify on the command line. .IP "\s-1CPANSCRIPT_LOGLEVEL\s0" 4 .IX Item "CPANSCRIPT_LOGLEVEL" The log level to use, with either the embedded, minimal logger or Log::Log4perl if it is installed. Possible values are the same as the \f(CW\*(C`Log::Log4perl\*(C'\fR levels: \f(CW\*(C`TRACE\*(C'\fR, \f(CW\*(C`DEBUG\*(C'\fR, \f(CW\*(C`INFO\*(C'\fR, \f(CW\*(C`WARN\*(C'\fR, \&\f(CW\*(C`ERROR\*(C'\fR, and \f(CW\*(C`FATAL\*(C'\fR. The default is \f(CW\*(C`INFO\*(C'\fR. .IP "\s-1GIT_COMMAND\s0" 4 .IX Item "GIT_COMMAND" The path to the \f(CW\*(C`git\*(C'\fR binary to use for the Git features. The default is \f(CW\*(C`/usr/local/bin/git\*(C'\fR. .SS "Methods" .IX Subsection "Methods" .IP "run( \s-1ARGS\s0 )" 4 .IX Item "run( ARGS )" Just do it. .Sp The \f(CW\*(C`run\*(C'\fR method returns 0 on success and a positive number on failure. See the section on \s-1EXIT CODES\s0 for details on the values. .Sp \&\s-1CPAN\s0.pm sends all the good stuff either to \s-1STDOUT,\s0 or to a temp file if \f(CW$CPAN::Be_Silent\fR is set. I have to intercept that output so I can find out what happened. .Sp Stolen from File::Path::Expand .SH "EXIT VALUES" .IX Header "EXIT VALUES" The script exits with zero if it thinks that everything worked, or a positive number if it thinks that something failed. Note, however, that in some cases it has to divine a failure by the output of things it does not control. For now, the exit codes are vague: .PP .Vb 1 \& 1 An unknown error \& \& 2 The was an external problem \& \& 4 There was an internal problem with the script \& \& 8 A module failed to install .Ve .SH "TO DO" .IX Header "TO DO" * There is initial support for Log4perl if it is available, but I haven't gone through everything to make the NullLogger work out correctly if Log4perl is not installed. .PP * When I capture \s-1CPAN\s0.pm output, I need to check for errors and report them to the user. .PP * Warnings switch .PP * Check then exit .SH "BUGS" .IX Header "BUGS" * none noted .SH "SEE ALSO" .IX Header "SEE ALSO" \&\s-1CPAN\s0, App::cpanminus .SH "SOURCE AVAILABILITY" .IX Header "SOURCE AVAILABILITY" This code is in Github in the \s-1CPAN\s0.pm repository: .PP .Vb 1 \& https://github.com/andk/cpanpm .Ve .PP The source used to be tracked separately in another GitHub repo, but the canonical source is now in the above repo. .SH "CREDITS" .IX Header "CREDITS" Japheth Cleaver added the bits to allow a forced install (\f(CW\*(C`\-f\*(C'\fR). .PP Jim Brandt suggested and provided the initial implementation for the up-to-date and Changes features. .PP Adam Kennedy pointed out that \f(CW\*(C`exit()\*(C'\fR causes problems on Windows where this script ends up with a .bat extension .PP David Golden helps integrate this into the \f(CW\*(C`CPAN.pm\*(C'\fR repos. .PP Jim Keenan fixed up various issues with _download .SH "AUTHOR" .IX Header "AUTHOR" brian d foy, \f(CW\*(C`\*(C'\fR .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright (c) 2001\-2021, brian d foy, All Rights Reserved. .PP You may redistribute this under the same terms as Perl itself. PK![//man/man3/CPAN.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN 3" .TH CPAN 3 "2023-05-10" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN \- query, download and build perl modules from CPAN sites .SH "SYNOPSIS" .IX Header "SYNOPSIS" Interactive mode: .PP .Vb 1 \& perl \-MCPAN \-e shell .Ve .PP \&\-\-or\*(-- .PP .Vb 1 \& cpan .Ve .PP Basic commands: .PP .Vb 1 \& # Modules: \& \& cpan> install Acme::Meta # in the shell \& \& CPAN::Shell\->install("Acme::Meta"); # in perl \& \& # Distributions: \& \& cpan> install NWCLARK/Acme\-Meta\-0.02.tar.gz # in the shell \& \& CPAN::Shell\-> \& install("NWCLARK/Acme\-Meta\-0.02.tar.gz"); # in perl \& \& # module objects: \& \& $mo = CPAN::Shell\->expandany($mod); \& $mo = CPAN::Shell\->expand("Module",$mod); # same thing \& \& # distribution objects: \& \& $do = CPAN::Shell\->expand("Module",$mod)\->distribution; \& $do = CPAN::Shell\->expandany($distro); # same thing \& $do = CPAN::Shell\->expand("Distribution", \& $distro); # same thing .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" The \s-1CPAN\s0 module automates or at least simplifies the make and install of perl modules and extensions. It includes some primitive searching capabilities and knows how to use \s-1LWP,\s0 HTTP::Tiny, Net::FTP and certain external download clients to fetch distributions from the net. .PP These are fetched from one or more mirrored \s-1CPAN\s0 (Comprehensive Perl Archive Network) sites and unpacked in a dedicated directory. .PP The \s-1CPAN\s0 module also supports named and versioned \&\fIbundles\fR of modules. Bundles simplify handling of sets of related modules. See Bundles below. .PP The package contains a session manager and a cache manager. The session manager keeps track of what has been fetched, built, and installed in the current session. The cache manager keeps track of the disk space occupied by the make processes and deletes excess space using a simple \s-1FIFO\s0 mechanism. .PP All methods provided are accessible in a programmer style and in an interactive shell style. .ie n .SS "CPAN::shell([$prompt, $command]) Starting Interactive Mode" .el .SS "CPAN::shell([$prompt, \f(CW$command\fP]) Starting Interactive Mode" .IX Subsection "CPAN::shell([$prompt, $command]) Starting Interactive Mode" Enter interactive mode by running .PP .Vb 1 \& perl \-MCPAN \-e shell .Ve .PP or .PP .Vb 1 \& cpan .Ve .PP which puts you into a readline interface. If \f(CW\*(C`Term::ReadKey\*(C'\fR and either of \f(CW\*(C`Term::ReadLine::Perl\*(C'\fR or \f(CW\*(C`Term::ReadLine::Gnu\*(C'\fR are installed, history and command completion are supported. .PP Once at the command line, type \f(CW\*(C`h\*(C'\fR for one-page help screen; the rest should be self-explanatory. .PP The function call \f(CW\*(C`shell\*(C'\fR takes two optional arguments: one the prompt, the second the default initial command line (the latter only works if a real ReadLine interface module is installed). .PP The most common uses of the interactive modes are .IP "Searching for authors, bundles, distribution files and modules" 2 .IX Item "Searching for authors, bundles, distribution files and modules" There are corresponding one-letter commands \f(CW\*(C`a\*(C'\fR, \f(CW\*(C`b\*(C'\fR, \f(CW\*(C`d\*(C'\fR, and \f(CW\*(C`m\*(C'\fR for each of the four categories and another, \f(CW\*(C`i\*(C'\fR for any of the mentioned four. Each of the four entities is implemented as a class with slightly differing methods for displaying an object. .Sp Arguments to these commands are either strings exactly matching the identification string of an object, or regular expressions matched case-insensitively against various attributes of the objects. The parser only recognizes a regular expression when you enclose it with slashes. .Sp The principle is that the number of objects found influences how an item is displayed. If the search finds one item, the result is displayed with the rather verbose method \f(CW\*(C`as_string\*(C'\fR, but if more than one is found, each object is displayed with the terse method \&\f(CW\*(C`as_glimpse\*(C'\fR. .Sp Examples: .Sp .Vb 10 \& cpan> m Acme::MetaSyntactic \& Module id = Acme::MetaSyntactic \& CPAN_USERID BOOK (Philippe Bruhat (BooK) <[...]>) \& CPAN_VERSION 0.99 \& CPAN_FILE B/BO/BOOK/Acme\-MetaSyntactic\-0.99.tar.gz \& UPLOAD_DATE 2006\-11\-06 \& MANPAGE Acme::MetaSyntactic \- Themed metasyntactic variables names \& INST_FILE /usr/local/lib/perl/5.10.0/Acme/MetaSyntactic.pm \& INST_VERSION 0.99 \& cpan> a BOOK \& Author id = BOOK \& EMAIL [...] \& FULLNAME Philippe Bruhat (BooK) \& cpan> d BOOK/Acme\-MetaSyntactic\-0.99.tar.gz \& Distribution id = B/BO/BOOK/Acme\-MetaSyntactic\-0.99.tar.gz \& CPAN_USERID BOOK (Philippe Bruhat (BooK) <[...]>) \& CONTAINSMODS Acme::MetaSyntactic Acme::MetaSyntactic::Alias [...] \& UPLOAD_DATE 2006\-11\-06 \& cpan> m /lorem/ \& Module = Acme::MetaSyntactic::loremipsum (BOOK/Acme\-MetaSyntactic\-0.99.tar.gz) \& Module Text::Lorem (ADEOLA/Text\-Lorem\-0.3.tar.gz) \& Module Text::Lorem::More (RKRIMEN/Text\-Lorem\-More\-0.12.tar.gz) \& Module Text::Lorem::More::Source (RKRIMEN/Text\-Lorem\-More\-0.12.tar.gz) \& cpan> i /berlin/ \& Distribution BEATNIK/Filter\-NumberLines\-0.02.tar.gz \& Module = DateTime::TimeZone::Europe::Berlin (DROLSKY/DateTime\-TimeZone\-0.7904.tar.gz) \& Module Filter::NumberLines (BEATNIK/Filter\-NumberLines\-0.02.tar.gz) \& Author [...] .Ve .Sp The examples illustrate several aspects: the first three queries target modules, authors, or distros directly and yield exactly one result. The last two use regular expressions and yield several results. The last one targets all of bundles, modules, authors, and distros simultaneously. When more than one result is available, they are printed in one-line format. .ie n .IP """get"", ""make"", ""test"", ""install"", ""clean"" modules or distributions" 2 .el .IP "\f(CWget\fR, \f(CWmake\fR, \f(CWtest\fR, \f(CWinstall\fR, \f(CWclean\fR modules or distributions" 2 .IX Item "get, make, test, install, clean modules or distributions" These commands take any number of arguments and investigate what is necessary to perform the action. Argument processing is as follows: .Sp .Vb 5 \& known module name in format Foo/Bar.pm module \& other embedded slash distribution \& \- with trailing slash dot directory \& enclosing slashes regexp \& known module name in format Foo::Bar module .Ve .Sp If the argument is a distribution file name (recognized by embedded slashes), it is processed. If it is a module, \s-1CPAN\s0 determines the distribution file in which this module is included and processes that, following any dependencies named in the module's \s-1META\s0.yml or Makefile.PL (this behavior is controlled by the configuration parameter \f(CW\*(C`prerequisites_policy\*(C'\fR). If an argument is enclosed in slashes it is treated as a regular expression: it is expanded and if the result is a single object (distribution, bundle or module), this object is processed. .Sp Example: .Sp .Vb 3 \& install Dummy::Perl # installs the module \& install AUXXX/Dummy\-Perl\-3.14.tar.gz # installs that distribution \& install /Dummy\-Perl\-3.14/ # same if the regexp is unambiguous .Ve .Sp \&\f(CW\*(C`get\*(C'\fR downloads a distribution file and untars or unzips it, \f(CW\*(C`make\*(C'\fR builds it, \f(CW\*(C`test\*(C'\fR runs the test suite, and \f(CW\*(C`install\*(C'\fR installs it. .Sp Any \f(CW\*(C`make\*(C'\fR or \f(CW\*(C`test\*(C'\fR is run unconditionally. An .Sp .Vb 1 \& install .Ve .Sp is also run unconditionally. But for .Sp .Vb 1 \& install .Ve .Sp \&\s-1CPAN\s0 checks whether an install is needed and prints \&\fImodule up to date\fR if the distribution file containing the module doesn't need updating. .Sp \&\s-1CPAN\s0 also keeps track of what it has done within the current session and doesn't try to build a package a second time regardless of whether it succeeded or not. It does not repeat a test run if the test has been run successfully before. Same for install runs. .Sp The \f(CW\*(C`force\*(C'\fR pragma may precede another command (currently: \f(CW\*(C`get\*(C'\fR, \&\f(CW\*(C`make\*(C'\fR, \f(CW\*(C`test\*(C'\fR, or \f(CW\*(C`install\*(C'\fR) to execute the command from scratch and attempt to continue past certain errors. See the section below on the \f(CW\*(C`force\*(C'\fR and the \f(CW\*(C`fforce\*(C'\fR pragma. .Sp The \f(CW\*(C`notest\*(C'\fR pragma skips the test part in the build process. .Sp Example: .Sp .Vb 1 \& cpan> notest install Tk .Ve .Sp A \f(CW\*(C`clean\*(C'\fR command results in a .Sp .Vb 1 \& make clean .Ve .Sp being executed within the distribution file's working directory. .ie n .IP """readme"", ""perldoc"", ""look"" module or distribution" 2 .el .IP "\f(CWreadme\fR, \f(CWperldoc\fR, \f(CWlook\fR module or distribution" 2 .IX Item "readme, perldoc, look module or distribution" \&\f(CW\*(C`readme\*(C'\fR displays the \s-1README\s0 file of the associated distribution. \&\f(CW\*(C`Look\*(C'\fR gets and untars (if not yet done) the distribution file, changes to the appropriate directory and opens a subshell process in that directory. \f(CW\*(C`perldoc\*(C'\fR displays the module's pod documentation in html or plain text format. .ie n .IP """ls"" author" 2 .el .IP "\f(CWls\fR author" 2 .IX Item "ls author" .PD 0 .ie n .IP """ls"" globbing_expression" 2 .el .IP "\f(CWls\fR globbing_expression" 2 .IX Item "ls globbing_expression" .PD The first form lists all distribution files in and below an author's \&\s-1CPAN\s0 directory as stored in the \s-1CHECKSUMS\s0 files distributed on \&\s-1CPAN.\s0 The listing recurses into subdirectories. .Sp The second form limits or expands the output with shell globbing as in the following examples: .Sp .Vb 3 \& ls JV/make* \& ls GSAR/*make* \& ls */*make* .Ve .Sp The last example is very slow and outputs extra progress indicators that break the alignment of the result. .Sp Note that globbing only lists directories explicitly asked for, for example FOO/* will not list FOO/bar/Acme\-Sthg\-n.nn.tar.gz. This may be regarded as a bug that may be changed in some future version. .ie n .IP """failed""" 2 .el .IP "\f(CWfailed\fR" 2 .IX Item "failed" The \f(CW\*(C`failed\*(C'\fR command reports all distributions that failed on one of \&\f(CW\*(C`make\*(C'\fR, \f(CW\*(C`test\*(C'\fR or \f(CW\*(C`install\*(C'\fR for some reason in the currently running shell session. .IP "Persistence between sessions" 2 .IX Item "Persistence between sessions" If the \f(CW\*(C`YAML\*(C'\fR or the \f(CW\*(C`YAML::Syck\*(C'\fR module is installed a record of the internal state of all modules is written to disk after each step. The files contain a signature of the currently running perl version for later perusal. .Sp If the configurations variable \f(CW\*(C`build_dir_reuse\*(C'\fR is set to a true value, then \s-1CPAN\s0.pm reads the collected \s-1YAML\s0 files. If the stored signature matches the currently running perl, the stored state is loaded into memory such that persistence between sessions is effectively established. .ie n .IP "The ""force"" and the ""fforce"" pragma" 2 .el .IP "The \f(CWforce\fR and the \f(CWfforce\fR pragma" 2 .IX Item "The force and the fforce pragma" To speed things up in complex installation scenarios, \s-1CPAN\s0.pm keeps track of what it has already done and refuses to do some things a second time. A \f(CW\*(C`get\*(C'\fR, a \f(CW\*(C`make\*(C'\fR, and an \f(CW\*(C`install\*(C'\fR are not repeated. A \f(CW\*(C`test\*(C'\fR is repeated only if the previous test was unsuccessful. The diagnostic message when \s-1CPAN\s0.pm refuses to do something a second time is one of \fIHas already been \fR\f(CW\*(C`unwrapped|made|tested successfully\*(C'\fR or something similar. Another situation where \s-1CPAN\s0 refuses to act is an \&\f(CW\*(C`install\*(C'\fR if the corresponding \f(CW\*(C`test\*(C'\fR was not successful. .Sp In all these cases, the user can override this stubborn behaviour by prepending the command with the word force, for example: .Sp .Vb 4 \& cpan> force get Foo \& cpan> force make AUTHOR/Bar\-3.14.tar.gz \& cpan> force test Baz \& cpan> force install Acme::Meta .Ve .Sp Each \fIforced\fR command is executed with the corresponding part of its memory erased. .Sp The \f(CW\*(C`fforce\*(C'\fR pragma is a variant that emulates a \f(CW\*(C`force get\*(C'\fR which erases the entire memory followed by the action specified, effectively restarting the whole get/make/test/install procedure from scratch. .IP "Lockfile" 2 .IX Item "Lockfile" Interactive sessions maintain a lockfile, by default \f(CW\*(C`~/.cpan/.lock\*(C'\fR. Batch jobs can run without a lockfile and not disturb each other. .Sp The shell offers to run in \fIdowngraded mode\fR when another process is holding the lockfile. This is an experimental feature that is not yet tested very well. This second shell then does not write the history file, does not use the metadata file, and has a different prompt. .IP "Signals" 2 .IX Item "Signals" \&\s-1CPAN\s0.pm installs signal handlers for \s-1SIGINT\s0 and \s-1SIGTERM.\s0 While you are in the cpan-shell, it is intended that you can press \f(CW\*(C`^C\*(C'\fR anytime and return to the cpan-shell prompt. A \s-1SIGTERM\s0 will cause the cpan-shell to clean up and leave the shell loop. You can emulate the effect of a \&\s-1SIGTERM\s0 by sending two consecutive SIGINTs, which usually means by pressing \f(CW\*(C`^C\*(C'\fR twice. .Sp \&\s-1CPAN\s0.pm ignores \s-1SIGPIPE.\s0 If the user sets \f(CW\*(C`inactivity_timeout\*(C'\fR, a \&\s-1SIGALRM\s0 is used during the run of the \f(CW\*(C`perl Makefile.PL\*(C'\fR or \f(CW\*(C`perl Build.PL\*(C'\fR subprocess. A \s-1SIGALRM\s0 is also used during module version parsing, and is controlled by \f(CW\*(C`version_timeout\*(C'\fR. .SS "CPAN::Shell" .IX Subsection "CPAN::Shell" The commands available in the shell interface are methods in the package CPAN::Shell. If you enter the shell command, your input is split by the \fBText::ParseWords::shellwords()\fR routine, which acts like most shells do. The first word is interpreted as the method to be invoked, and the rest of the words are treated as the method's arguments. Continuation lines are supported by ending a line with a literal backslash. .SS "autobundle" .IX Subsection "autobundle" \&\f(CW\*(C`autobundle\*(C'\fR writes a bundle file into the \&\f(CW\*(C`$CPAN::Config\->{cpan_home}/Bundle\*(C'\fR directory. The file contains a list of all modules that are both available from \s-1CPAN\s0 and currently installed within \f(CW@INC\fR. Duplicates of each distribution are suppressed. The name of the bundle file is based on the current date and a counter, e.g. \fIBundle/Snapshot_2012_05_21_00.pm\fR. This is installed again by running \f(CW\*(C`cpan Bundle::Snapshot_2012_05_21_00\*(C'\fR, or installing \&\f(CW\*(C`Bundle::Snapshot_2012_05_21_00\*(C'\fR from the \s-1CPAN\s0 shell. .PP Return value: path to the written file. .SS "hosts" .IX Subsection "hosts" Note: this feature is still in alpha state and may change in future versions of \s-1CPAN\s0.pm .PP This commands provides a statistical overview over recent download activities. The data for this is collected in the \s-1YAML\s0 file \&\f(CW\*(C`FTPstats.yml\*(C'\fR in your \f(CW\*(C`cpan_home\*(C'\fR directory. If no \s-1YAML\s0 module is configured or \s-1YAML\s0 not installed, no stats are provided. .IP "install_tested" 4 .IX Item "install_tested" Install all distributions that have been tested successfully but have not yet been installed. See also \f(CW\*(C`is_tested\*(C'\fR. .IP "is_tested" 4 .IX Item "is_tested" List all build directories of distributions that have been tested successfully but have not yet been installed. See also \&\f(CW\*(C`install_tested\*(C'\fR. .SS "mkmyconfig" .IX Subsection "mkmyconfig" \&\fBmkmyconfig()\fR writes your own CPAN::MyConfig file into your \f(CW\*(C`~/.cpan/\*(C'\fR directory so that you can save your own preferences instead of the system-wide ones. .SS "r [Module|/Regexp/]..." .IX Subsection "r [Module|/Regexp/]..." scans current perl installation for modules that have a newer version available on \s-1CPAN\s0 and provides a list of them. If called without argument, all potential upgrades are listed; if called with arguments the list is filtered to the modules and regexps given as arguments. .PP The listing looks something like this: .PP .Vb 10 \& Package namespace installed latest in CPAN file \& CPAN 1.94_64 1.9600 ANDK/CPAN\-1.9600.tar.gz \& CPAN::Reporter 1.1801 1.1902 DAGOLDEN/CPAN\-Reporter\-1.1902.tar.gz \& YAML 0.70 0.73 INGY/YAML\-0.73.tar.gz \& YAML::Syck 1.14 1.17 AVAR/YAML\-Syck\-1.17.tar.gz \& YAML::Tiny 1.44 1.50 ADAMK/YAML\-Tiny\-1.50.tar.gz \& CGI 3.43 3.55 MARKSTOS/CGI.pm\-3.55.tar.gz \& Module::Build::YAML 1.40 1.41 DAGOLDEN/Module\-Build\-0.3800.tar.gz \& TAP::Parser::Result::YAML 3.22 3.23 ANDYA/Test\-Harness\-3.23.tar.gz \& YAML::XS 0.34 0.35 INGY/YAML\-LibYAML\-0.35.tar.gz .Ve .PP It suppresses duplicates in the column \f(CW\*(C`in CPAN file\*(C'\fR such that distributions with many upgradeable modules are listed only once. .PP Note that the list is not sorted. .SS "recent ***EXPERIMENTAL COMMAND***" .IX Subsection "recent ***EXPERIMENTAL COMMAND***" The \f(CW\*(C`recent\*(C'\fR command downloads a list of recent uploads to \s-1CPAN\s0 and displays them \fIslowly\fR. While the command is running, a \f(CW$SIG\fR{\s-1INT\s0} exits the loop after displaying the current item. .PP \&\fBNote\fR: This command requires XML::LibXML installed. .PP \&\fBNote\fR: This whole command currently is just a hack and will probably change in future versions of \s-1CPAN\s0.pm, but the general approach will likely remain. .PP \&\fBNote\fR: See also smoke .SS "recompile" .IX Subsection "recompile" \&\fBrecompile()\fR is a special command that takes no argument and runs the make/test/install cycle with brute force over all installed dynamically loadable extensions (a.k.a. \s-1XS\s0 modules) with 'force' in effect. The primary purpose of this command is to finish a network installation. Imagine you have a common source tree for two different architectures. You decide to do a completely independent fresh installation. You start on one architecture with the help of a Bundle file produced earlier. \s-1CPAN\s0 installs the whole Bundle for you, but when you try to repeat the job on the second architecture, \s-1CPAN\s0 responds with a \f(CW"Foo up to date"\fR message for all modules. So you invoke \s-1CPAN\s0's recompile on the second architecture and you're done. .PP Another popular use for \f(CW\*(C`recompile\*(C'\fR is to act as a rescue in case your perl breaks binary compatibility. If one of the modules that \s-1CPAN\s0 uses is in turn depending on binary compatibility (so you cannot run \s-1CPAN\s0 commands), then you should try the CPAN::Nox module for recovery. .SS "report Bundle|Distribution|Module" .IX Subsection "report Bundle|Distribution|Module" The \f(CW\*(C`report\*(C'\fR command temporarily turns on the \f(CW\*(C`test_report\*(C'\fR config variable, then runs the \f(CW\*(C`force test\*(C'\fR command with the given arguments. The \f(CW\*(C`force\*(C'\fR pragma reruns the tests and repeats every step that might have failed before. .SS "smoke ***EXPERIMENTAL COMMAND***" .IX Subsection "smoke ***EXPERIMENTAL COMMAND***" \&\fB*** \s-1WARNING:\s0 this command downloads and executes software from \s-1CPAN\s0 to your computer of completely unknown status. You should never do this with your normal account and better have a dedicated well separated and secured machine to do this. ***\fR .PP The \f(CW\*(C`smoke\*(C'\fR command takes the list of recent uploads to \s-1CPAN\s0 as provided by the \f(CW\*(C`recent\*(C'\fR command and tests them all. While the command is running \f(CW$SIG\fR{\s-1INT\s0} is defined to mean that the current item shall be skipped. .PP \&\fBNote\fR: This whole command currently is just a hack and will probably change in future versions of \s-1CPAN\s0.pm, but the general approach will likely remain. .PP \&\fBNote\fR: See also recent .SS "upgrade [Module|/Regexp/]..." .IX Subsection "upgrade [Module|/Regexp/]..." The \f(CW\*(C`upgrade\*(C'\fR command first runs an \f(CW\*(C`r\*(C'\fR command with the given arguments and then installs the newest versions of all modules that were listed by that. .ie n .SS "The four ""CPAN::*"" Classes: Author, Bundle, Module, Distribution" .el .SS "The four \f(CWCPAN::*\fP Classes: Author, Bundle, Module, Distribution" .IX Subsection "The four CPAN::* Classes: Author, Bundle, Module, Distribution" Although it may be considered internal, the class hierarchy does matter for both users and programmer. \s-1CPAN\s0.pm deals with the four classes mentioned above, and those classes all share a set of methods. Classical single polymorphism is in effect. A metaclass object registers all objects of all kinds and indexes them with a string. The strings referencing objects have a separated namespace (well, not completely separated): .PP .Vb 1 \& Namespace Class \& \& words containing a "/" (slash) Distribution \& words starting with Bundle:: Bundle \& everything else Module or Author .Ve .PP Modules know their associated Distribution objects. They always refer to the most recent official release. Developers may mark their releases as unstable development versions (by inserting an underscore into the module version number which will also be reflected in the distribution name when you run 'make dist'), so the really hottest and newest distribution is not always the default. If a module Foo circulates on \s-1CPAN\s0 in both version 1.23 and 1.23_90, \s-1CPAN\s0.pm offers a convenient way to install version 1.23 by saying .PP .Vb 1 \& install Foo .Ve .PP This would install the complete distribution file (say BAR/Foo\-1.23.tar.gz) with all accompanying material. But if you would like to install version 1.23_90, you need to know where the distribution file resides on \s-1CPAN\s0 relative to the authors/id/ directory. If the author is \s-1BAR,\s0 this might be BAR/Foo\-1.23_90.tar.gz; so you would have to say .PP .Vb 1 \& install BAR/Foo\-1.23_90.tar.gz .Ve .PP The first example will be driven by an object of the class CPAN::Module, the second by an object of class CPAN::Distribution. .SS "Integrating local directories" .IX Subsection "Integrating local directories" Note: this feature is still in alpha state and may change in future versions of \s-1CPAN\s0.pm .PP Distribution objects are normally distributions from the \s-1CPAN,\s0 but there is a slightly degenerate case for Distribution objects, too, of projects held on the local disk. These distribution objects have the same name as the local directory and end with a dot. A dot by itself is also allowed for the current directory at the time \s-1CPAN\s0.pm was used. All actions such as \f(CW\*(C`make\*(C'\fR, \f(CW\*(C`test\*(C'\fR, and \f(CW\*(C`install\*(C'\fR are applied directly to that directory. This gives the command \f(CW\*(C`cpan .\*(C'\fR an interesting touch: while the normal mantra of installing a \s-1CPAN\s0 module without \s-1CPAN\s0.pm is one of .PP .Vb 5 \& perl Makefile.PL perl Build.PL \& ( go and get prerequisites ) \& make ./Build \& make test ./Build test \& make install ./Build install .Ve .PP the command \f(CW\*(C`cpan .\*(C'\fR does all of this at once. It figures out which of the two mantras is appropriate, fetches and installs all prerequisites, takes care of them recursively, and finally finishes the installation of the module in the current directory, be it a \s-1CPAN\s0 module or not. .PP The typical usage case is for private modules or working copies of projects from remote repositories on the local disk. .SS "Redirection" .IX Subsection "Redirection" The usual shell redirection symbols \f(CW\*(C` | \*(C'\fR and \f(CW\*(C`>\*(C'\fR are recognized by the cpan shell \fBonly when surrounded by whitespace\fR. So piping to pager or redirecting output into a file works somewhat as in a normal shell, with the stipulation that you must type extra spaces. .SS "Plugin support ***EXPERIMENTAL***" .IX Subsection "Plugin support ***EXPERIMENTAL***" Plugins are objects that implement any of currently eight methods: .PP .Vb 8 \& pre_get \& post_get \& pre_make \& post_make \& pre_test \& post_test \& pre_install \& post_install .Ve .PP The \f(CW\*(C`plugin_list\*(C'\fR configuration parameter holds a list of strings of the form .PP .Vb 1 \& Modulename=arg0,arg1,arg2,arg3,... .Ve .PP eg: .PP .Vb 1 \& CPAN::Plugin::Flurb=dir,/opt/pkgs/flurb/raw,verbose,1 .Ve .PP At run time, each listed plugin is instantiated as a singleton object by running the equivalent of this pseudo code: .PP .Vb 3 \& my $plugin = ; \& ; \& my $p = $instance{$plugin} ||= Modulename\->new($arg0,$arg1,...); .Ve .PP The generated singletons are kept around from instantiation until the end of the shell session. can be reconfigured at any time at run time. While the cpan shell is running, it checks all activated plugins at each of the 8 reference points listed above and runs the respective method if it is implemented for that object. The method is called with the active CPAN::Distribution object passed in as an argument. .SH "CONFIGURATION" .IX Header "CONFIGURATION" When the \s-1CPAN\s0 module is used for the first time, a configuration dialogue tries to determine a couple of site specific options. The result of the dialog is stored in a hash reference \f(CW $CPAN::Config \fR in a file CPAN/Config.pm. .PP Default values defined in the CPAN/Config.pm file can be overridden in a user specific file: CPAN/MyConfig.pm. Such a file is best placed in \f(CW\*(C`$HOME/.cpan/CPAN/MyConfig.pm\*(C'\fR, because \f(CW\*(C`$HOME/.cpan\*(C'\fR is added to the search path of the \s-1CPAN\s0 module before the \fBuse()\fR or \&\fBrequire()\fR statements. The mkmyconfig command writes this file for you. .PP The \f(CW\*(C`o conf\*(C'\fR command has various bells and whistles: .IP "completion support" 4 .IX Item "completion support" If you have a ReadLine module installed, you can hit \s-1TAB\s0 at any point of the commandline and \f(CW\*(C`o conf\*(C'\fR will offer you completion for the built-in subcommands and/or config variable names. .IP "displaying some help: o conf help" 4 .IX Item "displaying some help: o conf help" Displays a short help .IP "displaying current values: o conf [\s-1KEY\s0]" 4 .IX Item "displaying current values: o conf [KEY]" Displays the current value(s) for this config variable. Without \s-1KEY,\s0 displays all subcommands and config variables. .Sp Example: .Sp .Vb 1 \& o conf shell .Ve .Sp If \s-1KEY\s0 starts and ends with a slash, the string in between is treated as a regular expression and only keys matching this regexp are displayed .Sp Example: .Sp .Vb 1 \& o conf /color/ .Ve .IP "changing of scalar values: o conf \s-1KEY VALUE\s0" 4 .IX Item "changing of scalar values: o conf KEY VALUE" Sets the config variable \s-1KEY\s0 to \s-1VALUE.\s0 The empty string can be specified as usual in shells, with \f(CW\*(Aq\*(Aq\fR or \f(CW""\fR .Sp Example: .Sp .Vb 1 \& o conf wget /usr/bin/wget .Ve .IP "changing of list values: o conf \s-1KEY\s0 SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST" 4 .IX Item "changing of list values: o conf KEY SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST" If a config variable name ends with \f(CW\*(C`list\*(C'\fR, it is a list. \f(CW\*(C`o conf KEY shift\*(C'\fR removes the first element of the list, \f(CW\*(C`o conf KEY pop\*(C'\fR removes the last element of the list. \f(CW\*(C`o conf KEYS unshift LIST\*(C'\fR prepends a list of values to the list, \f(CW\*(C`o conf KEYS push LIST\*(C'\fR appends a list of valued to the list. .Sp Likewise, \f(CW\*(C`o conf KEY splice LIST\*(C'\fR passes the \s-1LIST\s0 to the corresponding splice command. .Sp Finally, any other list of arguments is taken as a new list value for the \s-1KEY\s0 variable discarding the previous value. .Sp Examples: .Sp .Vb 3 \& o conf urllist unshift http://cpan.dev.local/CPAN \& o conf urllist splice 3 1 \& o conf urllist http://cpan1.local http://cpan2.local ftp://ftp.perl.org .Ve .IP "reverting to saved: o conf defaults" 4 .IX Item "reverting to saved: o conf defaults" Reverts all config variables to the state in the saved config file. .IP "saving the config: o conf commit" 4 .IX Item "saving the config: o conf commit" Saves all config variables to the current config file (CPAN/Config.pm or CPAN/MyConfig.pm that was loaded at start). .PP The configuration dialog can be started any time later again by issuing the command \f(CW\*(C` o conf init \*(C'\fR in the \s-1CPAN\s0 shell. A subset of the configuration dialog can be run by issuing \f(CW\*(C`o conf init WORD\*(C'\fR where \s-1WORD\s0 is any valid config variable or a regular expression. .SS "Config Variables" .IX Subsection "Config Variables" The following keys in the hash reference \f(CW$CPAN::Config\fR are currently defined: .PP .Vb 10 \& allow_installing_module_downgrades \& allow or disallow installing module downgrades \& allow_installing_outdated_dists \& allow or disallow installing modules that are \& indexed in the cpan index pointing to a distro \& with a higher distro\-version number \& applypatch path to external prg \& auto_commit commit all changes to config variables to disk \& build_cache size of cache for directories to build modules \& build_dir locally accessible directory to build modules \& build_dir_reuse boolean if distros in build_dir are persistent \& build_requires_install_policy \& to install or not to install when a module is \& only needed for building. yes|no|ask/yes|ask/no \& bzip2 path to external prg \& cache_metadata use serializer to cache metadata \& check_sigs if signatures should be verified \& cleanup_after_install \& remove build directory immediately after a \& successful install and remember that for the \& duration of the session \& colorize_debug Term::ANSIColor attributes for debugging output \& colorize_output boolean if Term::ANSIColor should colorize output \& colorize_print Term::ANSIColor attributes for normal output \& colorize_warn Term::ANSIColor attributes for warnings \& commandnumber_in_prompt \& boolean if you want to see current command number \& commands_quote preferred character to use for quoting external \& commands when running them. Defaults to double \& quote on Windows, single tick everywhere else; \& can be set to space to disable quoting \& connect_to_internet_ok \& whether to ask if opening a connection is ok before \& urllist is specified \& cpan_home local directory reserved for this package \& curl path to external prg \& dontload_hash DEPRECATED \& dontload_list arrayref: modules in the list will not be \& loaded by the CPAN::has_inst() routine \& ftp path to external prg \& ftp_passive if set, the environment variable FTP_PASSIVE is set \& for downloads \& ftp_proxy proxy host for ftp requests \& ftpstats_period max number of days to keep download statistics \& ftpstats_size max number of items to keep in the download statistics \& getcwd see below \& gpg path to external prg \& gzip location of external program gzip \& halt_on_failure stop processing after the first failure of queued \& items or dependencies \& histfile file to maintain history between sessions \& histsize maximum number of lines to keep in histfile \& http_proxy proxy host for http requests \& inactivity_timeout breaks interactive Makefile.PLs or Build.PLs \& after this many seconds inactivity. Set to 0 to \& disable timeouts. \& index_expire refetch index files after this many days \& inhibit_startup_message \& if true, suppress the startup message \& keep_source_where directory in which to keep the source (if we do) \& load_module_verbosity \& report loading of optional modules used by CPAN.pm \& lynx path to external prg \& make location of external make program \& make_arg arguments that should always be passed to \*(Aqmake\*(Aq \& make_install_make_command \& the make command for running \*(Aqmake install\*(Aq, for \& example \*(Aqsudo make\*(Aq \& make_install_arg same as make_arg for \*(Aqmake install\*(Aq \& makepl_arg arguments passed to \*(Aqperl Makefile.PL\*(Aq \& mbuild_arg arguments passed to \*(Aq./Build\*(Aq \& mbuild_install_arg arguments passed to \*(Aq./Build install\*(Aq \& mbuild_install_build_command \& command to use instead of \*(Aq./Build\*(Aq when we are \& in the install stage, for example \*(Aqsudo ./Build\*(Aq \& mbuildpl_arg arguments passed to \*(Aqperl Build.PL\*(Aq \& ncftp path to external prg \& ncftpget path to external prg \& no_proxy don\*(Aqt proxy to these hosts/domains (comma separated list) \& pager location of external program more (or any pager) \& password your password if you CPAN server wants one \& patch path to external prg \& patches_dir local directory containing patch files \& perl5lib_verbosity verbosity level for PERL5LIB additions \& plugin_list list of active hooks (see Plugin support above \& and the CPAN::Plugin module) \& prefer_external_tar \& per default all untar operations are done with \& Archive::Tar; by setting this variable to true \& the external tar command is used if available \& prefer_installer legal values are MB and EUMM: if a module comes \& with both a Makefile.PL and a Build.PL, use the \& former (EUMM) or the latter (MB); if the module \& comes with only one of the two, that one will be \& used no matter the setting \& prerequisites_policy \& what to do if you are missing module prerequisites \& (\*(Aqfollow\*(Aq automatically, \*(Aqask\*(Aq me, or \*(Aqignore\*(Aq) \& For \*(Aqfollow\*(Aq, also sets PERL_AUTOINSTALL and \& PERL_EXTUTILS_AUTOINSTALL for "\-\-defaultdeps" if \& not already set \& prefs_dir local directory to store per\-distro build options \& proxy_user username for accessing an authenticating proxy \& proxy_pass password for accessing an authenticating proxy \& pushy_https use https to cpan.org when possible, otherwise use http \& to cpan.org and issue a warning \& randomize_urllist add some randomness to the sequence of the urllist \& recommends_policy whether recommended prerequisites should be included \& scan_cache controls scanning of cache (\*(Aqatstart\*(Aq, \*(Aqatexit\*(Aq or \*(Aqnever\*(Aq) \& shell your favorite shell \& show_unparsable_versions \& boolean if r command tells which modules are versionless \& show_upload_date boolean if commands should try to determine upload date \& show_zero_versions boolean if r command tells for which modules $version==0 \& suggests_policy whether suggested prerequisites should be included \& tar location of external program tar \& tar_verbosity verbosity level for the tar command \& term_is_latin deprecated: if true Unicode is translated to ISO\-8859\-1 \& (and nonsense for characters outside latin range) \& term_ornaments boolean to turn ReadLine ornamenting on/off \& test_report email test reports (if CPAN::Reporter is installed) \& trust_test_report_history \& skip testing when previously tested ok (according to \& CPAN::Reporter history) \& unzip location of external program unzip \& urllist arrayref to nearby CPAN sites (or equivalent locations) \& urllist_ping_external \& use external ping command when autoselecting mirrors \& urllist_ping_verbose \& increase verbosity when autoselecting mirrors \& use_prompt_default set PERL_MM_USE_DEFAULT for configure/make/test/install \& use_sqlite use CPAN::SQLite for metadata storage (fast and lean) \& username your username if you CPAN server wants one \& version_timeout stops version parsing after this many seconds. \& Default is 15 secs. Set to 0 to disable. \& wait_list arrayref to a wait server to try (See CPAN::WAIT) \& wget path to external prg \& yaml_load_code enable YAML code deserialisation via CPAN::DeferredCode \& yaml_module which module to use to read/write YAML files .Ve .PP You can set and query each of these options interactively in the cpan shell with the \f(CW\*(C`o conf\*(C'\fR or the \f(CW\*(C`o conf init\*(C'\fR command as specified below. .ie n .IP """o conf """ 2 .el .IP "\f(CWo conf \fR" 2 .IX Item "o conf " prints the current value of the \fIscalar option\fR .ie n .IP """o conf """ 2 .el .IP "\f(CWo conf \fR" 2 .IX Item "o conf " Sets the value of the \fIscalar option\fR to \fIvalue\fR .ie n .IP """o conf """ 2 .el .IP "\f(CWo conf \fR" 2 .IX Item "o conf " prints the current value of the \fIlist option\fR in MakeMaker's neatvalue format. .ie n .IP """o conf [shift|pop]""" 2 .el .IP "\f(CWo conf [shift|pop]\fR" 2 .IX Item "o conf [shift|pop]" shifts or pops the array in the \fIlist option\fR variable .ie n .IP """o conf [unshift|push|splice] """ 2 .el .IP "\f(CWo conf [unshift|push|splice] \fR" 2 .IX Item "o conf [unshift|push|splice] " works like the corresponding perl commands. .IP "interactive editing: o conf init [MATCH|LIST]" 2 .IX Item "interactive editing: o conf init [MATCH|LIST]" Runs an interactive configuration dialog for matching variables. Without argument runs the dialog over all supported config variables. To specify a \s-1MATCH\s0 the argument must be enclosed by slashes. .Sp Examples: .Sp .Vb 2 \& o conf init ftp_passive ftp_proxy \& o conf init /color/ .Ve .Sp Note: this method of setting config variables often provides more explanation about the functioning of a variable than the manpage. .SS "CPAN::anycwd($path): Note on config variable getcwd" .IX Subsection "CPAN::anycwd($path): Note on config variable getcwd" \&\s-1CPAN\s0.pm changes the current working directory often and needs to determine its own current working directory. By default it uses Cwd::cwd, but if for some reason this doesn't work on your system, configure alternatives according to the following table: .IP "cwd" 4 .IX Item "cwd" Calls Cwd::cwd .IP "getcwd" 4 .IX Item "getcwd" Calls Cwd::getcwd .IP "fastcwd" 4 .IX Item "fastcwd" Calls Cwd::fastcwd .IP "getdcwd" 4 .IX Item "getdcwd" Calls Cwd::getdcwd .IP "backtickcwd" 4 .IX Item "backtickcwd" Calls the external command cwd. .SS "Note on the format of the urllist parameter" .IX Subsection "Note on the format of the urllist parameter" urllist parameters are URLs according to \s-1RFC 1738.\s0 We do a little guessing if your \s-1URL\s0 is not compliant, but if you have problems with \&\f(CW\*(C`file\*(C'\fR URLs, please try the correct format. Either: .PP .Vb 1 \& file://localhost/whatever/ftp/pub/CPAN/ .Ve .PP or .PP .Vb 1 \& file:///home/ftp/pub/CPAN/ .Ve .SS "The urllist parameter has CD-ROM support" .IX Subsection "The urllist parameter has CD-ROM support" The \f(CW\*(C`urllist\*(C'\fR parameter of the configuration table contains a list of URLs used for downloading. If the list contains any \&\f(CW\*(C`file\*(C'\fR URLs, \s-1CPAN\s0 always tries there first. This feature is disabled for index files. So the recommendation for the owner of a CD-ROM with \s-1CPAN\s0 contents is: include your local, possibly outdated CD-ROM as a \f(CW\*(C`file\*(C'\fR \s-1URL\s0 at the end of urllist, e.g. .PP .Vb 1 \& o conf urllist push file://localhost/CDROM/CPAN .Ve .PP \&\s-1CPAN\s0.pm will then fetch the index files from one of the \s-1CPAN\s0 sites that come at the beginning of urllist. It will later check for each module to see whether there is a local copy of the most recent version. .PP Another peculiarity of urllist is that the site that we could successfully fetch the last file from automatically gets a preference token and is tried as the first site for the next request. So if you add a new site at runtime it may happen that the previously preferred site will be tried another time. This means that if you want to disallow a site for the next transfer, it must be explicitly removed from urllist. .SS "Maintaining the urllist parameter" .IX Subsection "Maintaining the urllist parameter" If you have \s-1YAML\s0.pm (or some other \s-1YAML\s0 module configured in \&\f(CW\*(C`yaml_module\*(C'\fR) installed, \s-1CPAN\s0.pm collects a few statistical data about recent downloads. You can view the statistics with the \f(CW\*(C`hosts\*(C'\fR command or inspect them directly by looking into the \f(CW\*(C`FTPstats.yml\*(C'\fR file in your \f(CW\*(C`cpan_home\*(C'\fR directory. .PP To get some interesting statistics, it is recommended that \&\f(CW\*(C`randomize_urllist\*(C'\fR be set; this introduces some amount of randomness into the \s-1URL\s0 selection. .ie n .SS "The ""requires"" and ""build_requires"" dependency declarations" .el .SS "The \f(CWrequires\fP and \f(CWbuild_requires\fP dependency declarations" .IX Subsection "The requires and build_requires dependency declarations" Since \s-1CPAN\s0.pm version 1.88_51 modules declared as \f(CW\*(C`build_requires\*(C'\fR by a distribution are treated differently depending on the config variable \f(CW\*(C`build_requires_install_policy\*(C'\fR. By setting \&\f(CW\*(C`build_requires_install_policy\*(C'\fR to \f(CW\*(C`no\*(C'\fR, such a module is not installed. It is only built and tested, and then kept in the list of tested but uninstalled modules. As such, it is available during the build of the dependent module by integrating the path to the \&\f(CW\*(C`blib/arch\*(C'\fR and \f(CW\*(C`blib/lib\*(C'\fR directories in the environment variable \&\s-1PERL5LIB.\s0 If \f(CW\*(C`build_requires_install_policy\*(C'\fR is set to \f(CW\*(C`yes\*(C'\fR, then both modules declared as \f(CW\*(C`requires\*(C'\fR and those declared as \&\f(CW\*(C`build_requires\*(C'\fR are treated alike. By setting to \f(CW\*(C`ask/yes\*(C'\fR or \&\f(CW\*(C`ask/no\*(C'\fR, \s-1CPAN\s0.pm asks the user and sets the default accordingly. .SS "Configuration of the allow_installing_* parameters" .IX Subsection "Configuration of the allow_installing_* parameters" The \f(CW\*(C`allow_installing_*\*(C'\fR parameters are evaluated during the \f(CW\*(C`make\*(C'\fR phase. If set to \f(CW\*(C`yes\*(C'\fR, they allow the testing and the installation of the current distro and otherwise have no effect. If set to \f(CW\*(C`no\*(C'\fR, they may abort the build (preventing testing and installing), depending on the contents of the \&\f(CW\*(C`blib/\*(C'\fR directory. The \f(CW\*(C`blib/\*(C'\fR directory is the directory that holds all the files that would usually be installed in the \f(CW\*(C`install\*(C'\fR phase. .PP \&\f(CW\*(C`allow_installing_outdated_dists\*(C'\fR compares the \f(CW\*(C`blib/\*(C'\fR directory with the \s-1CPAN\s0 index. If it finds something there that belongs, according to the index, to a different dist, it aborts the current build. .PP \&\f(CW\*(C`allow_installing_module_downgrades\*(C'\fR compares the \f(CW\*(C`blib/\*(C'\fR directory with already installed modules, actually their version numbers, as determined by ExtUtils::MakeMaker or equivalent. If a to-be-installed module would downgrade an already installed module, the current build is aborted. .PP An interesting twist occurs when a distroprefs document demands the installation of an outdated dist via goto while \&\f(CW\*(C`allow_installing_outdated_dists\*(C'\fR forbids it. Without additional provisions, this would let the \f(CW\*(C`allow_installing_outdated_dists\*(C'\fR win and the distroprefs lose. So the proper arrangement in such a case is to write a second distroprefs document for the distro that \f(CW\*(C`goto\*(C'\fR points to and overrule the \f(CW\*(C`cpanconfig\*(C'\fR there. E.g.: .PP .Vb 9 \& \-\-\- \& match: \& distribution: "^MAUKE/Keyword\-Simple\-0.04.tar.gz" \& goto: "MAUKE/Keyword\-Simple\-0.03.tar.gz" \& \-\-\- \& match: \& distribution: "^MAUKE/Keyword\-Simple\-0.03.tar.gz" \& cpanconfig: \& allow_installing_outdated_dists: yes .Ve .SS "Configuration for individual distributions (\fIDistroprefs\fP)" .IX Subsection "Configuration for individual distributions (Distroprefs)" (\fBNote:\fR This feature has been introduced in \s-1CPAN\s0.pm 1.8854) .PP Distributions on \s-1CPAN\s0 usually behave according to what we call the \&\s-1CPAN\s0 mantra. Or since the advent of Module::Build we should talk about two mantras: .PP .Vb 4 \& perl Makefile.PL perl Build.PL \& make ./Build \& make test ./Build test \& make install ./Build install .Ve .PP But some modules cannot be built with this mantra. They try to get some extra data from the user via the environment, extra arguments, or interactively\*(--thus disturbing the installation of large bundles like Phalanx100 or modules with many dependencies like Plagger. .PP The distroprefs system of \f(CW\*(C`CPAN.pm\*(C'\fR addresses this problem by allowing the user to specify extra informations and recipes in \s-1YAML\s0 files to either .IP "\(bu" 4 pass additional arguments to one of the four commands, .IP "\(bu" 4 set environment variables .IP "\(bu" 4 instantiate an Expect object that reads from the console, waits for some regular expressions and enters some answers .IP "\(bu" 4 temporarily override assorted \f(CW\*(C`CPAN.pm\*(C'\fR configuration variables .IP "\(bu" 4 specify dependencies the original maintainer forgot .IP "\(bu" 4 disable the installation of an object altogether .PP See the \s-1YAML\s0 and Data::Dumper files that come with the \f(CW\*(C`CPAN.pm\*(C'\fR distribution in the \f(CW\*(C`distroprefs/\*(C'\fR directory for examples. .SS "Filenames" .IX Subsection "Filenames" The \s-1YAML\s0 files themselves must have the \f(CW\*(C`.yml\*(C'\fR extension; all other files are ignored (for two exceptions see \fIFallback Data::Dumper and Storable\fR below). The containing directory can be specified in \&\f(CW\*(C`CPAN.pm\*(C'\fR in the \f(CW\*(C`prefs_dir\*(C'\fR config variable. Try \f(CW\*(C`o conf init prefs_dir\*(C'\fR in the \s-1CPAN\s0 shell to set and activate the distroprefs system. .PP Every \s-1YAML\s0 file may contain arbitrary documents according to the \s-1YAML\s0 specification, and every document is treated as an entity that can specify the treatment of a single distribution. .PP Filenames can be picked arbitrarily; \f(CW\*(C`CPAN.pm\*(C'\fR always reads all files (in alphabetical order) and takes the key \f(CW\*(C`match\*(C'\fR (see below in \fILanguage Specs\fR) as a hashref containing match criteria that determine if the current distribution matches the \s-1YAML\s0 document or not. .SS "Fallback Data::Dumper and Storable" .IX Subsection "Fallback Data::Dumper and Storable" If neither your configured \f(CW\*(C`yaml_module\*(C'\fR nor \s-1YAML\s0.pm is installed, \&\s-1CPAN\s0.pm falls back to using Data::Dumper and Storable and looks for files with the extensions \f(CW\*(C`.dd\*(C'\fR or \f(CW\*(C`.st\*(C'\fR in the \f(CW\*(C`prefs_dir\*(C'\fR directory. These files are expected to contain one or more hashrefs. For Data::Dumper generated files, this is expected to be done with by defining \f(CW$VAR1\fR, \f(CW$VAR2\fR, etc. The \s-1YAML\s0 shell would produce these with the command .PP .Vb 1 \& ysh < somefile.yml > somefile.dd .Ve .PP For Storable files the rule is that they must be constructed such that \&\f(CW\*(C`Storable::retrieve(file)\*(C'\fR returns an array reference and the array elements represent one distropref object each. The conversion from \&\s-1YAML\s0 would look like so: .PP .Vb 3 \& perl \-MYAML=LoadFile \-MStorable=nstore \-e \*(Aq \& @y=LoadFile(shift); \& nstore(\e@y, shift)\*(Aq somefile.yml somefile.st .Ve .PP In bootstrapping situations it is usually sufficient to translate only a few \s-1YAML\s0 files to Data::Dumper for crucial modules like \&\f(CW\*(C`YAML::Syck\*(C'\fR, \f(CW\*(C`YAML.pm\*(C'\fR and \f(CW\*(C`Expect.pm\*(C'\fR. If you prefer Storable over Data::Dumper, remember to pull out a Storable version that writes an older format than all the other Storable versions that will need to read them. .SS "Blueprint" .IX Subsection "Blueprint" The following example contains all supported keywords and structures with the exception of \f(CW\*(C`eexpect\*(C'\fR which can be used instead of \&\f(CW\*(C`expect\*(C'\fR. .PP .Vb 10 \& \-\-\- \& comment: "Demo" \& match: \& module: "Dancing::Queen" \& distribution: "^CHACHACHA/Dancing\-" \& not_distribution: "\e.zip$" \& perl: "/usr/local/cariba\-perl/bin/perl" \& perlconfig: \& archname: "freebsd" \& not_cc: "gcc" \& env: \& DANCING_FLOOR: "Shubiduh" \& disabled: 1 \& cpanconfig: \& make: gmake \& pl: \& args: \& \- "\-\-somearg=specialcase" \& \& env: {} \& \& expect: \& \- "Which is your favorite fruit" \& \- "apple\en" \& \& make: \& args: \& \- all \& \- extra\-all \& \& env: {} \& \& expect: [] \& \& commandline: "echo SKIPPING make" \& \& test: \& args: [] \& \& env: {} \& \& expect: [] \& \& install: \& args: [] \& \& env: \& WANT_TO_INSTALL: YES \& \& expect: \& \- "Do you really want to install" \& \- "y\en" \& \& patches: \& \- "ABCDE/Fedcba\-3.14\-ABCDE\-01.patch" \& \& depends: \& configure_requires: \& LWP: 5.8 \& build_requires: \& Test::Exception: 0.25 \& requires: \& Spiffy: 0.30 .Ve .SS "Language Specs" .IX Subsection "Language Specs" Every \s-1YAML\s0 document represents a single hash reference. The valid keys in this hash are as follows: .IP "comment [scalar]" 4 .IX Item "comment [scalar]" A comment .IP "cpanconfig [hash]" 4 .IX Item "cpanconfig [hash]" Temporarily override assorted \f(CW\*(C`CPAN.pm\*(C'\fR configuration variables. .Sp Supported are: \f(CW\*(C`build_requires_install_policy\*(C'\fR, \f(CW\*(C`check_sigs\*(C'\fR, \&\f(CW\*(C`make\*(C'\fR, \f(CW\*(C`make_install_make_command\*(C'\fR, \f(CW\*(C`prefer_installer\*(C'\fR, \&\f(CW\*(C`test_report\*(C'\fR. Please report as a bug when you need another one supported. .IP "depends [hash] *** \s-1EXPERIMENTAL FEATURE\s0 ***" 4 .IX Item "depends [hash] *** EXPERIMENTAL FEATURE ***" All three types, namely \f(CW\*(C`configure_requires\*(C'\fR, \f(CW\*(C`build_requires\*(C'\fR, and \&\f(CW\*(C`requires\*(C'\fR are supported in the way specified in the \s-1META\s0.yml specification. The current implementation \fImerges\fR the specified dependencies with those declared by the package maintainer. In a future implementation this may be changed to override the original declaration. .IP "disabled [boolean]" 4 .IX Item "disabled [boolean]" Specifies that this distribution shall not be processed at all. .IP "features [array] *** \s-1EXPERIMENTAL FEATURE\s0 ***" 4 .IX Item "features [array] *** EXPERIMENTAL FEATURE ***" Experimental implementation to deal with optional_features from \&\s-1META\s0.yml. Still needs coordination with installer software and currently works only for \s-1META\s0.yml declaring \f(CW\*(C`dynamic_config=0\*(C'\fR. Use with caution. .IP "goto [string]" 4 .IX Item "goto [string]" The canonical name of a delegate distribution to install instead. Useful when a new version, although it tests \s-1OK\s0 itself, breaks something else or a developer release or a fork is already uploaded that is better than the last released version. .IP "install [hash]" 4 .IX Item "install [hash]" Processing instructions for the \f(CW\*(C`make install\*(C'\fR or \f(CW\*(C`./Build install\*(C'\fR phase of the \s-1CPAN\s0 mantra. See below under \fIProcessing Instructions\fR. .IP "make [hash]" 4 .IX Item "make [hash]" Processing instructions for the \f(CW\*(C`make\*(C'\fR or \f(CW\*(C`./Build\*(C'\fR phase of the \&\s-1CPAN\s0 mantra. See below under \fIProcessing Instructions\fR. .IP "match [hash]" 4 .IX Item "match [hash]" A hashref with one or more of the keys \f(CW\*(C`distribution\*(C'\fR, \f(CW\*(C`module\*(C'\fR, \&\f(CW\*(C`perl\*(C'\fR, \f(CW\*(C`perlconfig\*(C'\fR, and \f(CW\*(C`env\*(C'\fR that specify whether a document is targeted at a specific \s-1CPAN\s0 distribution or installation. Keys prefixed with \f(CW\*(C`not_\*(C'\fR negates the corresponding match. .Sp The corresponding values are interpreted as regular expressions. The \&\f(CW\*(C`distribution\*(C'\fR related one will be matched against the canonical distribution name, e.g. \*(L"AUTHOR/Foo\-Bar\-3.14.tar.gz\*(R". .Sp The \f(CW\*(C`module\*(C'\fR related one will be matched against \fIall\fR modules contained in the distribution until one module matches. .Sp The \f(CW\*(C`perl\*(C'\fR related one will be matched against \f(CW$^X\fR (but with the absolute path). .Sp The value associated with \f(CW\*(C`perlconfig\*(C'\fR is itself a hashref that is matched against corresponding values in the \f(CW%Config::Config\fR hash living in the \f(CW\*(C`Config.pm\*(C'\fR module. Keys prefixed with \f(CW\*(C`not_\*(C'\fR negates the corresponding match. .Sp The value associated with \f(CW\*(C`env\*(C'\fR is itself a hashref that is matched against corresponding values in the \f(CW%ENV\fR hash. Keys prefixed with \f(CW\*(C`not_\*(C'\fR negates the corresponding match. .Sp If more than one restriction of \f(CW\*(C`module\*(C'\fR, \f(CW\*(C`distribution\*(C'\fR, etc. is specified, the results of the separately computed match values must all match. If so, the hashref represented by the \&\s-1YAML\s0 document is returned as the preference structure for the current distribution. .IP "patches [array]" 4 .IX Item "patches [array]" An array of patches on \s-1CPAN\s0 or on the local disk to be applied in order via an external patch program. If the value for the \f(CW\*(C`\-p\*(C'\fR parameter is \f(CW0\fR or \f(CW1\fR is determined by reading the patch beforehand. The path to each patch is either an absolute path on the local filesystem or relative to a patch directory specified in the \&\f(CW\*(C`patches_dir\*(C'\fR configuration variable or in the format of a canonical distro name. For examples please consult the distroprefs/ directory in the \s-1CPAN\s0.pm distribution (these examples are not installed by default). .Sp Note: if the \f(CW\*(C`applypatch\*(C'\fR program is installed and \f(CW\*(C`CPAN::Config\*(C'\fR knows about it \fBand\fR a patch is written by the \f(CW\*(C`makepatch\*(C'\fR program, then \f(CW\*(C`CPAN.pm\*(C'\fR lets \f(CW\*(C`applypatch\*(C'\fR apply the patch. Both \f(CW\*(C`makepatch\*(C'\fR and \f(CW\*(C`applypatch\*(C'\fR are available from \s-1CPAN\s0 in the \f(CW\*(C`JV/makepatch\-*\*(C'\fR distribution. .IP "pl [hash]" 4 .IX Item "pl [hash]" Processing instructions for the \f(CW\*(C`perl Makefile.PL\*(C'\fR or \f(CW\*(C`perl Build.PL\*(C'\fR phase of the \s-1CPAN\s0 mantra. See below under \fIProcessing Instructions\fR. .IP "test [hash]" 4 .IX Item "test [hash]" Processing instructions for the \f(CW\*(C`make test\*(C'\fR or \f(CW\*(C`./Build test\*(C'\fR phase of the \s-1CPAN\s0 mantra. See below under \fIProcessing Instructions\fR. .SS "Processing Instructions" .IX Subsection "Processing Instructions" .IP "args [array]" 4 .IX Item "args [array]" Arguments to be added to the command line .IP "commandline" 4 .IX Item "commandline" A full commandline to run via \f(CW\*(C`system()\*(C'\fR. During execution, the environment variable \s-1PERL\s0 is set to $^X (but with an absolute path). If \f(CW\*(C`commandline\*(C'\fR is specified, \&\f(CW\*(C`args\*(C'\fR is not used. .IP "eexpect [hash]" 4 .IX Item "eexpect [hash]" Extended \f(CW\*(C`expect\*(C'\fR. This is a hash reference with four allowed keys, \&\f(CW\*(C`mode\*(C'\fR, \f(CW\*(C`timeout\*(C'\fR, \f(CW\*(C`reuse\*(C'\fR, and \f(CW\*(C`talk\*(C'\fR. .Sp You must install the \f(CW\*(C`Expect\*(C'\fR module to use \f(CW\*(C`eexpect\*(C'\fR. \s-1CPAN\s0.pm does not install it for you. .Sp \&\f(CW\*(C`mode\*(C'\fR may have the values \f(CW\*(C`deterministic\*(C'\fR for the case where all questions come in the order written down and \f(CW\*(C`anyorder\*(C'\fR for the case where the questions may come in any order. The default mode is \&\f(CW\*(C`deterministic\*(C'\fR. .Sp \&\f(CW\*(C`timeout\*(C'\fR denotes a timeout in seconds. Floating-point timeouts are \&\s-1OK.\s0 With \f(CW\*(C`mode=deterministic\*(C'\fR, the timeout denotes the timeout per question; with \f(CW\*(C`mode=anyorder\*(C'\fR it denotes the timeout per byte received from the stream or questions. .Sp \&\f(CW\*(C`talk\*(C'\fR is a reference to an array that contains alternating questions and answers. Questions are regular expressions and answers are literal strings. The Expect module watches the stream from the execution of the external program (\f(CW\*(C`perl Makefile.PL\*(C'\fR, \f(CW\*(C`perl Build.PL\*(C'\fR, \f(CW\*(C`make\*(C'\fR, etc.). .Sp For \f(CW\*(C`mode=deterministic\*(C'\fR, the \s-1CPAN\s0.pm injects the corresponding answer as soon as the stream matches the regular expression. .Sp For \f(CW\*(C`mode=anyorder\*(C'\fR \s-1CPAN\s0.pm answers a question as soon as the timeout is reached for the next byte in the input stream. In this mode you can use the \f(CW\*(C`reuse\*(C'\fR parameter to decide what will happen with a question-answer pair after it has been used. In the default case (reuse=0) it is removed from the array, avoiding being used again accidentally. If you want to answer the question \f(CW\*(C`Do you really want to do that\*(C'\fR several times, then it must be included in the array at least as often as you want this answer to be given. Setting the parameter \f(CW\*(C`reuse\*(C'\fR to 1 makes this repetition unnecessary. .IP "env [hash]" 4 .IX Item "env [hash]" Environment variables to be set during the command .IP "expect [array]" 4 .IX Item "expect [array]" You must install the \f(CW\*(C`Expect\*(C'\fR module to use \f(CW\*(C`expect\*(C'\fR. \s-1CPAN\s0.pm does not install it for you. .Sp \&\f(CW\*(C`expect: \*(C'\fR is a short notation for this \f(CW\*(C`eexpect\*(C'\fR: .Sp .Vb 4 \& eexpect: \& mode: deterministic \& timeout: 15 \& talk: .Ve .ie n .SS "Schema verification with ""Kwalify""" .el .SS "Schema verification with \f(CWKwalify\fP" .IX Subsection "Schema verification with Kwalify" If you have the \f(CW\*(C`Kwalify\*(C'\fR module installed (which is part of the Bundle::CPANxxl), then all your distroprefs files are checked for syntactic correctness. .SS "Example Distroprefs Files" .IX Subsection "Example Distroprefs Files" \&\f(CW\*(C`CPAN.pm\*(C'\fR comes with a collection of example \s-1YAML\s0 files. Note that these are really just examples and should not be used without care because they cannot fit everybody's purpose. After all, the authors of the packages that ask questions had a need to ask, so you should watch their questions and adjust the examples to your environment and your needs. You have been warned:\-) .SH "PROGRAMMER'S INTERFACE" .IX Header "PROGRAMMER'S INTERFACE" If you do not enter the shell, shell commands are available both as methods (\f(CW\*(C`CPAN::Shell\->install(...)\*(C'\fR) and as functions in the calling package (\f(CW\*(C`install(...)\*(C'\fR). Before calling low-level commands, it makes sense to initialize components of \s-1CPAN\s0 you need, e.g.: .PP .Vb 3 \& CPAN::HandleConfig\->load; \& CPAN::Shell::setup_output; \& CPAN::Index\->reload; .Ve .PP High-level commands do such initializations automatically. .PP There's currently only one class that has a stable interface \- CPAN::Shell. All commands that are available in the \s-1CPAN\s0 shell are methods of the class CPAN::Shell. The arguments on the commandline are passed as arguments to the method. .PP So if you take for example the shell command .PP .Vb 1 \& notest install A B C .Ve .PP the actually executed command is .PP .Vb 1 \& CPAN::Shell\->notest("install","A","B","C"); .Ve .PP Each of the commands that produce listings of modules (\f(CW\*(C`r\*(C'\fR, \&\f(CW\*(C`autobundle\*(C'\fR, \f(CW\*(C`u\*(C'\fR) also return a list of the IDs of all modules within the list. .IP "expand($type,@things)" 2 .IX Item "expand($type,@things)" The IDs of all objects available within a program are strings that can be expanded to the corresponding real objects with the \&\f(CW\*(C`CPAN::Shell\->expand("Module",@things)\*(C'\fR method. Expand returns a list of CPAN::Module objects according to the \f(CW@things\fR arguments given. In scalar context, it returns only the first element of the list. .IP "expandany(@things)" 2 .IX Item "expandany(@things)" Like expand, but returns objects of the appropriate type, i.e. CPAN::Bundle objects for bundles, CPAN::Module objects for modules, and CPAN::Distribution objects for distributions. Note: it does not expand to CPAN::Author objects. .IP "Programming Examples" 2 .IX Item "Programming Examples" This enables the programmer to do operations that combine functionalities that are available in the shell. .Sp .Vb 2 \& # install everything that is outdated on my disk: \& perl \-MCPAN \-e \*(AqCPAN::Shell\->install(CPAN::Shell\->r)\*(Aq \& \& # install my favorite programs if necessary: \& for $mod (qw(Net::FTP Digest::SHA Data::Dumper)) { \& CPAN::Shell\->install($mod); \& } \& \& # list all modules on my disk that have no VERSION number \& for $mod (CPAN::Shell\->expand("Module","/./")) { \& next unless $mod\->inst_file; \& # MakeMaker convention for undefined $VERSION: \& next unless $mod\->inst_version eq "undef"; \& print "No VERSION in ", $mod\->id, "\en"; \& } \& \& # find out which distribution on CPAN contains a module: \& print CPAN::Shell\->expand("Module","Apache::Constants")\->cpan_file .Ve .Sp Or if you want to schedule a \fIcron\fR job to watch \s-1CPAN,\s0 you could list all modules that need updating. First a quick and dirty way: .Sp .Vb 1 \& perl \-e \*(Aquse CPAN; CPAN::Shell\->r;\*(Aq .Ve .Sp If you don't want any output should all modules be up to date, parse the output of above command for the regular expression \f(CW\*(C`/modules are up to date/\*(C'\fR and decide to mail the output only if it doesn't match. .Sp If you prefer to do it more in a programmerish style in one single process, something like this may better suit you: .Sp .Vb 7 \& # list all modules on my disk that have newer versions on CPAN \& for $mod (CPAN::Shell\->expand("Module","/./")) { \& next unless $mod\->inst_file; \& next if $mod\->uptodate; \& printf "Module %s is installed as %s, could be updated to %s from CPAN\en", \& $mod\->id, $mod\->inst_version, $mod\->cpan_version; \& } .Ve .Sp If that gives too much output every day, you may want to watch only for three modules. You can write .Sp .Vb 1 \& for $mod (CPAN::Shell\->expand("Module","/Apache|LWP|CGI/")) { .Ve .Sp as the first line instead. Or you can combine some of the above tricks: .Sp .Vb 5 \& # watch only for a new mod_perl module \& $mod = CPAN::Shell\->expand("Module","mod_perl"); \& exit if $mod\->uptodate; \& # new mod_perl arrived, let me know all update recommendations \& CPAN::Shell\->r; .Ve .SS "Methods in the other Classes" .IX Subsection "Methods in the other Classes" .IP "\fBCPAN::Author::as_glimpse()\fR" 4 .IX Item "CPAN::Author::as_glimpse()" Returns a one-line description of the author .IP "\fBCPAN::Author::as_string()\fR" 4 .IX Item "CPAN::Author::as_string()" Returns a multi-line description of the author .IP "\fBCPAN::Author::email()\fR" 4 .IX Item "CPAN::Author::email()" Returns the author's email address .IP "\fBCPAN::Author::fullname()\fR" 4 .IX Item "CPAN::Author::fullname()" Returns the author's name .IP "\fBCPAN::Author::name()\fR" 4 .IX Item "CPAN::Author::name()" An alias for fullname .IP "\fBCPAN::Bundle::as_glimpse()\fR" 4 .IX Item "CPAN::Bundle::as_glimpse()" Returns a one-line description of the bundle .IP "\fBCPAN::Bundle::as_string()\fR" 4 .IX Item "CPAN::Bundle::as_string()" Returns a multi-line description of the bundle .IP "\fBCPAN::Bundle::clean()\fR" 4 .IX Item "CPAN::Bundle::clean()" Recursively runs the \f(CW\*(C`clean\*(C'\fR method on all items contained in the bundle. .IP "\fBCPAN::Bundle::contains()\fR" 4 .IX Item "CPAN::Bundle::contains()" Returns a list of objects' IDs contained in a bundle. The associated objects may be bundles, modules or distributions. .IP "CPAN::Bundle::force($method,@args)" 4 .IX Item "CPAN::Bundle::force($method,@args)" Forces \s-1CPAN\s0 to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that \s-1CPAN\s0.pm does not refuse to take the action. The \f(CW\*(C`force\*(C'\fR is passed recursively to all contained objects. See also the section above on the \f(CW\*(C`force\*(C'\fR and the \f(CW\*(C`fforce\*(C'\fR pragma. .IP "\fBCPAN::Bundle::get()\fR" 4 .IX Item "CPAN::Bundle::get()" Recursively runs the \f(CW\*(C`get\*(C'\fR method on all items contained in the bundle .IP "\fBCPAN::Bundle::inst_file()\fR" 4 .IX Item "CPAN::Bundle::inst_file()" Returns the highest installed version of the bundle in either \f(CW@INC\fR or \&\f(CW\*(C`$CPAN::Config\->{cpan_home}\*(C'\fR. Note that this is different from CPAN::Module::inst_file. .IP "\fBCPAN::Bundle::inst_version()\fR" 4 .IX Item "CPAN::Bundle::inst_version()" Like CPAN::Bundle::inst_file, but returns the \f(CW$VERSION\fR .IP "\fBCPAN::Bundle::uptodate()\fR" 4 .IX Item "CPAN::Bundle::uptodate()" Returns 1 if the bundle itself and all its members are up-to-date. .IP "\fBCPAN::Bundle::install()\fR" 4 .IX Item "CPAN::Bundle::install()" Recursively runs the \f(CW\*(C`install\*(C'\fR method on all items contained in the bundle .IP "\fBCPAN::Bundle::make()\fR" 4 .IX Item "CPAN::Bundle::make()" Recursively runs the \f(CW\*(C`make\*(C'\fR method on all items contained in the bundle .IP "\fBCPAN::Bundle::readme()\fR" 4 .IX Item "CPAN::Bundle::readme()" Recursively runs the \f(CW\*(C`readme\*(C'\fR method on all items contained in the bundle .IP "\fBCPAN::Bundle::test()\fR" 4 .IX Item "CPAN::Bundle::test()" Recursively runs the \f(CW\*(C`test\*(C'\fR method on all items contained in the bundle .IP "\fBCPAN::Distribution::as_glimpse()\fR" 4 .IX Item "CPAN::Distribution::as_glimpse()" Returns a one-line description of the distribution .IP "\fBCPAN::Distribution::as_string()\fR" 4 .IX Item "CPAN::Distribution::as_string()" Returns a multi-line description of the distribution .IP "CPAN::Distribution::author" 4 .IX Item "CPAN::Distribution::author" Returns the CPAN::Author object of the maintainer who uploaded this distribution .IP "\fBCPAN::Distribution::pretty_id()\fR" 4 .IX Item "CPAN::Distribution::pretty_id()" Returns a string of the form \*(L"\s-1AUTHORID/TARBALL\*(R",\s0 where \s-1AUTHORID\s0 is the author's \s-1PAUSE ID\s0 and \s-1TARBALL\s0 is the distribution filename. .IP "\fBCPAN::Distribution::base_id()\fR" 4 .IX Item "CPAN::Distribution::base_id()" Returns the distribution filename without any archive suffix. E.g \&\*(L"Foo\-Bar\-0.01\*(R" .IP "\fBCPAN::Distribution::clean()\fR" 4 .IX Item "CPAN::Distribution::clean()" Changes to the directory where the distribution has been unpacked and runs \f(CW\*(C`make clean\*(C'\fR there. .IP "\fBCPAN::Distribution::containsmods()\fR" 4 .IX Item "CPAN::Distribution::containsmods()" Returns a list of IDs of modules contained in a distribution file. Works only for distributions listed in the 02packages.details.txt.gz file. This typically means that just most recent version of a distribution is covered. .IP "\fBCPAN::Distribution::cvs_import()\fR" 4 .IX Item "CPAN::Distribution::cvs_import()" Changes to the directory where the distribution has been unpacked and runs something like .Sp .Vb 1 \& cvs \-d $cvs_root import \-m $cvs_log $cvs_dir $userid v$version .Ve .Sp there. .IP "\fBCPAN::Distribution::dir()\fR" 4 .IX Item "CPAN::Distribution::dir()" Returns the directory into which this distribution has been unpacked. .IP "CPAN::Distribution::force($method,@args)" 4 .IX Item "CPAN::Distribution::force($method,@args)" Forces \s-1CPAN\s0 to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that \s-1CPAN\s0.pm does not refuse to take the action. See also the section above on the \&\f(CW\*(C`force\*(C'\fR and the \f(CW\*(C`fforce\*(C'\fR pragma. .IP "\fBCPAN::Distribution::get()\fR" 4 .IX Item "CPAN::Distribution::get()" Downloads the distribution from \s-1CPAN\s0 and unpacks it. Does nothing if the distribution has already been downloaded and unpacked within the current session. .IP "\fBCPAN::Distribution::install()\fR" 4 .IX Item "CPAN::Distribution::install()" Changes to the directory where the distribution has been unpacked and runs the external command \f(CW\*(C`make install\*(C'\fR there. If \f(CW\*(C`make\*(C'\fR has not yet been run, it will be run first. A \f(CW\*(C`make test\*(C'\fR is issued in any case and if this fails, the install is cancelled. The cancellation can be avoided by letting \f(CW\*(C`force\*(C'\fR run the \f(CW\*(C`install\*(C'\fR for you. .Sp This install method only has the power to install the distribution if there are no dependencies in the way. To install an object along with all its dependencies, use CPAN::Shell\->install. .Sp Note that \fBinstall()\fR gives no meaningful return value. See \fBuptodate()\fR. .IP "\fBCPAN::Distribution::isa_perl()\fR" 4 .IX Item "CPAN::Distribution::isa_perl()" Returns 1 if this distribution file seems to be a perl distribution. Normally this is derived from the file name only, but the index from \&\s-1CPAN\s0 can contain a hint to achieve a return value of true for other filenames too. .IP "\fBCPAN::Distribution::look()\fR" 4 .IX Item "CPAN::Distribution::look()" Changes to the directory where the distribution has been unpacked and opens a subshell there. Exiting the subshell returns. .IP "\fBCPAN::Distribution::make()\fR" 4 .IX Item "CPAN::Distribution::make()" First runs the \f(CW\*(C`get\*(C'\fR method to make sure the distribution is downloaded and unpacked. Changes to the directory where the distribution has been unpacked and runs the external commands \f(CW\*(C`perl Makefile.PL\*(C'\fR or \f(CW\*(C`perl Build.PL\*(C'\fR and \f(CW\*(C`make\*(C'\fR there. .IP "\fBCPAN::Distribution::perldoc()\fR" 4 .IX Item "CPAN::Distribution::perldoc()" Downloads the pod documentation of the file associated with a distribution (in \s-1HTML\s0 format) and runs it through the external command \fIlynx\fR specified in \f(CW\*(C`$CPAN::Config\->{lynx}\*(C'\fR. If \fIlynx\fR isn't available, it converts it to plain text with the external command \fIhtml2text\fR and runs it through the pager specified in \f(CW\*(C`$CPAN::Config\->{pager}\*(C'\fR. .IP "\fBCPAN::Distribution::prefs()\fR" 4 .IX Item "CPAN::Distribution::prefs()" Returns the hash reference from the first matching \s-1YAML\s0 file that the user has deposited in the \f(CW\*(C`prefs_dir/\*(C'\fR directory. The first succeeding match wins. The files in the \f(CW\*(C`prefs_dir/\*(C'\fR are processed alphabetically, and the canonical distro name (e.g. AUTHOR/Foo\-Bar\-3.14.tar.gz) is matched against the regular expressions stored in the \f(CW$root\fR\->{match}{distribution} attribute value. Additionally all module names contained in a distribution are matched against the regular expressions in the \f(CW$root\fR\->{match}{module} attribute value. The two match values are ANDed together. Each of the two attributes are optional. .IP "\fBCPAN::Distribution::prereq_pm()\fR" 4 .IX Item "CPAN::Distribution::prereq_pm()" Returns the hash reference that has been announced by a distribution as the \f(CW\*(C`requires\*(C'\fR and \f(CW\*(C`build_requires\*(C'\fR elements. These can be declared either by the \f(CW\*(C`META.yml\*(C'\fR (if authoritative) or can be deposited after the run of \f(CW\*(C`Build.PL\*(C'\fR in the file \f(CW\*(C`./_build/prereqs\*(C'\fR or after the run of \f(CW\*(C`Makfile.PL\*(C'\fR written as the \f(CW\*(C`PREREQ_PM\*(C'\fR hash in a comment in the produced \f(CW\*(C`Makefile\*(C'\fR. \fINote\fR: this method only works after an attempt has been made to \f(CW\*(C`make\*(C'\fR the distribution. Returns undef otherwise. .IP "\fBCPAN::Distribution::readme()\fR" 4 .IX Item "CPAN::Distribution::readme()" Downloads the \s-1README\s0 file associated with a distribution and runs it through the pager specified in \f(CW\*(C`$CPAN::Config\->{pager}\*(C'\fR. .IP "\fBCPAN::Distribution::reports()\fR" 4 .IX Item "CPAN::Distribution::reports()" Downloads report data for this distribution from www.cpantesters.org and displays a subset of them. .IP "\fBCPAN::Distribution::read_yaml()\fR" 4 .IX Item "CPAN::Distribution::read_yaml()" Returns the content of the \s-1META\s0.yml of this distro as a hashref. Note: works only after an attempt has been made to \f(CW\*(C`make\*(C'\fR the distribution. Returns undef otherwise. Also returns undef if the content of \s-1META\s0.yml is not authoritative. (The rules about what exactly makes the content authoritative are still in flux.) .IP "\fBCPAN::Distribution::test()\fR" 4 .IX Item "CPAN::Distribution::test()" Changes to the directory where the distribution has been unpacked and runs \f(CW\*(C`make test\*(C'\fR there. .IP "\fBCPAN::Distribution::uptodate()\fR" 4 .IX Item "CPAN::Distribution::uptodate()" Returns 1 if all the modules contained in the distribution are up-to-date. Relies on containsmods. .IP "\fBCPAN::Index::force_reload()\fR" 4 .IX Item "CPAN::Index::force_reload()" Forces a reload of all indices. .IP "\fBCPAN::Index::reload()\fR" 4 .IX Item "CPAN::Index::reload()" Reloads all indices if they have not been read for more than \&\f(CW\*(C`$CPAN::Config\->{index_expire}\*(C'\fR days. .IP "\fBCPAN::InfoObj::dump()\fR" 4 .IX Item "CPAN::InfoObj::dump()" CPAN::Author, CPAN::Bundle, CPAN::Module, and CPAN::Distribution inherit this method. It prints the data structure associated with an object. Useful for debugging. Note: the data structure is considered internal and thus subject to change without notice. .IP "\fBCPAN::Module::as_glimpse()\fR" 4 .IX Item "CPAN::Module::as_glimpse()" Returns a one-line description of the module in four columns: The first column contains the word \f(CW\*(C`Module\*(C'\fR, the second column consists of one character: an equals sign if this module is already installed and up-to-date, a less-than sign if this module is installed but can be upgraded, and a space if the module is not installed. The third column is the name of the module and the fourth column gives maintainer or distribution information. .IP "\fBCPAN::Module::as_string()\fR" 4 .IX Item "CPAN::Module::as_string()" Returns a multi-line description of the module .IP "\fBCPAN::Module::clean()\fR" 4 .IX Item "CPAN::Module::clean()" Runs a clean on the distribution associated with this module. .IP "\fBCPAN::Module::cpan_file()\fR" 4 .IX Item "CPAN::Module::cpan_file()" Returns the filename on \s-1CPAN\s0 that is associated with the module. .IP "\fBCPAN::Module::cpan_version()\fR" 4 .IX Item "CPAN::Module::cpan_version()" Returns the latest version of this module available on \s-1CPAN.\s0 .IP "\fBCPAN::Module::cvs_import()\fR" 4 .IX Item "CPAN::Module::cvs_import()" Runs a cvs_import on the distribution associated with this module. .IP "\fBCPAN::Module::description()\fR" 4 .IX Item "CPAN::Module::description()" Returns a 44 character description of this module. Only available for modules listed in The Module List (CPAN/modules/00modlist.long.html or 00modlist.long.txt.gz) .IP "\fBCPAN::Module::distribution()\fR" 4 .IX Item "CPAN::Module::distribution()" Returns the CPAN::Distribution object that contains the current version of this module. .IP "\fBCPAN::Module::dslip_status()\fR" 4 .IX Item "CPAN::Module::dslip_status()" Returns a hash reference. The keys of the hash are the letters \f(CW\*(C`D\*(C'\fR, \&\f(CW\*(C`S\*(C'\fR, \f(CW\*(C`L\*(C'\fR, \f(CW\*(C`I\*(C'\fR, and

, for development status, support level, language, interface and public licence respectively. The data for the \&\s-1DSLIP\s0 status are collected by pause.perl.org when authors register their namespaces. The values of the 5 hash elements are one-character words whose meaning is described in the table below. There are also 5 hash elements \f(CW\*(C`DV\*(C'\fR, \f(CW\*(C`SV\*(C'\fR, \f(CW\*(C`LV\*(C'\fR, \f(CW\*(C`IV\*(C'\fR, and <\s-1PV\s0> that carry a more verbose value of the 5 status variables. .Sp Where the '\s-1DSLIP\s0' characters have the following meanings: .Sp .Vb 7 \& D \- Development Stage (Note: *NO IMPLIED TIMESCALES*): \& i \- Idea, listed to gain consensus or as a placeholder \& c \- under construction but pre\-alpha (not yet released) \& a/b \- Alpha/Beta testing \& R \- Released \& M \- Mature (no rigorous definition) \& S \- Standard, supplied with Perl 5 \& \& S \- Support Level: \& m \- Mailing\-list \& d \- Developer \& u \- Usenet newsgroup comp.lang.perl.modules \& n \- None known, try comp.lang.perl.modules \& a \- abandoned; volunteers welcome to take over maintenance \& \& L \- Language Used: \& p \- Perl\-only, no compiler needed, should be platform independent \& c \- C and perl, a C compiler will be needed \& h \- Hybrid, written in perl with optional C code, no compiler needed \& + \- C++ and perl, a C++ compiler will be needed \& o \- perl and another language other than C or C++ \& \& I \- Interface Style \& f \- plain Functions, no references used \& h \- hybrid, object and function interfaces available \& n \- no interface at all (huh?) \& r \- some use of unblessed References or ties \& O \- Object oriented using blessed references and/or inheritance \& \& P \- Public License \& p \- Standard\-Perl: user may choose between GPL and Artistic \& g \- GPL: GNU General Public License \& l \- LGPL: "GNU Lesser General Public License" (previously known as \& "GNU Library General Public License") \& b \- BSD: The BSD License \& a \- Artistic license alone \& 2 \- Artistic license 2.0 or later \& o \- open source: approved by www.opensource.org \& d \- allows distribution without restrictions \& r \- restricted distribution \& n \- no license at all .Ve .IP "CPAN::Module::force($method,@args)" 4 .IX Item "CPAN::Module::force($method,@args)" Forces \s-1CPAN\s0 to perform a task it would normally refuse to do. Force takes as arguments a method name to be invoked and any number of additional arguments to pass that method. The internals of the object get the needed changes so that \s-1CPAN\s0.pm does not refuse to take the action. See also the section above on the \&\f(CW\*(C`force\*(C'\fR and the \f(CW\*(C`fforce\*(C'\fR pragma. .IP "\fBCPAN::Module::get()\fR" 4 .IX Item "CPAN::Module::get()" Runs a get on the distribution associated with this module. .IP "\fBCPAN::Module::inst_file()\fR" 4 .IX Item "CPAN::Module::inst_file()" Returns the filename of the module found in \f(CW@INC\fR. The first file found is reported, just as perl itself stops searching \f(CW@INC\fR once it finds a module. .IP "\fBCPAN::Module::available_file()\fR" 4 .IX Item "CPAN::Module::available_file()" Returns the filename of the module found in \s-1PERL5LIB\s0 or \f(CW@INC\fR. The first file found is reported. The advantage of this method over \&\f(CW\*(C`inst_file\*(C'\fR is that modules that have been tested but not yet installed are included because \s-1PERL5LIB\s0 keeps track of tested modules. .IP "\fBCPAN::Module::inst_version()\fR" 4 .IX Item "CPAN::Module::inst_version()" Returns the version number of the installed module in readable format. .IP "\fBCPAN::Module::available_version()\fR" 4 .IX Item "CPAN::Module::available_version()" Returns the version number of the available module in readable format. .IP "\fBCPAN::Module::install()\fR" 4 .IX Item "CPAN::Module::install()" Runs an \f(CW\*(C`install\*(C'\fR on the distribution associated with this module. .IP "\fBCPAN::Module::look()\fR" 4 .IX Item "CPAN::Module::look()" Changes to the directory where the distribution associated with this module has been unpacked and opens a subshell there. Exiting the subshell returns. .IP "\fBCPAN::Module::make()\fR" 4 .IX Item "CPAN::Module::make()" Runs a \f(CW\*(C`make\*(C'\fR on the distribution associated with this module. .IP "\fBCPAN::Module::manpage_headline()\fR" 4 .IX Item "CPAN::Module::manpage_headline()" If module is installed, peeks into the module's manpage, reads the headline, and returns it. Moreover, if the module has been downloaded within this session, does the equivalent on the downloaded module even if it hasn't been installed yet. .IP "\fBCPAN::Module::perldoc()\fR" 4 .IX Item "CPAN::Module::perldoc()" Runs a \f(CW\*(C`perldoc\*(C'\fR on this module. .IP "\fBCPAN::Module::readme()\fR" 4 .IX Item "CPAN::Module::readme()" Runs a \f(CW\*(C`readme\*(C'\fR on the distribution associated with this module. .IP "\fBCPAN::Module::reports()\fR" 4 .IX Item "CPAN::Module::reports()" Calls the \fBreports()\fR method on the associated distribution object. .IP "\fBCPAN::Module::test()\fR" 4 .IX Item "CPAN::Module::test()" Runs a \f(CW\*(C`test\*(C'\fR on the distribution associated with this module. .IP "\fBCPAN::Module::uptodate()\fR" 4 .IX Item "CPAN::Module::uptodate()" Returns 1 if the module is installed and up-to-date. .IP "\fBCPAN::Module::userid()\fR" 4 .IX Item "CPAN::Module::userid()" Returns the author's \s-1ID\s0 of the module. .SS "Cache Manager" .IX Subsection "Cache Manager" Currently the cache manager only keeps track of the build directory ($CPAN::Config\->{build_dir}). It is a simple \s-1FIFO\s0 mechanism that deletes complete directories below \f(CW\*(C`build_dir\*(C'\fR as soon as the size of all directories there gets bigger than \f(CW$CPAN::Config\fR\->{build_cache} (in \s-1MB\s0). The contents of this cache may be used for later re-installations that you intend to do manually, but will never be trusted by \s-1CPAN\s0 itself. This is due to the fact that the user might use these directories for building modules on different architectures. .PP There is another directory ($CPAN::Config\->{keep_source_where}) where the original distribution files are kept. This directory is not covered by the cache manager and must be controlled by the user. If you choose to have the same directory as build_dir and as keep_source_where directory, then your sources will be deleted with the same fifo mechanism. .SS "Bundles" .IX Subsection "Bundles" A bundle is just a perl module in the namespace Bundle:: that does not define any functions or methods. It usually only contains documentation. .PP It starts like a perl module with a package declaration and a \f(CW$VERSION\fR variable. After that the pod section looks like any other pod with the only difference being that \fIone special pod section\fR exists starting with (verbatim): .PP .Vb 1 \& =head1 CONTENTS .Ve .PP In this pod section each line obeys the format .PP .Vb 1 \& Module_Name [Version_String] [\- optional text] .Ve .PP The only required part is the first field, the name of a module (e.g. Foo::Bar, i.e. \fInot\fR the name of the distribution file). The rest of the line is optional. The comment part is delimited by a dash just as in the man page header. .PP The distribution of a bundle should follow the same convention as other distributions. .PP Bundles are treated specially in the \s-1CPAN\s0 package. If you say 'install Bundle::Tkkit' (assuming such a bundle exists), \s-1CPAN\s0 will install all the modules in the \s-1CONTENTS\s0 section of the pod. You can install your own Bundles locally by placing a conformant Bundle file somewhere into your \f(CW@INC\fR path. The \fBautobundle()\fR command which is available in the shell interface does that for you by including all currently installed modules in a snapshot bundle file. .SH "PREREQUISITES" .IX Header "PREREQUISITES" The \s-1CPAN\s0 program is trying to depend on as little as possible so the user can use it in hostile environment. It works better the more goodies the environment provides. For example if you try in the \s-1CPAN\s0 shell .PP .Vb 1 \& install Bundle::CPAN .Ve .PP or .PP .Vb 1 \& install Bundle::CPANxxl .Ve .PP you will find the shell more convenient than the bare shell before. .PP If you have a local mirror of \s-1CPAN\s0 and can access all files with \&\*(L"file:\*(R" URLs, then you only need a perl later than perl5.003 to run this module. Otherwise Net::FTP is strongly recommended. \s-1LWP\s0 may be required for non-UNIX systems, or if your nearest \s-1CPAN\s0 site is associated with a \s-1URL\s0 that is not \f(CW\*(C`ftp:\*(C'\fR. .PP If you have neither Net::FTP nor \s-1LWP,\s0 there is a fallback mechanism implemented for an external ftp command or for an external lynx command. .SH "UTILITIES" .IX Header "UTILITIES" .SS "Finding packages and \s-1VERSION\s0" .IX Subsection "Finding packages and VERSION" This module presumes that all packages on \s-1CPAN\s0 .IP "\(bu" 2 declare their \f(CW$VERSION\fR variable in an easy to parse manner. This prerequisite can hardly be relaxed because it consumes far too much memory to load all packages into the running program just to determine the \f(CW$VERSION\fR variable. Currently all programs that are dealing with version use something like this .Sp .Vb 2 \& perl \-MExtUtils::MakeMaker \-le \e \& \*(Aqprint MM\->parse_version(shift)\*(Aq filename .Ve .Sp If you are author of a package and wonder if your \f(CW$VERSION\fR can be parsed, please try the above method. .IP "\(bu" 2 come as compressed or gzipped tarfiles or as zip files and contain a \&\f(CW\*(C`Makefile.PL\*(C'\fR or \f(CW\*(C`Build.PL\*(C'\fR (well, we try to handle a bit more, but with little enthusiasm). .SS "Debugging" .IX Subsection "Debugging" Debugging this module is more than a bit complex due to interference from the software producing the indices on \s-1CPAN,\s0 the mirroring process on \s-1CPAN,\s0 packaging, configuration, synchronicity, and even (gasp!) due to bugs within the \s-1CPAN\s0.pm module itself. .PP For debugging the code of \s-1CPAN\s0.pm itself in interactive mode, some debugging aid can be turned on for most packages within \&\s-1CPAN\s0.pm with one of .IP "o debug package..." 2 .IX Item "o debug package..." sets debug mode for packages. .IP "o debug \-package..." 2 .IX Item "o debug -package..." unsets debug mode for packages. .IP "o debug all" 2 .IX Item "o debug all" turns debugging on for all packages. .IP "o debug number" 2 .IX Item "o debug number" .PP which sets the debugging packages directly. Note that \f(CW\*(C`o debug 0\*(C'\fR turns debugging off. .PP What seems a successful strategy is the combination of \f(CW\*(C`reload cpan\*(C'\fR and the debugging switches. Add a new debug statement while running in the shell and then issue a \f(CW\*(C`reload cpan\*(C'\fR and see the new debugging messages immediately without losing the current context. .PP \&\f(CW\*(C`o debug\*(C'\fR without an argument lists the valid package names and the current set of packages in debugging mode. \f(CW\*(C`o debug\*(C'\fR has built-in completion support. .PP For debugging of \s-1CPAN\s0 data there is the \f(CW\*(C`dump\*(C'\fR command which takes the same arguments as make/test/install and outputs each object's Data::Dumper dump. If an argument looks like a perl variable and contains one of \f(CW\*(C`$\*(C'\fR, \f(CW\*(C`@\*(C'\fR or \f(CW\*(C`%\*(C'\fR, it is \fBeval()\fRed and fed to Data::Dumper directly. .SS "Floppy, Zip, Offline Mode" .IX Subsection "Floppy, Zip, Offline Mode" \&\s-1CPAN\s0.pm works nicely without network access, too. If you maintain machines that are not networked at all, you should consider working with \f(CW\*(C`file:\*(C'\fR URLs. You'll have to collect your modules somewhere first. So you might use \s-1CPAN\s0.pm to put together all you need on a networked machine. Then copy the \f(CW$CPAN::Config\fR\->{keep_source_where} (but not \&\f(CW$CPAN::Config\fR\->{build_dir}) directory on a floppy. This floppy is kind of a personal \s-1CPAN. CPAN\s0.pm on the non-networked machines works nicely with this floppy. See also below the paragraph about CD-ROM support. .SS "Basic Utilities for Programmers" .IX Subsection "Basic Utilities for Programmers" .IP "has_inst($module)" 2 .IX Item "has_inst($module)" Returns true if the module is installed. Used to load all modules into the running \s-1CPAN\s0.pm that are considered optional. The config variable \&\f(CW\*(C`dontload_list\*(C'\fR intercepts the \f(CW\*(C`has_inst()\*(C'\fR call such that an optional module is not loaded despite being available. For example, the following command will prevent \f(CW\*(C`YAML.pm\*(C'\fR from being loaded: .Sp .Vb 1 \& cpan> o conf dontload_list push YAML .Ve .Sp See the source for details. .IP "use_inst($module)" 2 .IX Item "use_inst($module)" Similary to \fBhas_inst()\fR tries to load optional library but also dies if library is not available .IP "has_usable($module)" 2 .IX Item "has_usable($module)" Returns true if the module is installed and in a usable state. Only useful for a handful of modules that are used internally. See the source for details. .IP "instance($module)" 2 .IX Item "instance($module)" The constructor for all the singletons used to represent modules, distributions, authors, and bundles. If the object already exists, this method returns the object; otherwise, it calls the constructor. .IP "\fBfrontend()\fR" 2 .IX Item "frontend()" .PD 0 .IP "frontend($new_frontend)" 2 .IX Item "frontend($new_frontend)" .PD Getter/setter for frontend object. Method just allows to subclass \s-1CPAN\s0.pm. .SH "SECURITY" .IX Header "SECURITY" There's no strong security layer in \s-1CPAN\s0.pm. \s-1CPAN\s0.pm helps you to install foreign, unmasked, unsigned code on your machine. We compare to a checksum that comes from the net just as the distribution file itself. But we try to make it easy to add security on demand: .SS "Cryptographically signed modules" .IX Subsection "Cryptographically signed modules" Since release 1.77, \s-1CPAN\s0.pm has been able to verify cryptographically signed module distributions using Module::Signature. The \s-1CPAN\s0 modules can be signed by their authors, thus giving more security. The simple unsigned \s-1MD5\s0 checksums that were used before by \s-1CPAN\s0 protect mainly against accidental file corruption. .PP You will need to have Module::Signature installed, which in turn requires that you have at least one of Crypt::OpenPGP module or the command-line \fIgpg\fR tool installed. .PP You will also need to be able to connect over the Internet to the public key servers, like pgp.mit.edu, and their port 11731 (the \s-1HKP\s0 protocol). .PP The configuration parameter check_sigs is there to turn signature checking on or off. .SH "EXPORT" .IX Header "EXPORT" Most functions in package \s-1CPAN\s0 are exported by default. The reason for this is that the primary use is intended for the cpan shell or for one-liners. .SH "ENVIRONMENT" .IX Header "ENVIRONMENT" When the \s-1CPAN\s0 shell enters a subshell via the look command, it sets the environment \s-1CPAN_SHELL_LEVEL\s0 to 1, or increments that variable if it is already set. .PP When \s-1CPAN\s0 runs, it sets the environment variable \s-1PERL5_CPAN_IS_RUNNING\s0 to the \s-1ID\s0 of the running process. It also sets \&\s-1PERL5_CPANPLUS_IS_RUNNING\s0 to prevent runaway processes which could happen with older versions of Module::Install. .PP When running \f(CW\*(C`perl Makefile.PL\*(C'\fR, the environment variable \&\f(CW\*(C`PERL5_CPAN_IS_EXECUTING\*(C'\fR is set to the full path of the \&\f(CW\*(C`Makefile.PL\*(C'\fR that is being executed. This prevents runaway processes with newer versions of Module::Install. .PP When the config variable ftp_passive is set, all downloads will be run with the environment variable \s-1FTP_PASSIVE\s0 set to this value. This is in general a good idea as it influences both Net::FTP and \s-1LWP\s0 based connections. The same effect can be achieved by starting the cpan shell with this environment variable set. For Net::FTP alone, one can also always set passive mode by running libnetcfg. .SH "POPULATE AN INSTALLATION WITH LOTS OF MODULES" .IX Header "POPULATE AN INSTALLATION WITH LOTS OF MODULES" Populating a freshly installed perl with one's favorite modules is pretty easy if you maintain a private bundle definition file. To get a useful blueprint of a bundle definition file, the command autobundle can be used on the \s-1CPAN\s0 shell command line. This command writes a bundle definition file for all modules installed for the current perl interpreter. It's recommended to run this command once only, and from then on maintain the file manually under a private name, say Bundle/my_bundle.pm. With a clever bundle file you can then simply say .PP .Vb 1 \& cpan> install Bundle::my_bundle .Ve .PP then answer a few questions and go out for coffee (possibly even in a different city). .PP Maintaining a bundle definition file means keeping track of two things: dependencies and interactivity. \s-1CPAN\s0.pm sometimes fails on calculating dependencies because not all modules define all MakeMaker attributes correctly, so a bundle definition file should specify prerequisites as early as possible. On the other hand, it's annoying that so many distributions need some interactive configuring. So what you can try to accomplish in your private bundle file is to have the packages that need to be configured early in the file and the gentle ones later, so you can go out for coffee after a few minutes and leave \s-1CPAN\s0.pm to churn away unattended. .SH "WORKING WITH CPAN.pm BEHIND FIREWALLS" .IX Header "WORKING WITH CPAN.pm BEHIND FIREWALLS" Thanks to Graham Barr for contributing the following paragraphs about the interaction between perl, and various firewall configurations. For further information on firewalls, it is recommended to consult the documentation that comes with the \fIncftp\fR program. If you are unable to go through the firewall with a simple Perl setup, it is likely that you can configure \fIncftp\fR so that it works through your firewall. .SS "Three basic types of firewalls" .IX Subsection "Three basic types of firewalls" Firewalls can be categorized into three basic types. .IP "http firewall" 4 .IX Item "http firewall" This is when the firewall machine runs a web server, and to access the outside world, you must do so via that web server. If you set environment variables like http_proxy or ftp_proxy to values beginning with http://, or in your web browser you've proxy information set, then you know you are running behind an http firewall. .Sp To access servers outside these types of firewalls with perl (even for ftp), you need \s-1LWP\s0 or HTTP::Tiny. .IP "ftp firewall" 4 .IX Item "ftp firewall" This where the firewall machine runs an ftp server. This kind of firewall will only let you access ftp servers outside the firewall. This is usually done by connecting to the firewall with ftp, then entering a username like \*(L"user@outside.host.com\*(R". .Sp To access servers outside these type of firewalls with perl, you need Net::FTP. .IP "One-way visibility" 4 .IX Item "One-way visibility" One-way visibility means these firewalls try to make themselves invisible to users inside the firewall. An \s-1FTP\s0 data connection is normally created by sending your \s-1IP\s0 address to the remote server and then listening for the return connection. But the remote server will not be able to connect to you because of the firewall. For these types of firewall, \&\s-1FTP\s0 connections need to be done in a passive mode. .Sp There are two that I can think off. .RS 4 .IP "\s-1SOCKS\s0" 4 .IX Item "SOCKS" If you are using a \s-1SOCKS\s0 firewall, you will need to compile perl and link it with the \s-1SOCKS\s0 library. This is what is normally called a 'socksified' perl. With this executable you will be able to connect to servers outside the firewall as if it were not there. .IP "\s-1IP\s0 Masquerade" 4 .IX Item "IP Masquerade" This is when the firewall implemented in the kernel (via \s-1NAT,\s0 or networking address translation), it allows you to hide a complete network behind one \&\s-1IP\s0 address. With this firewall no special compiling is needed as you can access hosts directly. .Sp For accessing ftp servers behind such firewalls you usually need to set the environment variable \f(CW\*(C`FTP_PASSIVE\*(C'\fR or the config variable ftp_passive to a true value. .RE .RS 4 .RE .SS "Configuring lynx or ncftp for going through a firewall" .IX Subsection "Configuring lynx or ncftp for going through a firewall" If you can go through your firewall with e.g. lynx, presumably with a command such as .PP .Vb 1 \& /usr/local/bin/lynx \-pscott:tiger .Ve .PP then you would configure \s-1CPAN\s0.pm with the command .PP .Vb 1 \& o conf lynx "/usr/local/bin/lynx \-pscott:tiger" .Ve .PP That's all. Similarly for ncftp or ftp, you would configure something like .PP .Vb 1 \& o conf ncftp "/usr/bin/ncftp \-f /home/scott/ncftplogin.cfg" .Ve .PP Your mileage may vary... .SH "FAQ" .IX Header "FAQ" .IP "1)" 4 .IX Item "1)" I installed a new version of module X but \s-1CPAN\s0 keeps saying, I have the old version installed .Sp Probably you \fBdo\fR have the old version installed. This can happen if a module installs itself into a different directory in the \&\f(CW@INC\fR path than it was previously installed. This is not really a \&\s-1CPAN\s0.pm problem, you would have the same problem when installing the module manually. The easiest way to prevent this behaviour is to add the argument \f(CW\*(C`UNINST=1\*(C'\fR to the \f(CW\*(C`make install\*(C'\fR call, and that is why many people add this argument permanently by configuring .Sp .Vb 1 \& o conf make_install_arg UNINST=1 .Ve .IP "2)" 4 .IX Item "2)" So why is UNINST=1 not the default? .Sp Because there are people who have their precise expectations about who may install where in the \f(CW@INC\fR path and who uses which \f(CW@INC\fR array. In fine tuned environments \f(CW\*(C`UNINST=1\*(C'\fR can cause damage. .IP "3)" 4 .IX Item "3)" I want to clean up my mess, and install a new perl along with all modules I have. How do I go about it? .Sp Run the autobundle command for your old perl and optionally rename the resulting bundle file (e.g. Bundle/mybundle.pm), install the new perl with the Configure option prefix, e.g. .Sp .Vb 1 \& ./Configure \-Dprefix=/usr/local/perl\-5.6.78.9 .Ve .Sp Install the bundle file you produced in the first step with something like .Sp .Vb 1 \& cpan> install Bundle::mybundle .Ve .Sp and you're done. .IP "4)" 4 .IX Item "4)" When I install bundles or multiple modules with one command there is too much output to keep track of. .Sp You may want to configure something like .Sp .Vb 2 \& o conf make_arg "| tee \-ai /root/.cpan/logs/make.out" \& o conf make_install_arg "| tee \-ai /root/.cpan/logs/make_install.out" .Ve .Sp so that \s-1STDOUT\s0 is captured in a file for later inspection. .IP "5)" 4 .IX Item "5)" I am not root, how can I install a module in a personal directory? .Sp As of \s-1CPAN 1.9463,\s0 if you do not have permission to write the default perl library directories, \s-1CPAN\s0's configuration process will ask you whether you want to bootstrap , which makes keeping a personal perl library directory easy. .Sp Another thing you should bear in mind is that the \s-1UNINST\s0 parameter can be dangerous when you are installing into a private area because you might accidentally remove modules that other people depend on that are not using the private area. .IP "6)" 4 .IX Item "6)" How to get a package, unwrap it, and make a change before building it? .Sp Have a look at the \f(CW\*(C`look\*(C'\fR (!) command. .IP "7)" 4 .IX Item "7)" I installed a Bundle and had a couple of fails. When I retried, everything resolved nicely. Can this be fixed to work on first try? .Sp The reason for this is that \s-1CPAN\s0 does not know the dependencies of all modules when it starts out. To decide about the additional items to install, it just uses data found in the \s-1META\s0.yml file or the generated Makefile. An undetected missing piece breaks the process. But it may well be that your Bundle installs some prerequisite later than some depending item and thus your second try is able to resolve everything. Please note, \s-1CPAN\s0.pm does not know the dependency tree in advance and cannot sort the queue of things to install in a topologically correct order. It resolves perfectly well \fBif\fR all modules declare the prerequisites correctly with the \s-1PREREQ_PM\s0 attribute to MakeMaker or the \f(CW\*(C`requires\*(C'\fR stanza of Module::Build. For bundles which fail and you need to install often, it is recommended to sort the Bundle definition file manually. .IP "8)" 4 .IX Item "8)" In our intranet, we have many modules for internal use. How can I integrate these modules with \s-1CPAN\s0.pm but without uploading the modules to \s-1CPAN\s0? .Sp Have a look at the CPAN::Site module. .IP "9)" 4 .IX Item "9)" When I run \s-1CPAN\s0's shell, I get an error message about things in my \&\f(CW\*(C`/etc/inputrc\*(C'\fR (or \f(CW\*(C`~/.inputrc\*(C'\fR) file. .Sp These are readline issues and can only be fixed by studying readline configuration on your architecture and adjusting the referenced file accordingly. Please make a backup of the \f(CW\*(C`/etc/inputrc\*(C'\fR or \f(CW\*(C`~/.inputrc\*(C'\fR and edit them. Quite often harmless changes like uppercasing or lowercasing some arguments solves the problem. .IP "10)" 4 .IX Item "10)" Some authors have strange characters in their names. .Sp Internally \s-1CPAN\s0.pm uses the \s-1UTF\-8\s0 charset. If your terminal is expecting \s-1ISO\-8859\-1\s0 charset, a converter can be activated by setting term_is_latin to a true value in your config file. One way of doing so would be .Sp .Vb 1 \& cpan> o conf term_is_latin 1 .Ve .Sp If other charset support is needed, please file a bug report against \&\s-1CPAN\s0.pm at rt.cpan.org and describe your needs. Maybe we can extend the support or maybe \s-1UTF\-8\s0 terminals become widely available. .Sp Note: this config variable is deprecated and will be removed in a future version of \s-1CPAN\s0.pm. It will be replaced with the conventions around the family of \f(CW$LANG\fR and \f(CW$LC_\fR* environment variables. .IP "11)" 4 .IX Item "11)" When an install fails for some reason and then I correct the error condition and retry, \s-1CPAN\s0.pm refuses to install the module, saying \&\f(CW\*(C`Already tried without success\*(C'\fR. .Sp Use the force pragma like so .Sp .Vb 1 \& force install Foo::Bar .Ve .Sp Or you can use .Sp .Vb 1 \& look Foo::Bar .Ve .Sp and then \f(CW\*(C`make install\*(C'\fR directly in the subshell. .IP "12)" 4 .IX Item "12)" How do I install a \*(L"\s-1DEVELOPER RELEASE\*(R"\s0 of a module? .Sp By default, \s-1CPAN\s0 will install the latest non-developer release of a module. If you want to install a dev release, you have to specify the partial path starting with the author id to the tarball you wish to install, like so: .Sp .Vb 1 \& cpan> install KWILLIAMS/Module\-Build\-0.27_07.tar.gz .Ve .Sp Note that you can use the \f(CW\*(C`ls\*(C'\fR command to get this path listed. .IP "13)" 4 .IX Item "13)" How do I install a module and all its dependencies from the commandline, without being prompted for anything, despite my \s-1CPAN\s0 configuration (or lack thereof)? .Sp \&\s-1CPAN\s0 uses ExtUtils::MakeMaker's \fBprompt()\fR function to ask its questions, so if you set the \s-1PERL_MM_USE_DEFAULT\s0 environment variable, you shouldn't be asked any questions at all (assuming the modules you are installing are nice about obeying that variable as well): .Sp .Vb 1 \& % PERL_MM_USE_DEFAULT=1 perl \-MCPAN \-e \*(Aqinstall My::Module\*(Aq .Ve .IP "14)" 4 .IX Item "14)" How do I create a Module::Build based Build.PL derived from an ExtUtils::MakeMaker focused Makefile.PL? .Sp http://search.cpan.org/dist/Module\-Build\-Convert/ .IP "15)" 4 .IX Item "15)" I'm frequently irritated with the \s-1CPAN\s0 shell's inability to help me select a good mirror. .Sp \&\s-1CPAN\s0 can now help you select a \*(L"good\*(R" mirror, based on which ones have the lowest 'ping' round-trip times. From the shell, use the command 'o conf init urllist' and allow \s-1CPAN\s0 to automatically select mirrors for you. .Sp Beyond that help, the urllist config parameter is yours. You can add and remove sites at will. You should find out which sites have the best up-to-dateness, bandwidth, reliability, etc. and are topologically close to you. Some people prefer fast downloads, others up-to-dateness, others reliability. You decide which to try in which order. .Sp Henk P. Penning maintains a site that collects data about \s-1CPAN\s0 sites: .Sp .Vb 1 \& http://mirrors.cpan.org/ .Ve .Sp Also, feel free to play with experimental features. Run .Sp .Vb 1 \& o conf init randomize_urllist ftpstats_period ftpstats_size .Ve .Sp and choose your favorite parameters. After a few downloads running the \&\f(CW\*(C`hosts\*(C'\fR command will probably assist you in choosing the best mirror sites. .IP "16)" 4 .IX Item "16)" Why do I get asked the same questions every time I start the shell? .Sp You can make your configuration changes permanent by calling the command \f(CW\*(C`o conf commit\*(C'\fR. Alternatively set the \f(CW\*(C`auto_commit\*(C'\fR variable to true by running \f(CW\*(C`o conf init auto_commit\*(C'\fR and answering the following question with yes. .IP "17)" 4 .IX Item "17)" Older versions of \s-1CPAN\s0.pm had the original root directory of all tarballs in the build directory. Now there are always random characters appended to these directory names. Why was this done? .Sp The random characters are provided by File::Temp and ensure that each module's individual build directory is unique. This makes running \&\s-1CPAN\s0.pm in concurrent processes simultaneously safe. .IP "18)" 4 .IX Item "18)" Speaking of the build directory. Do I have to clean it up myself? .Sp You have the choice to set the config variable \f(CW\*(C`scan_cache\*(C'\fR to \&\f(CW\*(C`never\*(C'\fR. Then you must clean it up yourself. The other possible values, \f(CW\*(C`atstart\*(C'\fR and \f(CW\*(C`atexit\*(C'\fR clean up the build directory when you start (or more precisely, after the first extraction into the build directory) or exit the \s-1CPAN\s0 shell, respectively. If you never start up the \s-1CPAN\s0 shell, you probably also have to clean up the build directory yourself. .IP "19)" 4 .IX Item "19)" How can I switch to sudo instead of local::lib? .Sp The following 5 environment veriables need to be reset to the previous values: \s-1PATH, PERL5LIB, PERL_LOCAL_LIB_ROOT, PERL_MB_OPT, PERL_MM_OPT\s0; and these two \s-1CPAN\s0.pm config variables must be reconfigured: make_install_make_command and mbuild_install_build_command. The five env variables have probably been overwritten in your \f(CW$HOME\fR/.bashrc or some equivalent. You either find them there and delete their traces and logout/login or you override them temporarily, depending on your exact desire. The two cpanpm config variables can be set with: .Sp .Vb 1 \& o conf init /install_.*_command/ .Ve .Sp probably followed by .Sp .Vb 1 \& o conf commit .Ve .SH "COMPATIBILITY" .IX Header "COMPATIBILITY" .SS "\s-1OLD PERL VERSIONS\s0" .IX Subsection "OLD PERL VERSIONS" \&\s-1CPAN\s0.pm is regularly tested to run under 5.005 and assorted newer versions. It is getting more and more difficult to get the minimal prerequisites working on older perls. It is close to impossible to get the whole Bundle::CPAN working there. If you're in the position to have only these old versions, be advised that \s-1CPAN\s0 is designed to work fine without the Bundle::CPAN installed. .PP To get things going, note that GBARR/Scalar\-List\-Utils\-1.18.tar.gz is compatible with ancient perls and that File::Temp is listed as a prerequisite but \s-1CPAN\s0 has reasonable workarounds if it is missing. .SS "\s-1CPANPLUS\s0" .IX Subsection "CPANPLUS" This module and its competitor, the \s-1CPANPLUS\s0 module, are both much cooler than the other. \s-1CPAN\s0.pm is older. \s-1CPANPLUS\s0 was designed to be more modular, but it was never intended to be compatible with \s-1CPAN\s0.pm. .SS "\s-1CPANMINUS\s0" .IX Subsection "CPANMINUS" In the year 2010 App::cpanminus was launched as a new approach to a cpan shell with a considerably smaller footprint. Very cool stuff. .SH "SECURITY ADVICE" .IX Header "SECURITY ADVICE" This software enables you to upgrade software on your computer and so is inherently dangerous because the newly installed software may contain bugs and may alter the way your computer works or even make it unusable. Please consider backing up your data before every upgrade. .SH "BUGS" .IX Header "BUGS" Please report bugs via .PP Before submitting a bug, please make sure that the traditional method of building a Perl module package from a shell by following the installation instructions of that package still works in your environment. .SH "AUTHOR" .IX Header "AUTHOR" Andreas Koenig \f(CW\*(C`\*(C'\fR .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP See .SH "TRANSLATIONS" .IX Header "TRANSLATIONS" Kawai,Takanori provides a Japanese translation of a very old version of this manpage at .SH "SEE ALSO" .IX Header "SEE ALSO" Many people enter the \s-1CPAN\s0 shell by running the cpan utility program which is installed in the same directory as perl itself. So if you have this directory in your \s-1PATH\s0 variable (or some equivalent in your operating system) then typing \f(CW\*(C`cpan\*(C'\fR in a console window will work for you as well. Above that the utility provides several commandline shortcuts. .PP melezhik (Alexey) sent me a link where he published a chef recipe to work with \s-1CPAN\s0.pm: http://community.opscode.com/cookbooks/cpan. PK!< man/man3/CPAN::API::HOWTO.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::API::HOWTO 3" .TH CPAN::API::HOWTO 3 "2012-09-08" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::API::HOWTO \- a recipe book for programming with CPAN.pm .SH "RECIPES" .IX Header "RECIPES" All of these recipes assume that you have put \*(L"use \s-1CPAN\*(R"\s0 at the top of your program. .SS "What distribution contains a particular module?" .IX Subsection "What distribution contains a particular module?" .Vb 3 \& my $distribution = CPAN::Shell\->expand( \& "Module", "Data::UUID" \& )\->distribution()\->pretty_id(); .Ve .PP This returns a string of the form \*(L"\s-1AUTHORID/TARBALL\*(R".\s0 If you want the full path and filename to this distribution on a \s-1CPAN\s0 mirror, then it is \&\f(CW\*(C`.../authors/id/A/AU/AUTHORID/TARBALL\*(C'\fR. .SS "What modules does a particular distribution contain?" .IX Subsection "What modules does a particular distribution contain?" .Vb 4 \& CPAN::Index\->reload(); \& my @modules = CPAN::Shell\->expand( \& "Distribution", "JHI/Graph\-0.83.tar.gz" \& )\->containsmods(); .Ve .PP You may also refer to a distribution in the form A/AU/AUTHORID/TARBALL. .SH "SEE ALSO" .IX Header "SEE ALSO" the main \s-1CPAN\s0.pm documentation .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP See .SH "AUTHOR" .IX Header "AUTHOR" David Cantrell PK!?&&man/man3/CPAN::Admin.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Admin 3" .TH CPAN::Admin 3 "2018-11-27" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" .Vb 1 \& CPAN::Admin \- A CPAN Shell for CPAN admins .Ve .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& perl \-MCPAN::Admin \-e shell .Ve .SH "STATUS" .IX Header "STATUS" Note: this module is currently not maintained. If you need it and fix it for your needs, please submit patches. .SH "DESCRIPTION" .IX Header "DESCRIPTION" CPAN::Admin is a subclass of \s-1CPAN\s0 that adds the commands \f(CW\*(C`register\*(C'\fR and \f(CW\*(C`modsearch\*(C'\fR to the \s-1CPAN\s0 shell. .PP \&\f(CW\*(C`register\*(C'\fR calls \f(CW\*(C`get\*(C'\fR on the named module, assembles a couple of informations (description, language), and calls Netscape with the \&\-remote argument so that a form is filled with all the assembled informations and the registration can be performed with a single click. If the command line has more than one argument, register does not run a \f(CW\*(C`get\*(C'\fR, instead it interprets the rest of the line as \s-1DSLI\s0 status, description, and userid and sends them to netscape such that the form is again mostly filled and can be edited or confirmed with a single click. CPAN::Admin never performs the submission click for you, it is only intended to fill in the form on \s-1PAUSE\s0 and leave the confirmation to you. .PP \&\f(CW\*(C`modsearch\*(C'\fR simply passes the arguments to the search engine for the modules@perl.org mailing list at where all registration requests are stored. It does so in the same way as register, namely with the \f(CW\*(C`netscape \-remote\*(C'\fR command. .PP An experimental feature has also been added, namely to color already registered modules in listings. If you have Term::ANSIColor installed, the u, r, and m commands will show already registered modules in green. .SH "PREREQUISITES" .IX Header "PREREQUISITES" URI::Escape, a browser available in the path, the browser must understand the \-remote switch (as far as I know, this is only available on \s-1UNIX\s0); coloring of registered modules is only available if Term::ANSIColor is installed. .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!stb b man/man3/CPAN::Debug.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Debug 3" .TH CPAN::Debug 3 "2016-08-17" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Debug \- internal debugging for CPAN.pm .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!a!man/man3/CPAN::Distroprefs.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Distroprefs 3" .TH CPAN::Distroprefs 3 "2020-03-01" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Distroprefs \-\- read and match distroprefs .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use CPAN::Distroprefs; \& \& my %info = (... distribution/environment info ...); \& \& my $finder = CPAN::Distroprefs\->find($prefs_dir, \e%ext_map); \& \& while (my $result = $finder\->next) { \& \& die $result\->as_string if $result\->is_fatal; \& \& warn($result\->as_string), next if $result\->is_warning; \& \& for my $pref (@{ $result\->prefs }) { \& if ($pref\->matches(\e%info)) { \& return $pref; \& } \& } \& } .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module encapsulates reading Distroprefs and matching them against \s-1CPAN\s0 distributions. .SH "INTERFACE" .IX Header "INTERFACE" .Vb 1 \& my $finder = CPAN::Distroprefs\->find($dir, \e%ext_map); \& \& while (my $result = $finder\->next) { ... } .Ve .PP Build an iterator which finds distroprefs files in the tree below the given directory. Within the tree directories matching \f(CW\*(C`m/^[._]/\*(C'\fR are pruned. .PP \&\f(CW%ext_map\fR is a hashref whose keys are file extensions and whose values are modules used to load matching files: .PP .Vb 5 \& { \& \*(Aqyml\*(Aq => \*(AqYAML::Syck\*(Aq, \& \*(Aqdd\*(Aq => \*(AqData::Dumper\*(Aq, \& ... \& } .Ve .PP Each time \f(CW\*(C`$finder\->next\*(C'\fR is called, the iterator returns one of two possible values: .IP "\(bu" 4 a CPAN::Distroprefs::Result object .IP "\(bu" 4 \&\f(CW\*(C`undef\*(C'\fR, indicating that no prefs files remain to be found .SH "RESULTS" .IX Header "RESULTS" \&\f(CW\*(C`find()\*(C'\fR returns CPAN::Distroprefs::Result objects to indicate success or failure when reading a prefs file. .SS "Common" .IX Subsection "Common" All results share some common attributes: .PP \fItype\fR .IX Subsection "type" .PP \&\f(CW\*(C`success\*(C'\fR, \f(CW\*(C`warning\*(C'\fR, or \f(CW\*(C`fatal\*(C'\fR .PP \fIfile\fR .IX Subsection "file" .PP the file from which these prefs were read, or to which this error refers (relative filename) .PP \fIext\fR .IX Subsection "ext" .PP the file's extension, which determines how to load it .PP \fIdir\fR .IX Subsection "dir" .PP the directory the file was read from .PP \fIabs\fR .IX Subsection "abs" .PP the absolute path to the file .SS "Errors" .IX Subsection "Errors" Error results (warning and fatal) contain: .PP \fImsg\fR .IX Subsection "msg" .PP the error message (usually either \f(CW$!\fR or a \s-1YAML\s0 error) .SS "Successes" .IX Subsection "Successes" Success results contain: .PP \fIprefs\fR .IX Subsection "prefs" .PP an arrayref of CPAN::Distroprefs::Pref objects .SH "PREFS" .IX Header "PREFS" CPAN::Distroprefs::Pref objects represent individual distroprefs documents. They are constructed automatically as part of \f(CW\*(C`success\*(C'\fR results from \f(CW\*(C`find()\*(C'\fR. .PP \fIdata\fR .IX Subsection "data" .PP the pref information as a hashref, suitable for e.g. passing to Kwalify .PP \fImatch_attributes\fR .IX Subsection "match_attributes" .PP returns a list of the valid match attributes (see the Distroprefs section in \s-1CPAN\s0) .PP currently: \f(CW\*(C`env perl perlconfig distribution module\*(C'\fR .PP \fIhas_any_match\fR .IX Subsection "has_any_match" .PP true if this pref has a 'match' attribute at all .PP \fIhas_valid_subkeys\fR .IX Subsection "has_valid_subkeys" .PP true if this pref has a 'match' attribute and at least one valid match attribute .PP \fImatches\fR .IX Subsection "matches" .PP .Vb 1 \& if ($pref\->matches(\e%arg)) { ... } .Ve .PP true if this pref matches the passed-in hashref, which must have a value for each of the \f(CW\*(C`match_attributes\*(C'\fR (above) .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK! m mman/man3/CPAN::FirstTime.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::FirstTime 3" .TH CPAN::FirstTime 3 "2022-04-03" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::FirstTime \- Utility for CPAN::Config file Initialization .SH "SYNOPSIS" .IX Header "SYNOPSIS" \&\fBCPAN::FirstTime::init()\fR .SH "DESCRIPTION" .IX Header "DESCRIPTION" The init routine asks a few questions and writes a CPAN/Config.pm or CPAN/MyConfig.pm file (depending on what it is currently using). .PP In the following all questions and explanations regarding config variables are collected. .IP "allow_installing_module_downgrades" 2 .IX Item "allow_installing_module_downgrades" The \s-1CPAN\s0 shell can watch the \f(CW\*(C`blib/\*(C'\fR directories that are built up before running \f(CW\*(C`make test\*(C'\fR to determine whether the current distribution will end up with modules being overwritten with decreasing module version numbers. It can then let the build of this distro fail when it discovers a downgrade. .Sp Do you want to allow installing distros with decreasing module versions compared to what you have installed (yes, no, ask/yes, ask/no)? .IP "allow_installing_outdated_dists" 2 .IX Item "allow_installing_outdated_dists" The \s-1CPAN\s0 shell can watch the \f(CW\*(C`blib/\*(C'\fR directories that are built up before running \f(CW\*(C`make test\*(C'\fR to determine whether the current distribution contains modules that are indexed with a distro with a higher distro-version number than the current one. It can then let the build of this distro fail when it would not represent the most up-to-date version of the distro. .Sp Note: choosing anything but 'yes' for this option will need CPAN::DistnameInfo being installed for taking effect. .Sp Do you want to allow installing distros that are not indexed as the highest distro-version for all contained modules (yes, no, ask/yes, ask/no)? .IP "auto_commit" 2 .IX Item "auto_commit" Normally \s-1CPAN\s0.pm keeps config variables in memory and changes need to be saved in a separate 'o conf commit' command to make them permanent between sessions. If you set the 'auto_commit' option to true, changes to a config variable are always automatically committed to disk. .Sp Always commit changes to config variables to disk? .IP "build_cache" 2 .IX Item "build_cache" \&\s-1CPAN\s0.pm can limit the size of the disk area for keeping the build directories with all the intermediate files. .Sp Cache size for build directory (in \s-1MB\s0)? .IP "build_dir" 2 .IX Item "build_dir" Directory where the build process takes place? .IP "build_dir_reuse" 2 .IX Item "build_dir_reuse" Until version 1.88 \s-1CPAN\s0.pm never trusted the contents of the build_dir directory between sessions. Since 1.88_58 \s-1CPAN\s0.pm has a YAML-based mechanism that makes it possible to share the contents of the build_dir/ directory between different sessions with the same version of perl. People who prefer to test things several days before installing will like this feature because it saves a lot of time. .Sp If you say yes to the following question, \s-1CPAN\s0 will try to store enough information about the build process so that it can pick up in future sessions at the same state of affairs as it left a previous session. .Sp Store and re-use state information about distributions between \&\s-1CPAN\s0.pm sessions? .IP "build_requires_install_policy" 2 .IX Item "build_requires_install_policy" When a module declares another one as a 'build_requires' prerequisite this means that the other module is only needed for building or testing the module but need not be installed permanently. In this case you may wish to install that other module nonetheless or just keep it in the 'build_dir' directory to have it available only temporarily. Installing saves time on future installations but makes the perl installation bigger. .Sp You can choose if you want to always install (yes), never install (no) or be always asked. In the latter case you can set the default answer for the question to yes (ask/yes) or no (ask/no). .Sp Policy on installing 'build_requires' modules (yes, no, ask/yes, ask/no)? .IP "cache_metadata" 2 .IX Item "cache_metadata" To considerably speed up the initial \s-1CPAN\s0 shell startup, it is possible to use Storable to create a cache of metadata. If Storable is not available, the normal index mechanism will be used. .Sp Note: this mechanism is not used when use_sqlite is on and SQLite is running. .Sp Cache metadata (yes/no)? .IP "check_sigs" 2 .IX Item "check_sigs" \&\s-1CPAN\s0 packages can be digitally signed by authors and thus verified with the security provided by strong cryptography. The exact mechanism is defined in the Module::Signature module. While this is generally considered a good thing, it is not always convenient to the end user to install modules that are signed incorrectly or where the key of the author is not available or where some prerequisite for Module::Signature has a bug and so on. .Sp With the check_sigs parameter you can turn signature checking on and off. The default is off for now because the whole tool chain for the functionality is not yet considered mature by some. The author of \&\s-1CPAN\s0.pm would recommend setting it to true most of the time and turning it off only if it turns out to be annoying. .Sp Note that if you do not have Module::Signature installed, no signature checks will be performed at all. .Sp Always try to check and verify signatures if a \s-1SIGNATURE\s0 file is in the package and Module::Signature is installed (yes/no)? .IP "cleanup_after_install" 2 .IX Item "cleanup_after_install" Users who install modules and do not intend to look back, can free occupied disk space quickly by letting \s-1CPAN\s0.pm cleanup each build directory immediately after a successful install. .Sp Remove build directory after a successful install? (yes/no)? .IP "colorize_output" 2 .IX Item "colorize_output" When you have Term::ANSIColor installed, you can turn on colorized output to have some visual differences between normal \s-1CPAN\s0.pm output, warnings, debugging output, and the output of the modules being installed. Set your favorite colors after some experimenting with the Term::ANSIColor module. .Sp Please note that on Windows platforms colorized output also requires the Win32::Console::ANSI module. .Sp Do you want to turn on colored output? .IP "colorize_print" 2 .IX Item "colorize_print" Color for normal output? .IP "colorize_warn" 2 .IX Item "colorize_warn" Color for warnings? .IP "colorize_debug" 2 .IX Item "colorize_debug" Color for debugging messages? .IP "commandnumber_in_prompt" 2 .IX Item "commandnumber_in_prompt" The prompt of the cpan shell can contain the current command number for easier tracking of the session or be a plain string. .Sp Do you want the command number in the prompt (yes/no)? .IP "connect_to_internet_ok" 2 .IX Item "connect_to_internet_ok" If you have never defined your own \f(CW\*(C`urllist\*(C'\fR in your configuration then \f(CW\*(C`CPAN.pm\*(C'\fR will be hesitant to use the built in default sites for downloading. It will ask you once per session if a connection to the internet is \s-1OK\s0 and only if you say yes, it will try to connect. But to avoid this question, you can choose your favorite download sites once and get away with it. Or, if you have no favorite download sites answer yes to the following question. .Sp If no urllist has been chosen yet, would you prefer \s-1CPAN\s0.pm to connect to the built-in default sites without asking? (yes/no)? .IP "ftp_passive" 2 .IX Item "ftp_passive" Shall we always set the \s-1FTP_PASSIVE\s0 environment variable when dealing with ftp download (yes/no)? .IP "ftpstats_period" 2 .IX Item "ftpstats_period" Statistics about downloads are truncated by size and period simultaneously. .Sp How many days shall we keep statistics about downloads? .IP "ftpstats_size" 2 .IX Item "ftpstats_size" Statistics about downloads are truncated by size and period simultaneously. Setting this to zero or negative disables download statistics. .Sp How many items shall we keep in the statistics about downloads? .IP "getcwd" 2 .IX Item "getcwd" \&\s-1CPAN\s0.pm changes the current working directory often and needs to determine its own current working directory. Per default it uses Cwd::cwd but if this doesn't work on your system for some reason, alternatives can be configured according to the following table: .Sp .Vb 5 \& cwd Cwd::cwd \& getcwd Cwd::getcwd \& fastcwd Cwd::fastcwd \& getdcwd Cwd::getdcwd \& backtickcwd external command cwd .Ve .Sp Preferred method for determining the current working directory? .IP "halt_on_failure" 2 .IX Item "halt_on_failure" Normally, \s-1CPAN\s0.pm continues processing the full list of targets and dependencies, even if one of them fails. However, you can specify that \s-1CPAN\s0 should halt after the first failure. (Note that optional recommended or suggested modules that fail will not cause a halt.) .Sp Do you want to halt on failure (yes/no)? .IP "histfile" 2 .IX Item "histfile" If you have one of the readline packages (Term::ReadLine::Perl, Term::ReadLine::Gnu, possibly others) installed, the interactive \s-1CPAN\s0 shell will have history support. The next two questions deal with the filename of the history file and with its size. If you do not want to set this variable, please hit \s-1SPACE ENTER\s0 to the following question. .Sp File to save your history? .IP "histsize" 2 .IX Item "histsize" Number of lines to save? .IP "inactivity_timeout" 2 .IX Item "inactivity_timeout" Sometimes you may wish to leave the processes run by \s-1CPAN\s0 alone without caring about them. Because the Makefile.PL or the Build.PL sometimes contains question you're expected to answer, you can set a timer that will kill a 'perl Makefile.PL' process after the specified time in seconds. .Sp If you set this value to 0, these processes will wait forever. This is the default and recommended setting. .Sp Timeout for inactivity during {Makefile,Build}.PL? .IP "index_expire" 2 .IX Item "index_expire" The \s-1CPAN\s0 indexes are usually rebuilt once or twice per hour, but the typical \s-1CPAN\s0 mirror mirrors only once or twice per day. Depending on the quality of your mirror and your desire to be on the bleeding edge, you may want to set the following value to more or less than one day (which is the default). It determines after how many days \s-1CPAN\s0.pm downloads new indexes. .Sp Let the index expire after how many days? .IP "inhibit_startup_message" 2 .IX Item "inhibit_startup_message" When the \s-1CPAN\s0 shell is started it normally displays a greeting message that contains the running version and the status of readline support. .Sp Do you want to turn this message off? .IP "keep_source_where" 2 .IX Item "keep_source_where" Unless you are accessing the \s-1CPAN\s0 on your filesystem via a file: \s-1URL, CPAN\s0.pm needs to keep the source files it downloads somewhere. Please supply a directory where the downloaded files are to be kept. .Sp Download target directory? .IP "load_module_verbosity" 2 .IX Item "load_module_verbosity" When \s-1CPAN\s0.pm loads a module it needs for some optional feature, it usually reports about module name and version. Choose 'v' to get this message, 'none' to suppress it. .Sp Verbosity level for loading modules (none or v)? .IP "makepl_arg" 2 .IX Item "makepl_arg" Every Makefile.PL is run by perl in a separate process. Likewise we run 'make' and 'make install' in separate processes. If you have any parameters (e.g. \s-1PREFIX, UNINST\s0 or the like) you want to pass to the calls, please specify them here. .Sp If you don't understand this question, just press \s-1ENTER.\s0 .Sp Typical frequently used settings: .Sp .Vb 1 \& PREFIX=~/perl # non\-root users (please see manual for more hints) .Ve .Sp Parameters for the 'perl Makefile.PL' command? .IP "make_arg" 2 .IX Item "make_arg" Parameters for the 'make' command? Typical frequently used setting: .Sp .Vb 1 \& \-j3 # dual processor system (on GNU make) .Ve .Sp Your choice: .IP "make_install_arg" 2 .IX Item "make_install_arg" Parameters for the 'make install' command? Typical frequently used setting: .Sp .Vb 2 \& UNINST=1 # to always uninstall potentially conflicting files \& # (but do NOT use with local::lib or INSTALL_BASE) .Ve .Sp Your choice: .IP "make_install_make_command" 2 .IX Item "make_install_make_command" Do you want to use a different make command for 'make install'? Cautious people will probably prefer: .Sp .Vb 5 \& su root \-c make \& or \& sudo make \& or \& /path1/to/sudo \-u admin_account /path2/to/make .Ve .Sp or some such. Your choice: .IP "mbuildpl_arg" 2 .IX Item "mbuildpl_arg" A Build.PL is run by perl in a separate process. Likewise we run \&'./Build' and './Build install' in separate processes. If you have any parameters you want to pass to the calls, please specify them here. .Sp Typical frequently used settings: .Sp .Vb 1 \& \-\-install_base /home/xxx # different installation directory .Ve .Sp Parameters for the 'perl Build.PL' command? .IP "mbuild_arg" 2 .IX Item "mbuild_arg" Parameters for the './Build' command? Setting might be: .Sp .Vb 1 \& \-\-extra_linker_flags \-L/usr/foo/lib # non\-standard library location .Ve .Sp Your choice: .IP "mbuild_install_arg" 2 .IX Item "mbuild_install_arg" Parameters for the './Build install' command? Typical frequently used setting: .Sp .Vb 2 \& \-\-uninst 1 # uninstall conflicting files \& # (but do NOT use with local::lib or INSTALL_BASE) .Ve .Sp Your choice: .IP "mbuild_install_build_command" 2 .IX Item "mbuild_install_build_command" Do you want to use a different command for './Build install'? Sudo users will probably prefer: .Sp .Vb 5 \& su root \-c ./Build \& or \& sudo ./Build \& or \& /path1/to/sudo \-u admin_account ./Build .Ve .Sp or some such. Your choice: .IP "pager" 2 .IX Item "pager" What is your favorite pager program? .IP "prefer_installer" 2 .IX Item "prefer_installer" When you have Module::Build installed and a module comes with both a Makefile.PL and a Build.PL, which shall have precedence? .Sp The main two standard installer modules are the old and well established ExtUtils::MakeMaker (for short: \s-1EUMM\s0) which uses the Makefile.PL. And the next generation installer Module::Build (\s-1MB\s0) which works with the Build.PL (and often comes with a Makefile.PL too). If a module comes only with one of the two we will use that one but if both are supplied then a decision must be made between \s-1EUMM\s0 and \&\s-1MB.\s0 See also http://rt.cpan.org/Ticket/Display.html?id=29235 for a discussion about the right default. .Sp Or, as a third option you can choose \s-1RAND\s0 which will make a random decision (something regular \s-1CPAN\s0 testers will enjoy). .Sp In case you can choose between running a Makefile.PL or a Build.PL, which installer would you prefer (\s-1EUMM\s0 or \s-1MB\s0 or \s-1RAND\s0)? .IP "prefs_dir" 2 .IX Item "prefs_dir" \&\s-1CPAN\s0.pm can store customized build environments based on regular expressions for distribution names. These are \s-1YAML\s0 files where the default options for \s-1CPAN\s0.pm and the environment can be overridden and dialog sequences can be stored that can later be executed by an Expect.pm object. The \s-1CPAN\s0.pm distribution comes with some prefab \s-1YAML\s0 files that cover sample distributions that can be used as blueprints to store your own prefs. Please check out the distroprefs/ directory of the \s-1CPAN\s0.pm distribution to get a quick start into the prefs system. .Sp Directory where to store default options/environment/dialogs for building modules that need some customization? .IP "prerequisites_policy" 2 .IX Item "prerequisites_policy" The \s-1CPAN\s0 module can detect when a module which you are trying to build depends on prerequisites. If this happens, it can build the prerequisites for you automatically ('follow'), ask you for confirmation ('ask'), or just ignore them ('ignore'). Choosing \&'follow' also sets \s-1PERL_AUTOINSTALL\s0 and \s-1PERL_EXTUTILS_AUTOINSTALL\s0 for \&\*(L"\-\-defaultdeps\*(R" if not already set. .Sp Please set your policy to one of the three values. .Sp Policy on building prerequisites (follow, ask or ignore)? .IP "pushy_https" 2 .IX Item "pushy_https" Boolean. Defaults to true. If this option is true, the cpan shell will use https://cpan.org/ to download stuff from the \s-1CPAN.\s0 It will fall back to http://cpan.org/ if it can't handle https for some reason (missing modules, missing programs). Whenever it falls back to the http protocol, it will issue a warning. .Sp If this option is true, the option \f(CW\*(C`urllist\*(C'\fR will be ignored. Consequently, if you want to work with local mirrors via your own configured list of URLs, you will have to choose no below. .Sp Do you want to turn the pushy_https behaviour on? .IP "randomize_urllist" 2 .IX Item "randomize_urllist" \&\s-1CPAN\s0.pm can introduce some randomness when using hosts for download that are configured in the urllist parameter. Enter a numeric value between 0 and 1 to indicate how often you want to let \s-1CPAN\s0.pm try a random host from the urllist. A value of one specifies to always use a random host as the first try. A value of zero means no randomness at all. Anything in between specifies how often, on average, a random host should be tried first. .Sp Randomize parameter .IP "recommends_policy" 2 .IX Item "recommends_policy" (Experimental feature!) Some \s-1CPAN\s0 modules recommend additional, optional dependencies. These should generally be installed except in resource constrained environments. When this policy is true, recommended modules will be included with required modules. .Sp Include recommended modules? .IP "scan_cache" 2 .IX Item "scan_cache" By default, each time the \s-1CPAN\s0 module is started, cache scanning is performed to keep the cache size in sync ('atstart'). Alternatively, scanning and cleanup can happen when \s-1CPAN\s0 exits ('atexit'). To prevent any cache cleanup, answer 'never'. .Sp Perform cache scanning ('atstart', 'atexit' or 'never')? .IP "shell" 2 .IX Item "shell" What is your favorite shell? .IP "show_unparsable_versions" 2 .IX Item "show_unparsable_versions" During the 'r' command \s-1CPAN\s0.pm finds modules without version number. When the command finishes, it prints a report about this. If you want this report to be very verbose, say yes to the following variable. .Sp Show all individual modules that have no \f(CW$VERSION\fR? .IP "show_upload_date" 2 .IX Item "show_upload_date" The 'd' and the 'm' command normally only show you information they have in their in-memory database and thus will never connect to the internet. If you set the 'show_upload_date' variable to true, 'm' and \&'d' will additionally show you the upload date of the module or distribution. Per default this feature is off because it may require a net connection to get at the upload date. .Sp Always try to show upload date with 'd' and 'm' command (yes/no)? .IP "show_zero_versions" 2 .IX Item "show_zero_versions" During the 'r' command \s-1CPAN\s0.pm finds modules with a version number of zero. When the command finishes, it prints a report about this. If you want this report to be very verbose, say yes to the following variable. .Sp Show all individual modules that have a \f(CW$VERSION\fR of zero? .IP "suggests_policy" 2 .IX Item "suggests_policy" (Experimental feature!) Some \s-1CPAN\s0 modules suggest additional, optional dependencies. These 'suggest' dependencies provide enhanced operation. When this policy is true, suggested modules will be included with required modules. .Sp Include suggested modules? .IP "tar_verbosity" 2 .IX Item "tar_verbosity" When \s-1CPAN\s0.pm uses the tar command, which switch for the verbosity shall be used? Choose 'none' for quiet operation, 'v' for file name listing, 'vv' for full listing. .Sp Tar command verbosity level (none or v or vv)? .IP "term_is_latin" 2 .IX Item "term_is_latin" The next option deals with the charset (a.k.a. character set) your terminal supports. In general, \s-1CPAN\s0 is English speaking territory, so the charset does not matter much but some \s-1CPAN\s0 have names that are outside the \s-1ASCII\s0 range. If your terminal supports \s-1UTF\-8,\s0 you should say no to the next question. If it expects \s-1ISO\-8859\-1\s0 (also known as \&\s-1LATIN1\s0) then you should say yes. If it supports neither, your answer does not matter because you will not be able to read the names of some authors anyway. If you answer no, names will be output in \s-1UTF\-8.\s0 .Sp Your terminal expects \s-1ISO\-8859\-1\s0 (yes/no)? .IP "term_ornaments" 2 .IX Item "term_ornaments" When using Term::ReadLine, you can turn ornaments on so that your input stands out against the output from \s-1CPAN\s0.pm. .Sp Do you want to turn ornaments on? .IP "test_report" 2 .IX Item "test_report" The goal of the \s-1CPAN\s0 Testers project (http://testers.cpan.org/) is to test as many \s-1CPAN\s0 packages as possible on as many platforms as possible. This provides valuable feedback to module authors and potential users to identify bugs or platform compatibility issues and improves the overall quality and value of \s-1CPAN.\s0 .Sp One way you can contribute is to send test results for each module that you install. If you install the CPAN::Reporter module, you have the option to automatically generate and deliver test reports to \s-1CPAN\s0 Testers whenever you run tests on a \s-1CPAN\s0 package. .Sp See the CPAN::Reporter documentation for additional details and configuration settings. If your firewall blocks outgoing traffic, you may need to configure CPAN::Reporter before sending reports. .Sp Generate test reports if CPAN::Reporter is installed (yes/no)? .IP "perl5lib_verbosity" 2 .IX Item "perl5lib_verbosity" When \s-1CPAN\s0.pm extends \f(CW@INC\fR via \s-1PERL5LIB,\s0 it prints a list of directories added (or a summary of how many directories are added). Choose 'v' to get this message, 'none' to suppress it. .Sp Verbosity level for \s-1PERL5LIB\s0 changes (none or v)? .IP "prefer_external_tar" 2 .IX Item "prefer_external_tar" Per default all untar operations are done with the perl module Archive::Tar; by setting this variable to true the external tar command is used if available; on Unix this is usually preferred because they have a reliable and fast gnutar implementation. .Sp Use the external tar program instead of Archive::Tar? .IP "trust_test_report_history" 2 .IX Item "trust_test_report_history" When a distribution has already been tested by CPAN::Reporter on this machine, \s-1CPAN\s0 can skip the test phase and just rely on the test report history instead. .Sp Note that this will not apply to distributions that failed tests because of missing dependencies. Also, tests can be run regardless of the history using \*(L"force\*(R". .Sp Do you want to rely on the test report history (yes/no)? .IP "urllist_ping_external" 2 .IX Item "urllist_ping_external" When automatic selection of the nearest cpan mirrors is performed, turn on the use of the external ping via Net::Ping::External. This is recommended in the case the local network has a transparent proxy. .Sp Do you want to use the external ping command when autoselecting mirrors? .IP "urllist_ping_verbose" 2 .IX Item "urllist_ping_verbose" When automatic selection of the nearest cpan mirrors is performed, this option can be used to turn on verbosity during the selection process. .Sp Do you want to see verbosity turned on when autoselecting mirrors? .IP "use_prompt_default" 2 .IX Item "use_prompt_default" When this is true, \s-1CPAN\s0 will set \s-1PERL_MM_USE_DEFAULT\s0 to a true value. This causes ExtUtils::MakeMaker (and compatible) prompts to use default values instead of stopping to prompt you to answer questions. It also sets \s-1NONINTERACTIVE_TESTING\s0 to a true value to signal more generally that distributions should not try to interact with you. .Sp Do you want to use prompt defaults (yes/no)? .IP "use_sqlite" 2 .IX Item "use_sqlite" CPAN::SQLite is a layer between the index files that are downloaded from the \s-1CPAN\s0 and \s-1CPAN\s0.pm that speeds up metadata queries and reduces memory consumption of \s-1CPAN\s0.pm considerably. .Sp Use CPAN::SQLite if available? (yes/no)? .IP "version_timeout" 2 .IX Item "version_timeout" This timeout prevents \s-1CPAN\s0 from hanging when trying to parse a pathologically coded \f(CW$VERSION\fR from a module. .Sp The default is 15 seconds. If you set this value to 0, no timeout will occur, but this is not recommended. .Sp Timeout for parsing module versions? .IP "yaml_load_code" 2 .IX Item "yaml_load_code" Both \s-1YAML\s0.pm and YAML::Syck are capable of deserialising code. As this requires a string eval, which might be a security risk, you can use this option to enable or disable the deserialisation of code via CPAN::DeferredCode. (Note: This does not work under perl 5.6) .Sp Do you want to enable code deserialisation (yes/no)? .IP "yaml_module" 2 .IX Item "yaml_module" At the time of this writing (2009\-03) there are three \s-1YAML\s0 implementations working: \s-1YAML,\s0 YAML::Syck, and \s-1YAML::XS.\s0 The latter two are faster but need a C compiler installed on your system. There may be more alternative \s-1YAML\s0 conforming modules. When I tried two other players, YAML::Tiny and YAML::Perl, they seemed not powerful enough to work with \s-1CPAN\s0.pm. This may have changed in the meantime. .Sp Which \s-1YAML\s0 implementation would you prefer? .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!j, man/man3/CPAN::HandleConfig.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::HandleConfig 3" .TH CPAN::HandleConfig 3 "2022-04-03" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::HandleConfig \- internal configuration handling for CPAN.pm .ie n .SS """CLASS\->safe_quote ITEM""" .el .SS "\f(CWCLASS\->safe_quote ITEM\fP" .IX Subsection "CLASS->safe_quote ITEM" Quotes an item to become safe against spaces in shell interpolation. An item is enclosed in double quotes if: .PP .Vb 2 \& \- the item contains spaces in the middle \& \- the item does not start with a quote .Ve .PP This happens to avoid shell interpolation problems when whitespace is present in directory names. .PP This method uses \f(CW\*(C`commands_quote\*(C'\fR to determine the correct quote. If \f(CW\*(C`commands_quote\*(C'\fR is a space, no quoting will take place. .PP if it starts and ends with the same quote character: leave it as it is .PP if it contains no whitespace: leave it as it is .PP if it contains whitespace, then .PP if it contains quotes: better leave it as it is .PP else: quote it with the correct quote type for the box we're on .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!lg man/man3/CPAN::Kwalify.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Kwalify 3" .TH CPAN::Kwalify 3 "2012-09-08" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Kwalify \- Interface between CPAN.pm and Kwalify.pm .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& use CPAN::Kwalify; \& validate($schema_name, $data, $file, $doc); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" .ie n .IP "_validate($schema_name, $data, $file, $doc)" 4 .el .IP "_validate($schema_name, \f(CW$data\fR, \f(CW$file\fR, \f(CW$doc\fR)" 4 .IX Item "_validate($schema_name, $data, $file, $doc)" \&\f(CW$schema_name\fR is the name of a supported schema. Currently only \&\f(CW\*(C`distroprefs\*(C'\fR is supported. \f(CW$data\fR is the data to be validated. \f(CW$file\fR is the absolute path to the file the data are coming from. \f(CW$doc\fR is the index of the document within \f(CW$doc\fR that is to be validated. The last two arguments are only there for better error reporting. .Sp Relies on being called from within \s-1CPAN\s0.pm. .Sp Dies if something fails. Does not return anything useful. .IP "yaml($schema_name)" 4 .IX Item "yaml($schema_name)" Returns the \s-1YAML\s0 text of that schema. Dies if something fails. .SH "AUTHOR" .IX Header "AUTHOR" Andreas Koenig \f(CW\*(C`\*(C'\fR .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP See PK!*'E""man/man3/CPAN::Mirrors.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Mirrors 3" .TH CPAN::Mirrors 3 "2020-05-23" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Mirrors \- Get CPAN mirror information and select a fast one .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use CPAN::Mirrors; \& \& my $mirrors = CPAN::Mirrors\->new( $mirrored_by_file ); \& \& my $seen = {}; \& \& my $best_continent = $mirrors\->find_best_continents( { seen => $seen } ); \& my @mirrors = $mirrors\->get_mirrors_by_continents( $best_continent ); \& \& my $callback = sub { \& my( $m ) = @_; \& printf "%s = %s\en", $m\->hostname, $m\->rtt \& }; \& $mirrors\->get_mirrors_timings( \e@mirrors, $seen, $callback, %args ); \& \& @mirrors = sort { $a\->rtt <=> $b\->rtt } @mirrors; \& \& print "Best mirrors are ", map( { $_\->rtt } @mirrors[0..3] ), "\en"; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" .IP "new( \s-1LOCAL_FILE_NAME\s0 )" 4 .IX Item "new( LOCAL_FILE_NAME )" Create a new CPAN::Mirrors object from \s-1LOCAL_FILE_NAME.\s0 This file should look like that in http://www.cpan.org/MIRRORED.BY . .IP "\fBcontinents()\fR" 4 .IX Item "continents()" Return a list of continents based on those defined in \fI\s-1MIRRORED.BY\s0\fR. .IP "countries( [\s-1CONTINENTS\s0] )" 4 .IX Item "countries( [CONTINENTS] )" Return a list of countries based on those defined in \fI\s-1MIRRORED.BY\s0\fR. It only returns countries for the continents you specify (as defined in \f(CW\*(C`continents\*(C'\fR). If you don't specify any continents, it returns all of the countries listed in \fI\s-1MIRRORED.BY\s0\fR. .IP "mirrors( [\s-1COUNTRIES\s0] )" 4 .IX Item "mirrors( [COUNTRIES] )" Return a list of mirrors based on those defined in \fI\s-1MIRRORED.BY\s0\fR. It only returns mirrors for the countries you specify (as defined in \f(CW\*(C`countries\*(C'\fR). If you don't specify any countries, it returns all of the mirrors listed in \fI\s-1MIRRORED.BY\s0\fR. .IP "get_mirrors_by_countries( [\s-1COUNTRIES\s0] )" 4 .IX Item "get_mirrors_by_countries( [COUNTRIES] )" A more sensible synonym for mirrors. .IP "get_mirrors_by_continents( [\s-1CONTINENTS\s0] )" 4 .IX Item "get_mirrors_by_continents( [CONTINENTS] )" Return a list of mirrors for all of continents you specify. If you don't specify any continents, it returns all of the mirrors. .Sp You can specify a single continent or an array reference of continents. .IP "get_countries_by_continents( [\s-1CONTINENTS\s0] )" 4 .IX Item "get_countries_by_continents( [CONTINENTS] )" A more sensible synonym for countries. .IP "default_mirror" 4 .IX Item "default_mirror" Returns the default mirror, http://www.cpan.org/ . This mirror uses dynamic \s-1DNS\s0 to give a close mirror. .IP "best_mirrors" 4 .IX Item "best_mirrors" \&\f(CW\*(C`best_mirrors\*(C'\fR checks for the best mirrors based on the list of continents you pass, or, without that, all continents, as defined by \f(CW\*(C`CPAN::Mirrored::By\*(C'\fR. It pings each mirror, up to the value of \&\f(CW\*(C`how_many\*(C'\fR. In list context, it returns up to \f(CW\*(C`how_many\*(C'\fR mirrors. In scalar context, it returns the single best mirror. .Sp Arguments .Sp .Vb 5 \& how_many \- the number of mirrors to return. Default: 1 \& callback \- a callback for find_best_continents \& verbose \- true or false on all the whining and moaning. Default: false \& continents \- an array ref of the continents to check \& external_ping \- if true, use external ping via Net::Ping::External. Default: false .Ve .Sp If you don't specify the continents, \f(CW\*(C`best_mirrors\*(C'\fR calls \&\f(CW\*(C`find_best_continents\*(C'\fR to get the list of continents to check. .Sp If you don't have Net::Ping v2.13 or later, needed for timings, this returns the default mirror. .Sp \&\f(CW\*(C`external_ping\*(C'\fR should be set and then \f(CW\*(C`Net::Ping::External\*(C'\fR needs to be installed, if the local network has a transparent proxy. .IP "get_n_random_mirrors_by_continents( N, [\s-1CONTINENTS\s0] )" 4 .IX Item "get_n_random_mirrors_by_continents( N, [CONTINENTS] )" Returns up to N random mirrors for the specified continents. Specify the continents as an array reference. .ie n .IP "get_mirrors_timings( \s-1MIRROR_LIST, SEEN, CALLBACK,\s0 %ARGS );" 4 .el .IP "get_mirrors_timings( \s-1MIRROR_LIST, SEEN, CALLBACK,\s0 \f(CW%ARGS\fR );" 4 .IX Item "get_mirrors_timings( MIRROR_LIST, SEEN, CALLBACK, %ARGS );" Pings the listed mirrors and returns a list of mirrors sorted in ascending ping times. .Sp \&\f(CW\*(C`MIRROR_LIST\*(C'\fR is an anonymous array of \f(CW\*(C`CPAN::Mirrored::By\*(C'\fR objects to ping. .Sp The optional argument \f(CW\*(C`SEEN\*(C'\fR is a hash reference used to track the mirrors you've already pinged. .Sp The optional argument \f(CW\*(C`CALLBACK\*(C'\fR is a subroutine reference to call after each ping. It gets the \f(CW\*(C`CPAN::Mirrored::By\*(C'\fR object after each ping. .IP "find_best_continents( \s-1HASH_REF\s0 );" 4 .IX Item "find_best_continents( HASH_REF );" \&\f(CW\*(C`find_best_continents\*(C'\fR goes through each continent and pings \f(CW\*(C`N\*(C'\fR random mirrors on that continent. It then orders the continents by ascending median ping time. In list context, it returns the ordered list of continent. In scalar context, it returns the same list as an anonymous array. .Sp Arguments: .Sp .Vb 6 \& n \- the number of hosts to ping for each continent. Default: 3 \& seen \- a hashref of cached hostname ping times \& verbose \- true or false for noisy or quiet. Default: false \& callback \- a subroutine to run after each ping. \& ping_cache_limit \- how long, in seconds, to reuse previous ping times. \& Default: 1 day .Ve .Sp The \f(CW\*(C`seen\*(C'\fR hash has hostnames as keys and anonymous arrays as values. The anonymous array is a triplet of a \f(CW\*(C`CPAN::Mirrored::By\*(C'\fR object, a ping time, and the epoch time for the measurement. .Sp The callback subroutine gets the \f(CW\*(C`CPAN::Mirrored::By\*(C'\fR object, the ping time, and measurement time (the same things in the \f(CW\*(C`seen\*(C'\fR hashref) as arguments. \f(CW\*(C`find_best_continents\*(C'\fR doesn't care what the callback does and ignores the return value. .Sp With a low value for \f(CW\*(C`N\*(C'\fR, a single mirror might skew the results enough to choose a worse continent. If you have that problem, try a larger value. .SH "AUTHOR" .IX Header "AUTHOR" Andreas Koenig \f(CW\*(C`\*(C'\fR, David Golden \f(CW\*(C`\*(C'\fR, brian d foy \f(CW\*(C`\*(C'\fR .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP See PK!އg! ! man/man3/CPAN::Nox.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Nox 3" .TH CPAN::Nox 3 "2016-08-17" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Nox \- Wrapper around CPAN.pm without using any XS module .SH "SYNOPSIS" .IX Header "SYNOPSIS" Interactive mode: .PP .Vb 1 \& perl \-MCPAN::Nox \-e shell; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This package has the same functionality as \s-1CPAN\s0.pm, but tries to prevent the usage of compiled extensions during its own execution. Its primary purpose is a rescue in case you upgraded perl and broke binary compatibility somehow. .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .SH "SEE ALSO" .IX Header "SEE ALSO" \&\s-1CPAN\s0 PK! man/man3/CPAN::Plugin.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Plugin 3" .TH CPAN::Plugin 3 "2020-05-19" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Plugin \- Base class for CPAN shell extensions .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& package CPAN::Plugin::Flurb; \& use parent \*(AqCPAN::Plugin\*(Aq; \& \& sub post_test { \& my ($self, $distribution_object) = @_; \& $self = $self\->new (distribution_object => $distribution_object); \& ...; \& } .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" .SS "Alpha Status" .IX Subsection "Alpha Status" The plugin system in the \s-1CPAN\s0 shell was introduced in version 2.07 and is still considered experimental. .SS "How Plugins work?" .IX Subsection "How Plugins work?" See \*(L"Plugin support\*(R" in \s-1CPAN\s0. .SH "METHODS" .IX Header "METHODS" .SS "plugin_requires" .IX Subsection "plugin_requires" returns list of packages given plugin requires for functionality. This list is evaluated using \f(CW\*(C`CPAN\->use_inst\*(C'\fR method. .SS "distribution_object" .IX Subsection "distribution_object" Get current distribution object. .SS "distribution" .IX Subsection "distribution" .SS "distribution_info" .IX Subsection "distribution_info" .SS "build_dir" .IX Subsection "build_dir" Simple delegatees for misc parameters derived from distribution .SS "is_xs" .IX Subsection "is_xs" Predicate to detect whether package contains \s-1XS.\s0 .SH "AUTHOR" .IX Header "AUTHOR" Branislav Zahradnik PK!&D#man/man3/CPAN::Plugin::Specfile.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Plugin::Specfile 3" .TH CPAN::Plugin::Specfile 3 "2020-05-19" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Plugin::Specfile \- Proof of concept implementation of a trivial CPAN::Plugin .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& # once in the cpan shell \& o conf plugin_list push CPAN::Plugin::Specfile \& \& # make permanent \& o conf commit \& \& # any time in the cpan shell to write a spec file \& test Acme::Meta \& \& # disable \& # if it is the last in plugin_list: \& o conf plugin_list pop \& # otherwise, determine the index to splice: \& o conf plugin_list \& # and then use splice, e.g. to splice position 3: \& o conf plugin_list splice 3 1 .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" Implemented as a post-test hook, this plugin writes a specfile after every successful test run. The content is also written to the terminal. .PP As a side effect, the timestamps of the written specfiles reflect the linear order of all dependencies. .PP \&\fB\s-1WARNING:\s0\fR This code is just a small demo how to use the plugin system of the \s-1CPAN\s0 shell, not a full fledged spec file writer. Do not expect new features in this plugin. .SS "\s-1OPTIONS\s0" .IX Subsection "OPTIONS" The target directory to store the spec files in can be set using \f(CW\*(C`dir\*(C'\fR as in .PP .Vb 1 \& o conf plugin_list push CPAN::Plugin::Specfile=dir,/tmp/specfiles\-000042 .Ve .PP The default directory for this is the \&\f(CW\*(C`plugins/CPAN::Plugin::Specfile\*(C'\fR directory in the \fIcpan_home\fR directory. .SH "AUTHOR" .IX Header "AUTHOR" Andreas Koenig , Branislav Zahradnik PK!uTf f man/man3/CPAN::Queue.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Queue 3" .TH CPAN::Queue 3 "2020-05-19" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Queue \- internal queue support for CPAN.pm .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!Jt t man/man3/CPAN::Tarzip.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Tarzip 3" .TH CPAN::Tarzip 3 "2020-05-19" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Tarzip \- internal handling of tar archives for CPAN.pm .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!Hy man/man3/CPAN::Version.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Version 3" .TH CPAN::Version 3 "2018-09-22" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Version \- utility functions to compare CPAN versions .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use CPAN::Version; \& \& CPAN::Version\->vgt("1.1","1.1.1"); # 1 bc. 1.1 > 1.001001 \& \& CPAN::Version\->vlt("1.1","1.1"); # 0 bc. 1.1 not < 1.1 \& \& CPAN::Version\->vcmp("1.1","1.1.1"); # 1 bc. first is larger \& \& CPAN::Version\->vcmp("1.1.1","1.1"); # \-1 bc. first is smaller \& \& CPAN::Version\->readable(v1.2.3); # "v1.2.3" \& \& CPAN::Version\->vstring("v1.2.3"); # v1.2.3 \& \& CPAN::Version\->float2vv(1.002003); # "v1.2.3" .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module mediates between some version that perl sees in a package and the version that is published by the \s-1CPAN\s0 indexer. .PP It's only written as a helper module for both \s-1CPAN\s0.pm and \s-1CPANPLUS\s0.pm. .PP As it stands it predates version.pm but has the same goal: make version strings visible and comparable. .SH "LICENSE" .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PK!5ܚ11%man/man3/CPAN::Meta::Requirements.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Meta::Requirements 3" .TH CPAN::Meta::Requirements 3 "2023-06-19" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Meta::Requirements \- a set of version requirements for a CPAN dist .SH "VERSION" .IX Header "VERSION" version 2.143 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use CPAN::Meta::Requirements; \& \& my $build_requires = CPAN::Meta::Requirements\->new; \& \& $build_requires\->add_minimum(\*(AqLibrary::Foo\*(Aq => 1.208); \& \& $build_requires\->add_minimum(\*(AqLibrary::Foo\*(Aq => 2.602); \& \& $build_requires\->add_minimum(\*(AqModule::Bar\*(Aq => \*(Aqv1.2.3\*(Aq); \& \& $METAyml\->{build_requires} = $build_requires\->as_string_hash; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" A CPAN::Meta::Requirements object models a set of version constraints like those specified in the \fI\s-1META\s0.yml\fR or \fI\s-1META\s0.json\fR files in \s-1CPAN\s0 distributions, and as defined by CPAN::Meta::Spec. It can be built up by adding more and more constraints, and it will reduce them to the simplest representation. .PP Logically impossible constraints will be identified immediately by thrown exceptions. .SH "METHODS" .IX Header "METHODS" .SS "new" .IX Subsection "new" .Vb 1 \& my $req = CPAN::Meta::Requirements\->new; .Ve .PP This returns a new CPAN::Meta::Requirements object. It takes an optional hash reference argument. Currently, only one key is supported: .IP "\(bu" 4 \&\f(CW\*(C`bad_version_hook\*(C'\fR \*(-- 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. .PP All other keys are ignored. .SS "add_minimum" .IX Subsection "add_minimum" .Vb 1 \& $req\->add_minimum( $module => $version ); .Ve .PP This adds a new minimum version requirement. If the new requirement is redundant to the existing specification, this has no effect. .PP Minimum requirements are inclusive. \f(CW$version\fR is required, along with any greater version number. .PP This method returns the requirements object. .SS "add_maximum" .IX Subsection "add_maximum" .Vb 1 \& $req\->add_maximum( $module => $version ); .Ve .PP This adds a new maximum version requirement. If the new requirement is redundant to the existing specification, this has no effect. .PP Maximum requirements are inclusive. No version strictly greater than the given version is allowed. .PP This method returns the requirements object. .SS "add_exclusion" .IX Subsection "add_exclusion" .Vb 1 \& $req\->add_exclusion( $module => $version ); .Ve .PP This adds a new excluded version. For example, you might use these three method calls: .PP .Vb 2 \& $req\->add_minimum( $module => \*(Aq1.00\*(Aq ); \& $req\->add_maximum( $module => \*(Aq1.82\*(Aq ); \& \& $req\->add_exclusion( $module => \*(Aq1.75\*(Aq ); .Ve .PP Any version between 1.00 and 1.82 inclusive would be acceptable, except for 1.75. .PP This method returns the requirements object. .SS "exact_version" .IX Subsection "exact_version" .Vb 1 \& $req\->exact_version( $module => $version ); .Ve .PP This sets the version required for the given module to \fIexactly\fR the given version. No other version would be considered acceptable. .PP This method returns the requirements object. .SS "version_range_for_module" .IX Subsection "version_range_for_module" .Vb 1 \& $req\->version_range_for_module( $another_req_object ); .Ve .SS "add_requirements" .IX Subsection "add_requirements" .Vb 1 \& $req\->add_requirements( $another_req_object ); .Ve .PP 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. .PP This method returns the requirements object. .SS "accepts_module" .IX Subsection "accepts_module" .Vb 1 \& my $bool = $req\->accepts_module($module => $version); .Ve .PP Given an module and version, this method returns true if the version specification for the module accepts the provided version. In other words, given: .PP .Vb 1 \& Module => \*(Aq>= 1.00, < 2.00\*(Aq .Ve .PP We will accept 1.00 and 1.75 but not 0.50 or 2.00. .PP For modules that do not appear in the requirements, this method will return true. .SS "clear_requirement" .IX Subsection "clear_requirement" .Vb 1 \& $req\->clear_requirement( $module ); .Ve .PP This removes the requirement for a given module from the object. .PP This method returns the requirements object. .SS "requirements_for_module" .IX Subsection "requirements_for_module" .Vb 1 \& $req\->requirements_for_module( $module ); .Ve .PP This returns a string containing the version requirements for a given module in the format described in CPAN::Meta::Spec 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"accepts_module\*(R" instead). .SS "structured_requirements_for_module" .IX Subsection "structured_requirements_for_module" .Vb 1 \& $req\->structured_requirements_for_module( $module ); .Ve .PP 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"accepts_module\*(R" instead). .PP Added in version 2.134. .SS "required_modules" .IX Subsection "required_modules" This method returns a list of all the modules for which requirements have been specified. .SS "clone" .IX Subsection "clone" .Vb 1 \& $req\->clone; .Ve .PP This method returns a clone of the invocant. The clone and the original object can then be changed independent of one another. .SS "is_simple" .IX Subsection "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. .SS "is_finalized" .IX Subsection "is_finalized" This method returns true if the requirements have been finalized by having the \&\f(CW\*(C`finalize\*(C'\fR method called on them. .SS "finalize" .IX Subsection "finalize" This method marks the requirements finalized. Subsequent attempts to change the requirements will be fatal, \fIif\fR they would result in a change. If they would not alter the requirements, they have no effect. .PP If a finalized set of requirements is cloned, the cloned requirements are not also finalized. .SS "as_string_hash" .IX Subsection "as_string_hash" This returns a reference to a hash describing the requirements using the strings in the CPAN::Meta::Spec specification. .PP For example after the following program: .PP .Vb 1 \& my $req = CPAN::Meta::Requirements\->new; \& \& $req\->add_minimum(\*(AqCPAN::Meta::Requirements\*(Aq => 0.102); \& \& $req\->add_minimum(\*(AqLibrary::Foo\*(Aq => 1.208); \& \& $req\->add_maximum(\*(AqLibrary::Foo\*(Aq => 2.602); \& \& $req\->add_minimum(\*(AqModule::Bar\*(Aq => \*(Aqv1.2.3\*(Aq); \& \& $req\->add_exclusion(\*(AqModule::Bar\*(Aq => \*(Aqv1.2.8\*(Aq); \& \& $req\->exact_version(\*(AqXyzzy\*(Aq => \*(Aq6.01\*(Aq); \& \& my $hashref = $req\->as_string_hash; .Ve .PP \&\f(CW$hashref\fR would contain: .PP .Vb 6 \& { \& \*(AqCPAN::Meta::Requirements\*(Aq => \*(Aq0.102\*(Aq, \& \*(AqLibrary::Foo\*(Aq => \*(Aq>= 1.208, <= 2.206\*(Aq, \& \*(AqModule::Bar\*(Aq => \*(Aq>= v1.2.3, != v1.2.8\*(Aq, \& \*(AqXyzzy\*(Aq => \*(Aq== 6.01\*(Aq, \& } .Ve .SS "add_string_requirement" .IX Subsection "add_string_requirement" .Vb 2 \& $req\->add_string_requirement(\*(AqLibrary::Foo\*(Aq => \*(Aq>= 1.208, <= 2.206\*(Aq); \& $req\->add_string_requirement(\*(AqLibrary::Foo\*(Aq => v1.208); .Ve .PP This method parses the passed in string and adds the appropriate requirement for the given module. A version can be a Perl \*(L"v\-string\*(R". It understands version ranges as described in the \*(L"Version Ranges\*(R" in CPAN::Meta::Spec. For example: .IP "1.3" 4 .IX Item "1.3" .PD 0 .IP ">= 1.3" 4 .IX Item ">= 1.3" .IP "<= 1.3" 4 .IX Item "<= 1.3" .IP "== 1.3" 4 .IX Item "== 1.3" .IP "!= 1.3" 4 .IX Item "!= 1.3" .IP "> 1.3" 4 .IX Item "> 1.3" .IP "< 1.3" 4 .IX Item "< 1.3" .IP ">= 1.3, != 1.5, <= 2.0" 4 .IX Item ">= 1.3, != 1.5, <= 2.0" .PD A version number without an operator is equivalent to specifying a minimum (\f(CW\*(C`>=\*(C'\fR). Extra whitespace is allowed. .SS "from_string_hash" .IX Subsection "from_string_hash" .Vb 2 \& my $req = CPAN::Meta::Requirements\->from_string_hash( \e%hash ); \& my $req = CPAN::Meta::Requirements\->from_string_hash( \e%hash, \e%opts ); .Ve .PP 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 \*(L"v\-string\*(R". Optionally, you can supply a hash-reference of options, exactly as with the \*(L"new\*(R" method. .SH "SUPPORT" .IX Header "SUPPORT" .SS "Bugs / Feature Requests" .IX Subsection "Bugs / Feature Requests" Please report any bugs or feature requests through the issue tracker at . You will be notified automatically of any progress on your issue. .SS "Source Code" .IX Subsection "Source Code" This is open source software. The code repository is available for public review and contribution under the terms of the license. .PP .PP .Vb 1 \& git clone https://github.com/Perl\-Toolchain\-Gang/CPAN\-Meta\-Requirements.git .Ve .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 David Golden .IP "\(bu" 4 Ricardo Signes .SH "CONTRIBUTORS" .IX Header "CONTRIBUTORS" .IP "\(bu" 4 Ed J .IP "\(bu" 4 Graham Knop .IP "\(bu" 4 Karen Etheridge .IP "\(bu" 4 Leon Timmermans .IP "\(bu" 4 Paul Howarth .IP "\(bu" 4 Ricardo Signes .IP "\(bu" 4 robario .IP "\(bu" 4 Tatsuhiko Miyagawa .IP "\(bu" 4 Tatsuhiko Miyagawa .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2010 by David Golden and Ricardo Signes. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. PK!W]# %%,man/man3/CPAN::Meta::Requirements::Range.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "CPAN::Meta::Requirements::Range 3" .TH CPAN::Meta::Requirements::Range 3 "2023-06-19" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" CPAN::Meta::Requirements::Range \- a set of version requirements for a CPAN dist .SH "VERSION" .IX Header "VERSION" version 2.143 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use CPAN::Meta::Requirements::Range; \& \& my $range = CPAN::Meta::Requirements::Range\->with_minimum(1); \& \& $range = $range\->with_maximum(\*(Aqv2.2\*(Aq); \& \& my $stringified = $range\->as_string; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" A CPAN::Meta::Requirements::Range object models a set of version constraints like those specified in the \fI\s-1META\s0.yml\fR or \fI\s-1META\s0.json\fR files in \s-1CPAN\s0 distributions, and as defined by CPAN::Meta::Spec; It can be built up by adding more and more constraints, and it will reduce them to the simplest representation. .PP Logically impossible constraints will be identified immediately by thrown exceptions. .SH "METHODS" .IX Header "METHODS" .SS "with_string_requirement" .IX Subsection "with_string_requirement" .Vb 2 \& $req\->with_string_requirement(\*(Aq>= 1.208, <= 2.206\*(Aq); \& $req\->with_string_requirement(v1.208); .Ve .PP This method parses the passed in string and adds the appropriate requirement. A version can be a Perl \*(L"v\-string\*(R". It understands version ranges as described in the \*(L"Version Ranges\*(R" in CPAN::Meta::Spec. For example: .IP "1.3" 4 .IX Item "1.3" .PD 0 .IP ">= 1.3" 4 .IX Item ">= 1.3" .IP "<= 1.3" 4 .IX Item "<= 1.3" .IP "== 1.3" 4 .IX Item "== 1.3" .IP "!= 1.3" 4 .IX Item "!= 1.3" .IP "> 1.3" 4 .IX Item "> 1.3" .IP "< 1.3" 4 .IX Item "< 1.3" .IP ">= 1.3, != 1.5, <= 2.0" 4 .IX Item ">= 1.3, != 1.5, <= 2.0" .PD A version number without an operator is equivalent to specifying a minimum (\f(CW\*(C`>=\*(C'\fR). Extra whitespace is allowed. .SS "with_range" .IX Subsection "with_range" .Vb 1 \& $range\->with_range($other_range) .Ve .PP This creates a new range object that is a merge two others. .SS "with_exact_version" .IX Subsection "with_exact_version" .Vb 1 \& $range\->with_exact_version( $version ); .Ve .PP This sets the version required to \fIexactly\fR the given version. No other version would be considered acceptable. .PP This method returns the version range object. .SS "with_minimum" .IX Subsection "with_minimum" .Vb 1 \& $range\->with_minimum( $version ); .Ve .PP This adds a new minimum version requirement. If the new requirement is redundant to the existing specification, this has no effect. .PP Minimum requirements are inclusive. \f(CW$version\fR is required, along with any greater version number. .PP This method returns the version range object. .SS "with_maximum" .IX Subsection "with_maximum" .Vb 1 \& $range\->with_maximum( $version ); .Ve .PP This adds a new maximum version requirement. If the new requirement is redundant to the existing specification, this has no effect. .PP Maximum requirements are inclusive. No version strictly greater than the given version is allowed. .PP This method returns the version range object. .SS "with_exclusion" .IX Subsection "with_exclusion" .Vb 1 \& $range\->with_exclusion( $version ); .Ve .PP This adds a new excluded version. For example, you might use these three method calls: .PP .Vb 2 \& $range\->with_minimum( \*(Aq1.00\*(Aq ); \& $range\->with_maximum( \*(Aq1.82\*(Aq ); \& \& $range\->with_exclusion( \*(Aq1.75\*(Aq ); .Ve .PP Any version between 1.00 and 1.82 inclusive would be acceptable, except for 1.75. .PP This method returns the requirements object. .SS "as_struct" .IX Subsection "as_struct" .Vb 1 \& $range\->as_struct( $module ); .Ve .PP This returns a data structure containing the version requirements. This should not be used for version checks (see \*(L"accepts_module\*(R" instead). .SS "as_string" .IX Subsection "as_string" .Vb 1 \& $range\->as_string; .Ve .PP This returns a string containing the version requirements in the format described in CPAN::Meta::Spec. This should only be used for informational purposes such as error messages and should not be interpreted or used for comparison (see \*(L"accepts\*(R" instead). .SS "accepts" .IX Subsection "accepts" .Vb 1 \& my $bool = $range\->accepts($version); .Ve .PP Given a version, this method returns true if the version specification accepts the provided version. In other words, given: .PP .Vb 1 \& \*(Aq>= 1.00, < 2.00\*(Aq .Ve .PP We will accept 1.00 and 1.75 but not 0.50 or 2.00. .SS "is_simple" .IX Subsection "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. .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 David Golden .IP "\(bu" 4 Ricardo Signes .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2010 by David Golden and Ricardo Signes. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. PK!z!!man/man3/IO::Pty.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Pty 3" .TH Pty 3 "2023-12-28" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" IO::Pty \- Pseudo TTY object class .SH "VERSION" .IX Header "VERSION" 1.20 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use IO::Pty; \& \& $pty = new IO::Pty; \& \& $slave = $pty\->slave; \& \& foreach $val (1..10) { \& print $pty "$val\en"; \& $_ = <$slave>; \& print "$_"; \& } \& \& close($slave); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" \&\f(CW\*(C`IO::Pty\*(C'\fR provides an interface to allow the creation of a pseudo tty. .PP \&\f(CW\*(C`IO::Pty\*(C'\fR inherits from \f(CW\*(C`IO::Handle\*(C'\fR and so provide all the methods defined by the \f(CW\*(C`IO::Handle\*(C'\fR package. .PP Please note that pty creation is very system-dependent. If you have problems, see IO::Tty for help. .SH "CONSTRUCTOR" .IX Header "CONSTRUCTOR" .IP "new" 3 .IX Item "new" The \f(CW\*(C`new\*(C'\fR constructor takes no arguments and returns a new file object which is the master side of the pseudo tty. .SH "METHODS" .IX Header "METHODS" .IP "\fBttyname()\fR" 4 .IX Item "ttyname()" Returns the name of the slave pseudo tty. On \s-1UNIX\s0 machines this will be the pathname of the device. Use this name for informational purpose only, to get a slave filehandle, use \fBslave()\fR. .IP "\fBslave()\fR" 4 .IX Item "slave()" The \f(CW\*(C`slave\*(C'\fR method will return the slave filehandle of the given master pty, opening it anew if necessary. If IO::Stty is installed, you can then call \f(CW\*(C`$slave\->stty()\*(C'\fR to modify the terminal settings. .IP "\fBclose_slave()\fR" 4 .IX Item "close_slave()" The slave filehandle will be closed and destroyed. This is necessary in the parent after forking to get rid of the open filehandle, otherwise the parent will not notice if the child exits. Subsequent calls of \f(CW\*(C`slave()\*(C'\fR will return a newly opened slave filehandle. .IP "\fBmake_slave_controlling_terminal()\fR" 4 .IX Item "make_slave_controlling_terminal()" This will set the slave filehandle as the controlling terminal of the current process, which will become a session leader, so this should only be called by a child process after a \fBfork()\fR, e.g. in the callback to \f(CW\*(C`sync_exec()\*(C'\fR (see Proc::SyncExec). See the \f(CW\*(C`try\*(C'\fR script (also \f(CW\*(C`test.pl\*(C'\fR) for an example how to correctly spawn a subprocess. .IP "\fBset_raw()\fR" 4 .IX Item "set_raw()" Will set the pty to raw. Note that this is a one-way operation, you need IO::Stty to set the terminal settings to anything else. .Sp On some systems, the master pty is not a tty. This method checks for that and returns success anyway on such systems. Note that this method must be called on the slave, and probably should be called on the master, just to be sure, i.e. .Sp .Vb 2 \& $pty\->slave\->set_raw(); \& $pty\->set_raw(); .Ve .IP "clone_winsize_from(\e*FH)" 4 .IX Item "clone_winsize_from(*FH)" Gets the terminal size from filehandle \s-1FH\s0 (which must be a terminal) and transfers it to the pty. Returns true on success and undef on failure. Note that this must be called upon the \fIslave\fR, i.e. .Sp .Vb 1 \& $pty\->slave\->clone_winsize_from(\e*STDIN); .Ve .Sp On some systems, the master pty also isatty. I actually have no idea if setting terminal sizes there is passed through to the slave, so if this method is called for a master that is not a tty, it silently returns \s-1OK.\s0 .Sp See the \f(CW\*(C`try\*(C'\fR script for example code how to propagate \s-1SIGWINCH.\s0 .IP "\fBget_winsize()\fR" 4 .IX Item "get_winsize()" Returns the terminal size, in a 4\-element list. .Sp .Vb 1 \& ($row, $col, $xpixel, $ypixel) = $tty\->get_winsize() .Ve .ie n .IP "set_winsize($row, $col, $xpixel, $ypixel)" 4 .el .IP "set_winsize($row, \f(CW$col\fR, \f(CW$xpixel\fR, \f(CW$ypixel\fR)" 4 .IX Item "set_winsize($row, $col, $xpixel, $ypixel)" Sets the terminal size. If not specified, \f(CW$xpixel\fR and \f(CW$ypixel\fR are set to 0. As with \f(CW\*(C`clone_winsize_from\*(C'\fR, this must be called upon the \fIslave\fR. .SH "SEE ALSO" .IX Header "SEE ALSO" IO::Tty, IO::Tty::Constant, IO::Handle, Expect, Proc::SyncExec .SH "MAILING LISTS" .IX Header "MAILING LISTS" As this module is mainly used by Expect, support for it is available via the two Expect mailing lists, expectperl-announce and expectperl-discuss, at .PP .Vb 1 \& http://lists.sourceforge.net/lists/listinfo/expectperl\-announce .Ve .PP and .PP .Vb 1 \& http://lists.sourceforge.net/lists/listinfo/expectperl\-discuss .Ve .SH "AUTHORS" .IX Header "AUTHORS" Originally by Graham Barr <\fIgbarr@pobox.com\fR>, based on the Ptty module by Nick Ing-Simmons <\fInik@tiuk.ti.com\fR>. .PP Now maintained and heavily rewritten by Roland Giersig <\fIRGiersig@cpan.org\fR>. .PP Contains copyrighted stuff from openssh v3.0p1, authored by Tatu Ylonen , Markus Friedl and Todd C. Miller . .SH "COPYRIGHT" .IX Header "COPYRIGHT" Now all code is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP Nevertheless the above \s-1AUTHORS\s0 retain their copyrights to the various parts and want to receive credit if their source code is used. See the source for details. .SH "DISCLAIMER" .IX Header "DISCLAIMER" \&\s-1THIS SOFTWARE IS PROVIDED\s0 ``\s-1AS IS\s0'' \s-1AND 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\s0 (\s-1INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES\s0; \s-1LOSS OF USE, DATA, OR PROFITS\s0; \s-1OR BUSINESS INTERRUPTION\s0) \s-1HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\s0 (\s-1INCLUDING NEGLIGENCE OR OTHERWISE\s0) \s-1ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\s0 .PP In other words: Use at your own risk. Provided as is. Your mileage may vary. Read the source, Luke! .PP And finally, just to be sure: .PP 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. PK! man/man3/IO::Tty.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Tty 3" .TH Tty 3 "2023-12-28" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" IO::Tty \- Low\-level allocate a pseudo\-Tty, import constants. .SH "VERSION" .IX Header "VERSION" 1.20 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 3 \& use IO::Tty qw(TIOCNOTTY); \& ... \& # use only to import constants, see IO::Pty to create ptys. .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" \&\f(CW\*(C`IO::Tty\*(C'\fR is used internally by \f(CW\*(C`IO::Pty\*(C'\fR to create a pseudo-tty. You wouldn't want to use it directly except to import constants, use \&\f(CW\*(C`IO::Pty\*(C'\fR. For a list of importable constants, see IO::Tty::Constant. .PP Windows is now supported, but \s-1ONLY\s0 under the Cygwin environment, see . .PP Please note that pty creation is very system-dependend. From my experience, any modern \s-1POSIX\s0 system should be fine. Find below a list of systems that \f(CW\*(C`IO::Tty\*(C'\fR should work on. A more detailed table (which is slowly getting out-of-date) is available from the project pages document manager at SourceForge . .PP If you have problems on your system and your system is listed in the \&\*(L"verified\*(R" list, you probably have some non-standard setup, e.g. you compiled your Linux-kernel yourself and disabled ptys (bummer!). Please ask your friendly sysadmin for help. .PP If your system is not listed, unpack the latest version of \f(CW\*(C`IO::Tty\*(C'\fR, do a \f(CW\*(Aqperl Makefile.PL; make; make test; uname \-a\*(Aq\fR and send me (\fIRGiersig@cpan.org\fR) the results and I'll see what I can deduce from that. There are chances that it will work right out-of-the-box... .PP If it's working on your system, please send me a short note with details (version number, distribution, etc. 'uname \-a' and 'perl \-V' is a good start; also, the output from \*(L"perl Makefile.PL\*(R" contains a lot of interesting info, so please include that as well) so I can get an overview. Thanks! .SH "VERIFIED SYSTEMS, KNOWN ISSUES" .IX Header "VERIFIED SYSTEMS, KNOWN ISSUES" This is a list of systems that \f(CW\*(C`IO::Tty\*(C'\fR seems to work on ('make test' passes) with comments about \*(L"features\*(R": .IP "\(bu" 4 \&\s-1AIX 4.3\s0 .Sp Returns \s-1EIO\s0 instead of \s-1EOF\s0 when the slave is closed. Benign. .IP "\(bu" 4 \&\s-1AIX 5\s0.x .IP "\(bu" 4 FreeBSD 4.4 .Sp \&\s-1EOF\s0 on the slave tty is not reported back to the master. .IP "\(bu" 4 OpenBSD 2.8 .Sp The ioctl \s-1TIOCSCTTY\s0 sometimes fails. This is also known in Tcl/Expect, see http://expect.nist.gov/FAQ.html .Sp \&\s-1EOF\s0 on the slave tty is not reported back to the master. .IP "\(bu" 4 Darwin 7.9.0 .IP "\(bu" 4 \&\s-1HPUX 10.20 & 11.00\s0 .Sp \&\s-1EOF\s0 on the slave tty is not reported back to the master. .IP "\(bu" 4 \&\s-1IRIX 6.5\s0 .IP "\(bu" 4 Linux 2.2.x & 2.4.x .Sp Returns \s-1EIO\s0 instead of \s-1EOF\s0 when the slave is closed. Benign. .IP "\(bu" 4 \&\s-1OSF 4.0\s0 .Sp \&\s-1EOF\s0 on the slave tty is not reported back to the master. .IP "\(bu" 4 Solaris 8, 2.7, 2.6 .Sp Has the \*(L"feature\*(R" of returning \s-1EOF\s0 just once?! .Sp \&\s-1EOF\s0 on the slave tty is not reported back to the master. .IP "\(bu" 4 Windows NT/2k/XP (under Cygwin) .Sp When you send (print) a too long line (>160 chars) to a non-raw pty, the call just hangs forever and even \fBalarm()\fR cannot get you out. Don't complain to me... .Sp \&\s-1EOF\s0 on the slave tty is not reported back to the master. .IP "\(bu" 4 z/OS .PP The following systems have not been verified yet for this version, but a previous version worked on them: .IP "\(bu" 4 \&\s-1SCO\s0 Unix .IP "\(bu" 4 NetBSD .Sp probably the same as the other *BSDs... .PP If you have additions to these lists, please mail them to <\fIRGiersig@cpan.org\fR>. .SH "SEE ALSO" .IX Header "SEE ALSO" IO::Pty, IO::Tty::Constant .SH "MAILING LISTS" .IX Header "MAILING LISTS" As this module is mainly used by Expect, support for it is available via the two Expect mailing lists, expectperl-announce and expectperl-discuss, at .PP .Vb 1 \& http://lists.sourceforge.net/lists/listinfo/expectperl\-announce .Ve .PP and .PP .Vb 1 \& http://lists.sourceforge.net/lists/listinfo/expectperl\-discuss .Ve .SH "AUTHORS" .IX Header "AUTHORS" Originally by Graham Barr <\fIgbarr@pobox.com\fR>, based on the Ptty module by Nick Ing-Simmons <\fInik@tiuk.ti.com\fR>. .PP Now maintained and heavily rewritten by Roland Giersig <\fIRGiersig@cpan.org\fR>. .PP Contains copyrighted stuff from openssh v3.0p1, authored by Tatu Ylonen , Markus Friedl and Todd C. Miller . I also got a lot of inspiration from the pty code in Xemacs. .SH "COPYRIGHT" .IX Header "COPYRIGHT" Now all code is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP Nevertheless the above \s-1AUTHORS\s0 retain their copyrights to the various parts and want to receive credit if their source code is used. See the source for details. .SH "DISCLAIMER" .IX Header "DISCLAIMER" \&\s-1THIS SOFTWARE IS PROVIDED\s0 ``\s-1AS IS\s0'' \s-1AND 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\s0 (\s-1INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES\s0; \s-1LOSS OF USE, DATA, OR PROFITS\s0; \s-1OR BUSINESS INTERRUPTION\s0) \s-1HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\s0 (\s-1INCLUDING NEGLIGENCE OR OTHERWISE\s0) \s-1ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\s0 .PP In other words: Use at your own risk. Provided as is. Your mileage may vary. Read the source, Luke! .PP And finally, just to be sure: .PP 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. PK!N). .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Tty::Constant 3" .TH Tty::Constant 3 "2024-08-07" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" IO::Tty::Constant \- Terminal Constants (autogenerated) .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& use IO::Tty::Constant qw(TIOCNOTTY); \& ... .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This package defines constants usually found in or (and their #include hierarchy). Find below an autogenerated alphabetic list of all known constants and whether they are defined on your system (prefixed with '+') and have compilation problems ('o'). Undefined or problematic constants are set to 'undef'. .SH "DEFINED CONSTANTS" .IX Header "DEFINED CONSTANTS" .IP "+" 4 B0 .IP "+" 4 B110 .IP "+" 4 B115200 .IP "+" 4 B1200 .IP "+" 4 B134 .IP "+" 4 B150 .IP "\-" 4 B153600 .IP "+" 4 B1800 .IP "+" 4 B19200 .IP "+" 4 B200 .IP "+" 4 B230400 .IP "+" 4 B2400 .IP "+" 4 B300 .IP "\-" 4 B307200 .IP "+" 4 B38400 .IP "+" 4 B460800 .IP "+" 4 B4800 .IP "+" 4 B50 .IP "+" 4 B57600 .IP "+" 4 B600 .IP "+" 4 B75 .IP "\-" 4 B76800 .IP "+" 4 B9600 .IP "+" 4 \&\s-1BRKINT\s0 .IP "+" 4 \&\s-1BS0\s0 .IP "+" 4 \&\s-1BS1\s0 .IP "+" 4 \&\s-1BSDLY\s0 .IP "+" 4 \&\s-1CBAUD\s0 .IP "\-" 4 \&\s-1CBAUDEXT\s0 .IP "+" 4 \&\s-1CBRK\s0 .IP "\-" 4 \&\s-1CCTS_OFLOW\s0 .IP "\-" 4 \&\s-1CDEL\s0 .IP "+" 4 \&\s-1CDSUSP\s0 .IP "+" 4 \&\s-1CEOF\s0 .IP "+" 4 \&\s-1CEOL\s0 .IP "\-" 4 \&\s-1CEOL2\s0 .IP "+" 4 \&\s-1CEOT\s0 .IP "+" 4 \&\s-1CERASE\s0 .IP "\-" 4 \&\s-1CESC\s0 .IP "+" 4 \&\s-1CFLUSH\s0 .IP "+" 4 \&\s-1CIBAUD\s0 .IP "\-" 4 \&\s-1CIBAUDEXT\s0 .IP "+" 4 \&\s-1CINTR\s0 .IP "+" 4 \&\s-1CKILL\s0 .IP "+" 4 \&\s-1CLNEXT\s0 .IP "+" 4 \&\s-1CLOCAL\s0 .IP "\-" 4 \&\s-1CNSWTCH\s0 .IP "\-" 4 \&\s-1CNUL\s0 .IP "+" 4 \&\s-1CQUIT\s0 .IP "+" 4 \&\s-1CR0\s0 .IP "+" 4 \&\s-1CR1\s0 .IP "+" 4 \&\s-1CR2\s0 .IP "+" 4 \&\s-1CR3\s0 .IP "+" 4 \&\s-1CRDLY\s0 .IP "+" 4 \&\s-1CREAD\s0 .IP "+" 4 \&\s-1CRPRNT\s0 .IP "+" 4 \&\s-1CRTSCTS\s0 .IP "\-" 4 \&\s-1CRTSXOFF\s0 .IP "\-" 4 \&\s-1CRTS_IFLOW\s0 .IP "+" 4 \&\s-1CS5\s0 .IP "+" 4 \&\s-1CS6\s0 .IP "+" 4 \&\s-1CS7\s0 .IP "+" 4 \&\s-1CS8\s0 .IP "+" 4 \&\s-1CSIZE\s0 .IP "+" 4 \&\s-1CSTART\s0 .IP "+" 4 \&\s-1CSTOP\s0 .IP "+" 4 \&\s-1CSTOPB\s0 .IP "+" 4 \&\s-1CSUSP\s0 .IP "\-" 4 \&\s-1CSWTCH\s0 .IP "+" 4 \&\s-1CWERASE\s0 .IP "\-" 4 \&\s-1DEFECHO\s0 .IP "\-" 4 \&\s-1DIOC\s0 .IP "\-" 4 \&\s-1DIOCGETP\s0 .IP "\-" 4 \&\s-1DIOCSETP\s0 .IP "\-" 4 \&\s-1DOSMODE\s0 .IP "+" 4 \&\s-1ECHO\s0 .IP "+" 4 \&\s-1ECHOCTL\s0 .IP "+" 4 \&\s-1ECHOE\s0 .IP "+" 4 \&\s-1ECHOK\s0 .IP "+" 4 \&\s-1ECHOKE\s0 .IP "+" 4 \&\s-1ECHONL\s0 .IP "+" 4 \&\s-1ECHOPRT\s0 .IP "+" 4 \&\s-1EXTA\s0 .IP "+" 4 \&\s-1EXTB\s0 .IP "+" 4 \&\s-1FF0\s0 .IP "+" 4 \&\s-1FF1\s0 .IP "+" 4 \&\s-1FFDLY\s0 .IP "\-" 4 \&\s-1FIORDCHK\s0 .IP "+" 4 \&\s-1FLUSHO\s0 .IP "+" 4 \&\s-1HUPCL\s0 .IP "+" 4 \&\s-1ICANON\s0 .IP "+" 4 \&\s-1ICRNL\s0 .IP "+" 4 \&\s-1IEXTEN\s0 .IP "+" 4 \&\s-1IGNBRK\s0 .IP "+" 4 \&\s-1IGNCR\s0 .IP "+" 4 \&\s-1IGNPAR\s0 .IP "+" 4 \&\s-1IMAXBEL\s0 .IP "+" 4 \&\s-1INLCR\s0 .IP "+" 4 \&\s-1INPCK\s0 .IP "+" 4 \&\s-1ISIG\s0 .IP "+" 4 \&\s-1ISTRIP\s0 .IP "+" 4 \&\s-1IUCLC\s0 .IP "+" 4 \&\s-1IXANY\s0 .IP "+" 4 \&\s-1IXOFF\s0 .IP "+" 4 \&\s-1IXON\s0 .IP "\-" 4 \&\s-1KBENABLED\s0 .IP "\-" 4 \&\s-1LDCHG\s0 .IP "\-" 4 \&\s-1LDCLOSE\s0 .IP "\-" 4 \&\s-1LDDMAP\s0 .IP "\-" 4 \&\s-1LDEMAP\s0 .IP "\-" 4 \&\s-1LDGETT\s0 .IP "\-" 4 \&\s-1LDGMAP\s0 .IP "\-" 4 \&\s-1LDIOC\s0 .IP "\-" 4 \&\s-1LDNMAP\s0 .IP "\-" 4 \&\s-1LDOPEN\s0 .IP "\-" 4 \&\s-1LDSETT\s0 .IP "\-" 4 \&\s-1LDSMAP\s0 .IP "\-" 4 \&\s-1LOBLK\s0 .IP "+" 4 \&\s-1NCCS\s0 .IP "+" 4 \&\s-1NL0\s0 .IP "+" 4 \&\s-1NL1\s0 .IP "+" 4 \&\s-1NLDLY\s0 .IP "+" 4 \&\s-1NOFLSH\s0 .IP "+" 4 \&\s-1OCRNL\s0 .IP "+" 4 \&\s-1OFDEL\s0 .IP "+" 4 \&\s-1OFILL\s0 .IP "+" 4 \&\s-1OLCUC\s0 .IP "+" 4 \&\s-1ONLCR\s0 .IP "+" 4 \&\s-1ONLRET\s0 .IP "+" 4 \&\s-1ONOCR\s0 .IP "+" 4 \&\s-1OPOST\s0 .IP "\-" 4 \&\s-1PAGEOUT\s0 .IP "+" 4 \&\s-1PARENB\s0 .IP "\-" 4 \&\s-1PAREXT\s0 .IP "+" 4 \&\s-1PARMRK\s0 .IP "+" 4 \&\s-1PARODD\s0 .IP "+" 4 \&\s-1PENDIN\s0 .IP "\-" 4 \&\s-1RCV1EN\s0 .IP "\-" 4 \&\s-1RTS_TOG\s0 .IP "+" 4 \&\s-1TAB0\s0 .IP "+" 4 \&\s-1TAB1\s0 .IP "+" 4 \&\s-1TAB2\s0 .IP "+" 4 \&\s-1TAB3\s0 .IP "+" 4 \&\s-1TABDLY\s0 .IP "\-" 4 \&\s-1TCDSET\s0 .IP "+" 4 \&\s-1TCFLSH\s0 .IP "+" 4 \&\s-1TCGETA\s0 .IP "+" 4 \&\s-1TCGETS\s0 .IP "+" 4 \&\s-1TCIFLUSH\s0 .IP "+" 4 \&\s-1TCIOFF\s0 .IP "+" 4 \&\s-1TCIOFLUSH\s0 .IP "+" 4 \&\s-1TCION\s0 .IP "+" 4 \&\s-1TCOFLUSH\s0 .IP "+" 4 \&\s-1TCOOFF\s0 .IP "+" 4 \&\s-1TCOON\s0 .IP "+" 4 \&\s-1TCSADRAIN\s0 .IP "+" 4 \&\s-1TCSAFLUSH\s0 .IP "+" 4 \&\s-1TCSANOW\s0 .IP "+" 4 \&\s-1TCSBRK\s0 .IP "+" 4 \&\s-1TCSETA\s0 .IP "+" 4 \&\s-1TCSETAF\s0 .IP "+" 4 \&\s-1TCSETAW\s0 .IP "\-" 4 \&\s-1TCSETCTTY\s0 .IP "+" 4 \&\s-1TCSETS\s0 .IP "+" 4 \&\s-1TCSETSF\s0 .IP "+" 4 \&\s-1TCSETSW\s0 .IP "+" 4 \&\s-1TCXONC\s0 .IP "\-" 4 \&\s-1TERM_D40\s0 .IP "\-" 4 \&\s-1TERM_D42\s0 .IP "\-" 4 \&\s-1TERM_H45\s0 .IP "\-" 4 \&\s-1TERM_NONE\s0 .IP "\-" 4 \&\s-1TERM_TEC\s0 .IP "\-" 4 \&\s-1TERM_TEX\s0 .IP "\-" 4 \&\s-1TERM_V10\s0 .IP "\-" 4 \&\s-1TERM_V61\s0 .IP "+" 4 \&\s-1TIOCCBRK\s0 .IP "\-" 4 \&\s-1TIOCCDTR\s0 .IP "+" 4 \&\s-1TIOCCONS\s0 .IP "+" 4 \&\s-1TIOCEXCL\s0 .IP "\-" 4 \&\s-1TIOCFLUSH\s0 .IP "+" 4 \&\s-1TIOCGETD\s0 .IP "\-" 4 \&\s-1TIOCGETC\s0 .IP "\-" 4 \&\s-1TIOCGETP\s0 .IP "\-" 4 \&\s-1TIOCGLTC\s0 .IP "\-" 4 \&\s-1TIOCSETC\s0 .IP "\-" 4 \&\s-1TIOCSETN\s0 .IP "\-" 4 \&\s-1TIOCSETP\s0 .IP "\-" 4 \&\s-1TIOCSLTC\s0 .IP "+" 4 \&\s-1TIOCGPGRP\s0 .IP "+" 4 \&\s-1TIOCGSID\s0 .IP "+" 4 \&\s-1TIOCGSOFTCAR\s0 .IP "+" 4 \&\s-1TIOCGWINSZ\s0 .IP "\-" 4 \&\s-1TIOCHPCL\s0 .IP "\-" 4 \&\s-1TIOCKBOF\s0 .IP "\-" 4 \&\s-1TIOCKBON\s0 .IP "\-" 4 \&\s-1TIOCLBIC\s0 .IP "\-" 4 \&\s-1TIOCLBIS\s0 .IP "\-" 4 \&\s-1TIOCLGET\s0 .IP "\-" 4 \&\s-1TIOCLSET\s0 .IP "+" 4 \&\s-1TIOCMBIC\s0 .IP "+" 4 \&\s-1TIOCMBIS\s0 .IP "+" 4 \&\s-1TIOCMGET\s0 .IP "+" 4 \&\s-1TIOCMSET\s0 .IP "+" 4 \&\s-1TIOCM_CAR\s0 .IP "+" 4 \&\s-1TIOCM_CD\s0 .IP "+" 4 \&\s-1TIOCM_CTS\s0 .IP "+" 4 \&\s-1TIOCM_DSR\s0 .IP "+" 4 \&\s-1TIOCM_DTR\s0 .IP "+" 4 \&\s-1TIOCM_LE\s0 .IP "+" 4 \&\s-1TIOCM_RI\s0 .IP "+" 4 \&\s-1TIOCM_RNG\s0 .IP "+" 4 \&\s-1TIOCM_RTS\s0 .IP "+" 4 \&\s-1TIOCM_SR\s0 .IP "+" 4 \&\s-1TIOCM_ST\s0 .IP "+" 4 \&\s-1TIOCNOTTY\s0 .IP "+" 4 \&\s-1TIOCNXCL\s0 .IP "+" 4 \&\s-1TIOCOUTQ\s0 .IP "\-" 4 \&\s-1TIOCREMOTE\s0 .IP "+" 4 \&\s-1TIOCSBRK\s0 .IP "+" 4 \&\s-1TIOCSCTTY\s0 .IP "\-" 4 \&\s-1TIOCSDTR\s0 .IP "+" 4 \&\s-1TIOCSETD\s0 .IP "\-" 4 \&\s-1TIOCSIGNAL\s0 .IP "+" 4 \&\s-1TIOCSPGRP\s0 .IP "\-" 4 \&\s-1TIOCSSID\s0 .IP "+" 4 \&\s-1TIOCSSOFTCAR\s0 .IP "\-" 4 \&\s-1TIOCSTART\s0 .IP "+" 4 \&\s-1TIOCSTI\s0 .IP "\-" 4 \&\s-1TIOCSTOP\s0 .IP "+" 4 \&\s-1TIOCSWINSZ\s0 .IP "\-" 4 \&\s-1TM_ANL\s0 .IP "\-" 4 \&\s-1TM_CECHO\s0 .IP "\-" 4 \&\s-1TM_CINVIS\s0 .IP "\-" 4 \&\s-1TM_LCF\s0 .IP "\-" 4 \&\s-1TM_NONE\s0 .IP "\-" 4 \&\s-1TM_SET\s0 .IP "\-" 4 \&\s-1TM_SNL\s0 .IP "+" 4 \&\s-1TOSTOP\s0 .IP "\-" 4 \&\s-1VCEOF\s0 .IP "\-" 4 \&\s-1VCEOL\s0 .IP "+" 4 \&\s-1VDISCARD\s0 .IP "\-" 4 \&\s-1VDSUSP\s0 .IP "+" 4 \&\s-1VEOF\s0 .IP "+" 4 \&\s-1VEOL\s0 .IP "+" 4 \&\s-1VEOL2\s0 .IP "+" 4 \&\s-1VERASE\s0 .IP "+" 4 \&\s-1VINTR\s0 .IP "+" 4 \&\s-1VKILL\s0 .IP "+" 4 \&\s-1VLNEXT\s0 .IP "+" 4 \&\s-1VMIN\s0 .IP "+" 4 \&\s-1VQUIT\s0 .IP "+" 4 \&\s-1VREPRINT\s0 .IP "+" 4 \&\s-1VSTART\s0 .IP "+" 4 \&\s-1VSTOP\s0 .IP "+" 4 \&\s-1VSUSP\s0 .IP "\-" 4 \&\s-1VSWTCH\s0 .IP "+" 4 \&\s-1VT0\s0 .IP "+" 4 \&\s-1VT1\s0 .IP "+" 4 \&\s-1VTDLY\s0 .IP "+" 4 \&\s-1VTIME\s0 .IP "+" 4 \&\s-1VWERASE\s0 .IP "\-" 4 \&\s-1WRAP\s0 .IP "+" 4 \&\s-1XCASE\s0 .IP "\-" 4 \&\s-1XCLUDE\s0 .IP "\-" 4 \&\s-1XMT1EN\s0 .IP "+" 4 \&\s-1XTABS\s0 .SH "FOR MORE INFO SEE" .IX Header "FOR MORE INFO SEE" IO::Tty PK!LLman/man3/Expect.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Expect 3" .TH Expect 3 "2024-03-08" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Expect \- automate interactions with command line programs that expose a text terminal interface. .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use Expect; \& \& # create an Expect object by spawning another process \& my $exp = Expect\->spawn($command, @params) \& or die "Cannot spawn $command: $!\en"; \& \& # or by using an already opened filehandle (e.g. from Net::Telnet) \& my $exp = Expect\->exp_init(\e*FILEHANDLE); \& \& # if you prefer the OO mindset: \& my $exp = Expect\->new; \& $exp\->raw_pty(1); \& $exp\->spawn($command, @parameters) \& or die "Cannot spawn $command: $!\en"; \& \& # send some string there: \& $exp\->send("string\en"); \& \& # or, for the filehandle mindset: \& print $exp "string\en"; \& \& # 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\en"); \& exp_continue; } ], \& [ "regexp2" , \e&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(); .Ve .PP 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: .PP .Vb 10 \& 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 | \e&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,\e&function,\e@parameters); .Ve .PP There are several configurable package variables that affect the behavior of Expect. They are: .PP .Vb 8 \& $Expect::Debug; \& $Expect::Exp_Internal; \& $Expect::IgnoreEintr; \& $Expect::Log_Group; \& $Expect::Log_Stdout; \& $Expect::Manual_Stty; \& $Expect::Multiline_Matching; \& $Expect::Do_Soft_Close; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" See an explanation of What is Expect .PP 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. .PP Expect.pm is an attempt to have more of a \fBswitch()\fR & case feeling to make decision processing more fluid. Three separate types of debugging have been implemented to make code production easier. .PP 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 :\-) . .PP Please, before you consider using Expect, read the FAQs about \&\*(L"I want to automate password entry for su/ssh/scp/rsh/...\*(R" and \&\*(L"I want to use Expect to automate [anything with a buzzword]...\*(R" .SH "USAGE" .IX Header "USAGE" .IP "new" 4 .IX 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 \fBslave()\fR below. The object returned is actually a reblessed IO::Pty filehandle, so see there for additional methods. .IP "Expect\->exp_init(\e*FILEHANDLE) \fIor\fR" 4 .IX Item "Expect->exp_init(*FILEHANDLE) or" .PD 0 .IP "Expect\->init(\e*FILEHANDLE)" 4 .IX Item "Expect->init(*FILEHANDLE)" .PD Initializes \f(CW$new_handle_object\fR for use with other Expect functions. It must be passed a \fB_reference_\fR to \s-1FILEHANDLE\s0 if you want it to work properly. IO::File objects are preferable. Returns a reference to the newly created object. .Sp You can use only real filehandles, certain tied filehandles (e.g. Net::SSH2) that lack a \fBfileno()\fR will not work. Net::Telnet objects can be used but have been reported to work only for certain hosts. \s-1YMMV.\s0 .ie n .IP "Expect\->spawn($command, @parameters) \fIor\fR" 4 .el .IP "Expect\->spawn($command, \f(CW@parameters\fR) \fIor\fR" 4 .IX Item "Expect->spawn($command, @parameters) or" .PD 0 .ie n .IP "$object\->spawn($command, @parameters) \fIor\fR" 4 .el .IP "\f(CW$object\fR\->spawn($command, \f(CW@parameters\fR) \fIor\fR" 4 .IX Item "$object->spawn($command, @parameters) or" .ie n .IP "Expect\->new($command, @parameters)" 4 .el .IP "Expect\->new($command, \f(CW@parameters\fR)" 4 .IX Item "Expect->new($command, @parameters)" .PD Forks and execs \f(CW$command\fR. Returns an Expect object upon success or \&\f(CW\*(C`undef\*(C'\fR if the fork was unsuccessful or the command could not be found. \fBspawn()\fR passes its parameters unchanged to Perls \fBexec()\fR, so look there for detailed semantics. .Sp Note that if spawn cannot \fBexec()\fR the given command, the Expect object is still valid and the next \fBexpect()\fR will see \*(L"Cannot exec\*(R", so you can use that for error handling. .Sp 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... .ie n .IP "$object\->debug(0 | 1 | 2 | 3 | undef)" 4 .el .IP "\f(CW$object\fR\->debug(0 | 1 | 2 | 3 | undef)" 4 .IX Item "$object->debug(0 | 1 | 2 | 3 | undef)" Sets debug level for \f(CW$object\fR. 1 refers to general debugging information, 2 refers to verbose debugging and 0 refers to no debugging. If you call \fBdebug()\fR with no parameters it will return the current debugging level. When the object is created the debugging level will match that \f(CW$Expect::Debug\fR, normally 0. .Sp 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.. .ie n .IP "$object\->exp_internal(1 | 0)" 4 .el .IP "\f(CW$object\fR\->exp_internal(1 | 0)" 4 .IX 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 \fBexpect()\fR sequences. When the object is created the exp_internal setting will match the value of \&\f(CW$Expect::Exp_Internal\fR, 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. .ie n .IP "$object\->raw_pty(1 | 0)" 4 .el .IP "\f(CW$object\fR\->raw_pty(1 | 0)" 4 .IX Item "$object->raw_pty(1 | 0)" Set pty to raw mode before spawning. This disables echoing, \s-1CR\-\s0>\s-1LF\s0 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 \fIbefore\fR spawning the program. .ie n .IP "$object\->stty(qw(mode1 mode2...))" 4 .el .IP "\f(CW$object\fR\->stty(qw(mode1 mode2...))" 4 .IX Item "$object->stty(qw(mode1 mode2...))" Sets the tty mode for \f(CW$object\fR'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. .ie n .IP "$object\->\fBslave()\fR" 4 .el .IP "\f(CW$object\fR\->\fBslave()\fR" 4 .IX Item "$object->slave()" Returns a filehandle to the slave part of the pty. Very useful in modifying the terminal settings: .Sp .Vb 1 \& $object\->slave\->stty(qw(raw \-echo)); .Ve .Sp 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). .ie n .IP "$object\->print(@strings) \fIor\fR" 4 .el .IP "\f(CW$object\fR\->print(@strings) \fIor\fR" 4 .IX Item "$object->print(@strings) or" .PD 0 .ie n .IP "$object\->send(@strings)" 4 .el .IP "\f(CW$object\fR\->send(@strings)" 4 .IX Item "$object->send(@strings)" .PD 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 \fBexpect()\fRing 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. .ie n .IP "$object\->expect($timeout, @match_patterns)" 4 .el .IP "\f(CW$object\fR\->expect($timeout, \f(CW@match_patterns\fR)" 4 .IX Item "$object->expect($timeout, @match_patterns)" .RS 4 .PD 0 .IP "Simple interface" 4 .IX Item "Simple interface" .PD Given \f(CW$timeout\fR in seconds Expect will wait for \f(CW$object\fR'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 (\f(CW\*(C`qr//\*(C'\fR) or prefix the pattern with '\-re'. .Sp .Vb 2 \& $object\->expect(15, \*(Aqmatch me exactly\*(Aq, qr/match\es+me\es+exactly/); \& $object\->expect(15, \*(Aqmatch me exactly\*(Aq,\*(Aq\-re\*(Aq,\*(Aqmatch\es+me\es+exactly\*(Aq); .Ve .Sp Due to o/s limitations \f(CW$timeout\fR should be a round number. If \f(CW$timeout\fR is 0 Expect will check one time to see if \f(CW$object\fR's handle contains any of the match_patterns. If \f(CW$timeout\fR 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 \f(CW\*(C`expect\*(C'\fR, you can set it via the \f(CW\*(C`timeout\*(C'\fR method . If the first argument of \f(CW\*(C`expect\*(C'\fR doesn't look like a number, that value will be used. .Sp .Vb 2 \& $object\->timeout(15); \& $object\->expect(\*(Aqmatch me exactly\*(Aq,\*(Aq\-re\*(Aq,\*(Aqmatch\es+me\es+exactly\*(Aq); .Ve .Sp If called in a scalar context, \fBexpect()\fR will return the position of the matched pattern within \f(CW@matched_patterns\fR, 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 \f(CW@matched_patterns\fR matched you should subtract one from the return value. .Sp If called in an array context \fBexpect()\fR will return ($matched_pattern_position, \f(CW$error\fR, \f(CW$successfully_matching_string\fR, \&\f(CW$before_match\fR, and \f(CW$after_match\fR). .Sp \&\f(CW$matched_pattern_position\fR will contain the value that would have been returned if \fBexpect()\fR had been called in a scalar context. .Sp \&\f(CW$error\fR is the error that occurred that caused \fBexpect()\fR to return. \f(CW$error\fR 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 \f(CW$timeout\fR seconds had elapsed without a match, '2:EOF' indicating an eof was read from \f(CW$object\fR, '3: spawn id($fileno) died' indicating that the process exited before matching and '4:$!' indicating whatever error was set in \f(CW$ERRNO\fR during the last read on \f(CW$object\fR's handle or during \fBselect()\fR. All handles indicated by set_group plus \s-1STDOUT\s0 will have all data to come out of \f(CW$object\fR printed to them during \fBexpect()\fR if log_group and log_stdout are set. .Sp \&\f(CW$successfully_matching_string\fR \&\f(CW$before_match\fR \&\f(CW$after_match\fR .Sp Changed from older versions is the regular expression handling. By default now all strings passed to \fBexpect()\fR 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. .Sp This change makes it possible to match literals and regular expressions in the same \fBexpect()\fR call. .Sp 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 \*(L"\er\en\*(R" at the end of every line. One way to check for a pattern at the end of a line would be to use \er?$ instead of $. .Sp Example: Spawning telnet to a host, you might look for the escape character. telnet would return to you \*(L"\er\enEscape character is \&'^]'.\er\en\*(R". To find this you might use \f(CW$match\fR='^Escape char.*\e.\er?$'; .Sp .Vb 1 \& $telnet\->expect(10,\*(Aq\-re\*(Aq,$match); .Ve .IP "New more Tcl/Expect\-like interface" 4 .IX Item "New more Tcl/Expect-like interface" .Vb 11 \& expect($timeout, \& \*(Aq\-i\*(Aq, [ $obj1, $obj2, ... ], \& [ $re_pattern, sub { ...; exp_continue; }, @subparms, ], \& [ \*(Aqeof\*(Aq, sub { ... } ], \& [ \*(Aqtimeout\*(Aq, sub { ... }, \e$subparm1 ], \& \*(Aq\-i\*(Aq, [ $objn, ...], \& \*(Aq\-ex\*(Aq, $exact_pattern, sub { ... }, \& $exact_pattern, sub { ...; exp_continue_timeout; }, \& \*(Aq\-re\*(Aq, $re_pattern, sub { ... }, \& \*(Aq\-i\*(Aq, \e@object_list, @pattern_list, \& ...); .Ve .Sp It's now possible to expect on more than one connection at a time by specifying '\f(CW\*(C`\-i\*(C'\fR' and a single Expect object or a ref to an array containing Expect objects, e.g. .Sp .Vb 4 \& expect($timeout, \& \*(Aq\-i\*(Aq, $exp1, @patterns_1, \& \*(Aq\-i\*(Aq, [ $exp2, $exp3 ], @patterns_2_3, \& ) .Ve .Sp Furthermore, patterns can now be specified as array refs containing [$regexp, sub { ...}, \f(CW@optional_subprams\fR] . When the pattern matches, the subroutine is called with parameters ($matched_expect_obj, \&\f(CW@optional_subparms\fR). 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. .Sp .Vb 8 \& $exp\->expect($timeout, \& [ qr/username: /i, sub { my $self = shift; \& $self\->send("$username\en"); \& exp_continue; }], \& [ qr/password: /i, sub { my $self = shift; \& $self\->send("$password\en"); \& exp_continue; }], \& $shell_prompt); .Ve .Sp `expect' is now exported by default. .RE .RS 4 .RE .ie n .IP "$object\->\fBexp_before()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_before()\fR \fIor\fR" 4 .IX Item "$object->exp_before() or" .PD 0 .ie n .IP "$object\->\fBbefore()\fR" 4 .el .IP "\f(CW$object\fR\->\fBbefore()\fR" 4 .IX Item "$object->before()" .PD \&\fBbefore()\fR returns the 'before' part of the last \fBexpect()\fR call. If the last \&\fBexpect()\fR call didn't match anything, \fBexp_before()\fR will return the entire output of the object accumulated before the \fBexpect()\fR call finished. .Sp Note that this is something different than Tcl Expects \fBbefore()\fR!! .ie n .IP "$object\->\fBexp_after()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_after()\fR \fIor\fR" 4 .IX Item "$object->exp_after() or" .PD 0 .ie n .IP "$object\->\fBafter()\fR" 4 .el .IP "\f(CW$object\fR\->\fBafter()\fR" 4 .IX Item "$object->after()" .PD returns the 'after' part of the last \fBexpect()\fR call. If the last \&\fBexpect()\fR call didn't match anything, \fBexp_after()\fR will return \fBundef()\fR. .ie n .IP "$object\->\fBexp_match()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_match()\fR \fIor\fR" 4 .IX Item "$object->exp_match() or" .PD 0 .ie n .IP "$object\->\fBmatch()\fR" 4 .el .IP "\f(CW$object\fR\->\fBmatch()\fR" 4 .IX Item "$object->match()" .PD returns the string matched by the last \fBexpect()\fR call, undef if no string was matched. .ie n .IP "$object\->\fBexp_match_number()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_match_number()\fR \fIor\fR" 4 .IX Item "$object->exp_match_number() or" .PD 0 .ie n .IP "$object\->\fBmatch_number()\fR" 4 .el .IP "\f(CW$object\fR\->\fBmatch_number()\fR" 4 .IX Item "$object->match_number()" .PD \&\fBexp_match_number()\fR returns the number of the pattern matched by the last \&\fBexpect()\fR call. Keep in mind that the first pattern in a list of patterns is 1, not 0. Returns undef if no pattern was matched. .ie n .IP "$object\->\fBexp_matchlist()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_matchlist()\fR \fIor\fR" 4 .IX Item "$object->exp_matchlist() or" .PD 0 .ie n .IP "$object\->\fBmatchlist()\fR" 4 .el .IP "\f(CW$object\fR\->\fBmatchlist()\fR" 4 .IX Item "$object->matchlist()" .PD \&\fBexp_matchlist()\fR returns a list of matched substrings from the brackets () inside the regexp that last matched. ($object\->matchlist)[0] thus corresponds to \f(CW$1\fR, ($object\->matchlist)[1] to \f(CW$2\fR, etc. .ie n .IP "$object\->\fBexp_error()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_error()\fR \fIor\fR" 4 .IX Item "$object->exp_error() or" .PD 0 .ie n .IP "$object\->\fBerror()\fR" 4 .el .IP "\f(CW$object\fR\->\fBerror()\fR" 4 .IX Item "$object->error()" .PD \&\fBexp_error()\fR returns the error generated by the last \fBexpect()\fR call if no pattern was matched. It is typically useful to examine the value returned by \&\fBbefore()\fR to find out what the output of the object was in determining why it didn't match any of the patterns. .ie n .IP "$object\->\fBclear_accum()\fR" 4 .el .IP "\f(CW$object\fR\->\fBclear_accum()\fR" 4 .IX Item "$object->clear_accum()" Clear the contents of the accumulator for \f(CW$object\fR. This gets rid of any residual contents of a handle after \fBexpect()\fR or \fBsend_slow()\fR such that the next \fBexpect()\fR call will only see new data from \f(CW$object\fR. The contents of the accumulator are returned. .ie n .IP "$object\->set_accum($value)" 4 .el .IP "\f(CW$object\fR\->set_accum($value)" 4 .IX Item "$object->set_accum($value)" Sets the content of the accumulator for \f(CW$object\fR to \f(CW$value\fR. The previous content of the accumulator is returned. .ie n .IP "$object\->\fBexp_command()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_command()\fR \fIor\fR" 4 .IX Item "$object->exp_command() or" .PD 0 .ie n .IP "$object\->\fBcommand()\fR" 4 .el .IP "\f(CW$object\fR\->\fBcommand()\fR" 4 .IX Item "$object->command()" .PD \&\fBexp_command()\fR returns the string that was used to spawn the command. Helpful for debugging and for reused patternmatch subroutines. .ie n .IP "$object\->\fBexp_exitstatus()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_exitstatus()\fR \fIor\fR" 4 .IX Item "$object->exp_exitstatus() or" .PD 0 .ie n .IP "$object\->\fBexitstatus()\fR" 4 .el .IP "\f(CW$object\fR\->\fBexitstatus()\fR" 4 .IX Item "$object->exitstatus()" .PD Returns the exit status of \f(CW$object\fR (if it already exited). .ie n .IP "$object\->\fBexp_pty_handle()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_pty_handle()\fR \fIor\fR" 4 .IX Item "$object->exp_pty_handle() or" .PD 0 .ie n .IP "$object\->\fBpty_handle()\fR" 4 .el .IP "\f(CW$object\fR\->\fBpty_handle()\fR" 4 .IX Item "$object->pty_handle()" .PD Returns a string representation of the attached pty, for example: `spawn \fBid\fR\|(5)' (pty has fileno 5), `handle \fBid\fR\|(7)' (pty was initialized from fileno 7) or `\s-1STDIN\s0'. Useful for debugging. .ie n .IP "$object\->restart_timeout_upon_receive(0 | 1)" 4 .el .IP "\f(CW$object\fR\->restart_timeout_upon_receive(0 | 1)" 4 .IX 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. .Sp .Vb 5 \& $exp\->restart_timeout_upon_receive(1); \& $exp\->expect($timeout, \& [ timeout => \e&report_timeout ], \& [ qr/pattern/ => \e&handle_pattern], \& ); .Ve .Sp 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. .ie n .IP "$object\->notransfer(1 | 0)" 4 .el .IP "\f(CW$object\fR\->notransfer(1 | 0)" 4 .IX 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 .Sp .Vb 1 \& $exp\->set_accum($exp\->after); .Ve .Sp to their callback, e.g. .Sp .Vb 12 \& $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()); \& } ], \& ); .Ve .Sp This is only a temporary fix until I can rewrite the pattern matching part so it can take that additional \-notransfer argument. .IP "Expect::interconnect(@objects);" 4 .IX Item "Expect::interconnect(@objects);" Read from \f(CW@objects\fR and print to their \f(CW@listen_groups\fR until an escape sequence is matched from one of \f(CW@objects\fR and the associated function returns 0 or undef. The special escape sequence '\s-1EOF\s0' 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 \f(CW@objects\fR 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 \s-1STDOUT\s0 (for example)? By default every member of \f(CW@objects\fR _as well as every member of its listen group_ will be set to 'raw \-echo' for the duration of interconnection. Setting \f(CW$object\fR\->\fBmanual_stty()\fR will stop this behavior per object. The original tty settings will be restored as interconnect exits. .Sp For a generic way to interconnect processes, take a look at IPC::Run. .IP "Expect::test_handles(@objects)" 4 .IX Item "Expect::test_handles(@objects)" Given a set of objects determines which objects' handles have data ready to be read. \fBReturns an array\fR who's members are positions in \f(CW@objects\fR that have ready handles. Returns undef if there are no such handles ready. .IP "Expect::version($version_requested or undef);" 4 .IX 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. .ie n .IP "$object\->interact( ""\e*FILEHANDLE, $escape_sequence"")" 4 .el .IP "\f(CW$object\fR\->interact( \f(CW\e*FILEHANDLE, $escape_sequence\fR)" 4 .IX Item "$object->interact( *FILEHANDLE, $escape_sequence)" \&\fBinteract()\fR is essentially a macro for calling \fBinterconnect()\fR for connecting 2 processes together. \e*FILEHANDLE defaults to \e*STDIN and \&\f(CW$escape_sequence\fR defaults to undef. Interaction ceases when \f(CW$escape_sequence\fR is read from \fB\s-1FILEHANDLE\s0\fR, not \f(CW$object\fR. \f(CW$object\fR's listen group will consist solely of \e*FILEHANDLE for the duration of the interaction. \&\e*FILEHANDLE will not be echoed on \s-1STDOUT.\s0 .ie n .IP "$object\->log_group(0 | 1 | undef)" 4 .el .IP "\f(CW$object\fR\->log_group(0 | 1 | undef)" 4 .IX Item "$object->log_group(0 | 1 | undef)" Set/unset logging of \f(CW$object\fR to its 'listen group'. If set all objects in the listen group will have output from \f(CW$object\fR printed to them during \&\f(CW$object\fR\->\fBexpect()\fR, \f(CW$object\fR\->\fBsend_slow()\fR, and \f(CW\*(C`Expect::interconnect($object , ...)\*(C'\fR. Default value is on. During creation of \f(CW$object\fR the setting will match the value of \f(CW$Expect::Log_Group\fR, normally 1. .ie n .IP "$object\->log_user(0 | 1 | undef) \fIor\fR" 4 .el .IP "\f(CW$object\fR\->log_user(0 | 1 | undef) \fIor\fR" 4 .IX Item "$object->log_user(0 | 1 | undef) or" .PD 0 .ie n .IP "$object\->log_stdout(0 | 1 | undef)" 4 .el .IP "\f(CW$object\fR\->log_stdout(0 | 1 | undef)" 4 .IX Item "$object->log_stdout(0 | 1 | undef)" .PD Set/unset logging of object's handle to \s-1STDOUT.\s0 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 \f(CW$Expect::Log_Stdout\fR variable, normally 1. If/when you initialize \s-1STDIN\s0 it is usually associated with a tty which will by default echo to \s-1STDOUT\s0 anyway, so be careful or you will have multiple echoes. .ie n .IP "$object\->log_file(""filename"" | $filehandle | \e&coderef | undef)" 4 .el .IP "\f(CW$object\fR\->log_file(``filename'' | \f(CW$filehandle\fR | \e&coderef | undef)" 4 .IX 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 \*(L"w\*(R" to truncate the file upon \fBopen()\fR: .Sp .Vb 1 \& $object\->log_file("filename", "w"); .Ve .Sp Returns the logfilehandle. .Sp If called with an undef value, stops logging and closes logfile: .Sp .Vb 1 \& $object\->log_file(undef); .Ve .Sp If called without argument, returns the logfilehandle: .Sp .Vb 1 \& $fh = $object\->log_file(); .Ve .Sp Can be set to a code ref, which will be called instead of printing to the logfile: .Sp .Vb 1 \& $object\->log_file(\e&myloggerfunc); .Ve .ie n .IP "$object\->print_log_file(@strings)" 4 .el .IP "\f(CW$object\fR\->print_log_file(@strings)" 4 .IX 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 \f(CW$object\fR\->log_file\->\fBprint()\fR but would only work for log files, not code hooks. .ie n .IP "$object\->set_seq($sequence, \e&function, \e@function_parameters)" 4 .el .IP "\f(CW$object\fR\->set_seq($sequence, \e&function, \e@function_parameters)" 4 .IX Item "$object->set_seq($sequence, &function, @function_parameters)" During Expect\->\fBinterconnect()\fR if \f(CW$sequence\fR is read from \f(CW$object\fR &function will be executed with parameters \f(CW@function_parameters\fR. It is \fB_highly recommended_\fR 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 \f(CW$object\fR's handle, making it impossible to strip \f(CW$sequence\fR from getting printed to \f(CW$object\fR's listen group. \e&function should be something like 'main::control_w_function' and \f(CW@function_parameters\fR should be an array defined by the caller, passed by reference to \fBset_seq()\fR. Your function should return a non-zero value if execution of \fBinterconnect()\fR is to resume after the function returns, zero or undefined if \fBinterconnect()\fR should return after your function returns. The special sequence '\s-1EOF\s0' matches the end of file being reached by \f(CW$object\fR. See \fBinterconnect()\fR for details. .ie n .IP "$object\->set_group(@listener_objects)" 4 .el .IP "\f(CW$object\fR\->set_group(@listener_objects)" 4 .IX Item "$object->set_group(@listener_objects)" \&\f(CW@listener_objects\fR is the list of objects that should have their handles printed to by \f(CW$object\fR when Expect::interconnect, \f(CW$object\fR\->\fBexpect()\fR or \&\f(CW$object\fR\->\fBsend_slow()\fR are called. Calling w/out parameters will return the current list of the listener objects. .ie n .IP "$object\->manual_stty(0 | 1 | undef)" 4 .el .IP "\f(CW$object\fR\->manual_stty(0 | 1 | undef)" 4 .IX 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 \f(CW$object\fR. Will match \&\f(CW$Expect::Manual_Stty\fR value (normally 0) when \f(CW$object\fR is created. If called without parameters \fBmanual_stty()\fR will return the current manual_stty setting. .ie n .IP "$object\->match_max($maximum_buffer_length | undef) \fIor\fR" 4 .el .IP "\f(CW$object\fR\->match_max($maximum_buffer_length | undef) \fIor\fR" 4 .IX Item "$object->match_max($maximum_buffer_length | undef) or" .PD 0 .ie n .IP "$object\->max_accum($maximum_buffer_length | undef)" 4 .el .IP "\f(CW$object\fR\->max_accum($maximum_buffer_length | undef)" 4 .IX Item "$object->max_accum($maximum_buffer_length | undef)" .PD Set the maximum accumulator size for object. This is useful if you think that the accumulator will grow out of hand during \fBexpect()\fR 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. .ie n .IP "$object\->notransfer(0 | 1)" 4 .el .IP "\f(CW$object\fR\->notransfer(0 | 1)" 4 .IX 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. .ie n .IP "$object\->\fBexp_pid()\fR \fIor\fR" 4 .el .IP "\f(CW$object\fR\->\fBexp_pid()\fR \fIor\fR" 4 .IX Item "$object->exp_pid() or" .PD 0 .ie n .IP "$object\->\fBpid()\fR" 4 .el .IP "\f(CW$object\fR\->\fBpid()\fR" 4 .IX Item "$object->pid()" .PD Return pid of \f(CW$object\fR, if one exists. Initialized filehandles will not have pids (of course). .ie n .IP "$object\->send_slow($delay, @strings);" 4 .el .IP "\f(CW$object\fR\->send_slow($delay, \f(CW@strings\fR);" 4 .IX Item "$object->send_slow($delay, @strings);" print each character from each string of \f(CW@strings\fR one at a time with \f(CW$delay\fR 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 \&\f(CW$object\fR will be checked to determine whether or not it has any new data ready and if so update the accumulator for future \fBexpect()\fR calls and print the output to \s-1STDOUT\s0 and \f(CW@listen_group\fR if log_stdout and log_group are appropriately set. .SS "Configurable Package Variables:" .IX Subsection "Configurable Package Variables:" .ie n .IP "$Expect::Debug" 4 .el .IP "\f(CW$Expect::Debug\fR" 4 .IX Item "$Expect::Debug" Defaults to 0. Newly created objects have a \f(CW$object\fR\->\fBdebug()\fR value of \f(CW$Expect::Debug\fR. See \f(CW$object\fR\->\fBdebug()\fR; .ie n .IP "$Expect::Do_Soft_Close" 4 .el .IP "\f(CW$Expect::Do_Soft_Close\fR" 4 .IX 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. .ie n .IP "$Expect::Exp_Internal" 4 .el .IP "\f(CW$Expect::Exp_Internal\fR" 4 .IX Item "$Expect::Exp_Internal" Defaults to 0. Newly created objects have a \f(CW$object\fR\->\fBexp_internal()\fR value of \f(CW$Expect::Exp_Internal\fR. See \f(CW$object\fR\->\fBexp_internal()\fR. .ie n .IP "$Expect::IgnoreEintr" 4 .el .IP "\f(CW$Expect::IgnoreEintr\fR" 4 .IX Item "$Expect::IgnoreEintr" Defaults to 0. If set to 1, when waiting for new data, Expect will ignore \s-1EINTR\s0 errors and restart the \fBselect()\fR call instead. .ie n .IP "$Expect::Log_Group" 4 .el .IP "\f(CW$Expect::Log_Group\fR" 4 .IX Item "$Expect::Log_Group" Defaults to 1. Newly created objects have a \f(CW$object\fR\->\fBlog_group()\fR value of \f(CW$Expect::Log_Group\fR. See \f(CW$object\fR\->\fBlog_group()\fR. .ie n .IP "$Expect::Log_Stdout" 4 .el .IP "\f(CW$Expect::Log_Stdout\fR" 4 .IX Item "$Expect::Log_Stdout" Defaults to 1 for spawned commands, 0 for file handles attached with \fBexp_init()\fR. Newly created objects have a \&\f(CW$object\fR\->\fBlog_stdout()\fR value of \f(CW$Expect::Log_Stdout\fR. See \&\f(CW$object\fR\->\fBlog_stdout()\fR. .ie n .IP "$Expect::Manual_Stty" 4 .el .IP "\f(CW$Expect::Manual_Stty\fR" 4 .IX Item "$Expect::Manual_Stty" Defaults to 0. Newly created objects have a \f(CW$object\fR\->\fBmanual_stty()\fR value of \f(CW$Expect::Manual_Stty\fR. See \f(CW$object\fR\->\fBmanual_stty()\fR. .ie n .IP "$Expect::Multiline_Matching" 4 .el .IP "\f(CW$Expect::Multiline_Matching\fR" 4 .IX Item "$Expect::Multiline_Matching" Defaults to 1. Affects whether or not \fBexpect()\fR uses the /m flag for doing regular expression matching. If set to 1 /m is used. .Sp 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. .Sp The \f(CW$Expect::Multiline_Matching\fR 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 \f(CW$Expect::Multiline_Matching\fR 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). .SH "CONTRIBUTIONS" .IX Header "CONTRIBUTIONS" Lee Eakin has ported the kibitz script from Tcl/Expect to Perl/Expect. .PP Jeff Carr provided a simple example of how handle terminal window resize events (transmitted via the \s-1WINCH\s0 signal) in a ssh session. .PP You can find both scripts in the examples/ subdir. Thanks to both! .PP Historical notes: .PP 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 \s-1NT\s0 box with one line of perl code' Schwartz for making these available to the perl public. .PP 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. .SH "REFERENCES" .IX Header "REFERENCES" Mark Rogaski wrote: .PP \&\*(L"I figured that you'd like to know that Expect.pm has been very useful to \s-1AT&T\s0 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 (\s-1AT&T\s0 Frame Relay) uses Expect.pm quite extensively.\*(R" .SH "FAQ \- Frequently Asked Questions" .IX Header "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 .SS "What systems does Expect run on?" .IX Subsection "What systems does Expect run on?" Expect itself doesn't have real system dependencies, but the underlying IO::Tty needs pseudoterminals. IO::Stty uses \s-1POSIX\s0.pm and Fcntl.pm. .PP I have used it on Solaris, Linux and \s-1AIX,\s0 others report *BSD and \s-1OSF\s0 as working. Generally, any modern \s-1POSIX\s0 Unix should do, but there are exceptions to every rule. Feedback is appreciated. .PP See IO::Tty for a list of verified systems. .SS "Can I use this module with ActivePerl on Windows?" .IX Subsection "Can I use this module with ActivePerl on Windows?" Up to now, the answer was 'No', but this has changed. .PP 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). .SS "The examples in the tutorial don't work!" .IX Subsection "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. .SS "How can I find out what Expect is doing?" .IX Subsection "How can I find out what Expect is doing?" If you set .PP .Vb 1 \& $Expect::Exp_Internal = 1; .Ve .PP 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 .PP .Vb 1 \& $exp\->exp_internal(1); .Ve .PP You can also set .PP .Vb 1 \& $Expect::Debug = 1; # or 2, 3 for more verbose output .Ve .PP or .PP .Vb 1 \& $exp\->debug(1); .Ve .PP which gives you even more output. .SS "I am seeing the output of the command I spawned. Can I turn that off?" .IX Subsection "I am seeing the output of the command I spawned. Can I turn that off?" Yes, just set .PP .Vb 1 \& $Expect::Log_Stdout = 0; .Ve .PP to globally disable it or .PP .Vb 1 \& $exp\->log_stdout(0); .Ve .PP for just that command. 'log_user' is provided as an alias so Tcl/Expect user get a \s-1DWIM\s0 experience... :\-) .SS "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." .IX Subsection "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 \*(L"\er\*(R" to the program instead of \*(L"\en\*(R" (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 \f(CW\*(C`$exp\->raw_pty(1)\*(C'\fR. .SS "How do I send control characters to a process?" .IX Subsection "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 \ec followed by the letter. For example, control-G can be represented with \*(L"\ecG\*(R" . Note that this will not work if you single-quote your string. So, to send control-C to a process in \&\f(CW$exp\fR, do: .PP .Vb 1 \& print $exp "\ecC"; .Ve .PP Or, if you prefer: .PP .Vb 1 \& $exp\->send("\ecC"); .Ve .PP 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. .SS "My script fails from time to time without any obvious reason. It seems that I am sometimes loosing output from the spawned program." .IX Subsection "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 \f(CW$exp\fR\->\fBsoft_close()\fR to terminate the program gracefully or do an \fBexpect()\fR for 'eof'. .PP Alternatively, try adding a 'sleep 1' after you \fBspawn()\fR 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). .SS "I want to automate password entry for su/ssh/scp/rsh/..." .IX Subsection "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 \s-1RSA\s0 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. .PP 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. .SS "I want to use Expect to automate [anything with a buzzword]..." .IX Subsection "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 \s-1HTTP\s0 requests by spawning telnet to port 80, use \s-1LWP\s0 instead. To automate \s-1FTP,\s0 take a look at Net::FTP or \f(CW\*(C`ncftp\*(C'\fR (http://www.ncftp.org). You don't use a screwdriver to hammer in your nails either, or do you? .SS "Is it possible to use threads with Expect?" .IX Subsection "Is it possible to use threads with Expect?" Basically yes, with one restriction: you must \fBspawn()\fR your programs in the main thread and then pass the Expect objects to the handling threads. The reason is that \fBspawn()\fR uses \fBfork()\fR, and perlthrtut: .PP .Vb 1 \& "Thinking of mixing fork() and threads? Please lie down and wait until the feeling passes." .Ve .SS "I want to log the whole session to a file." .IX Subsection "I want to log the whole session to a file." Use .PP .Vb 1 \& $exp\->log_file("filename"); .Ve .PP or .PP .Vb 1 \& $exp\->log_file($filehandle); .Ve .PP or even .PP .Vb 1 \& $exp\->log_file(\e&log_procedure); .Ve .PP for maximum flexibility. .PP Note that the logfile is appended to by default, but you can specify an optional mode \*(L"w\*(R" to truncate the logfile: .PP .Vb 1 \& $exp\->log_file("filename", "w"); .Ve .PP To stop logging, just call it with a false argument: .PP .Vb 1 \& $exp\->log_file(undef); .Ve .SS "How can I turn off multi-line matching for my regexps?" .IX Subsection "How can I turn off multi-line matching for my regexps?" To globally unset multi-line matching for all regexps: .PP .Vb 1 \& $Expect::Multiline_Matching = 0; .Ve .PP You can do that on a per-regexp basis by stating \f(CW\*(C`(?\-m)\*(C'\fR inside the regexp (you need perl5.00503 or later for that). .SS "How can I expect on multiple spawned commands?" .IX Subsection "How can I expect on multiple spawned commands?" You can use the \fB\-i\fR parameter to specify a single object or a list of Expect objects. All following patterns will be evaluated against that list. .PP You can specify \fB\-i\fR multiple times to create groups of objects and patterns to match against within the same expect statement. .PP This works just like in Tcl/Expect. .PP See the source example below. .SS "I seem to have problems with ptys!" .IX Subsection "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. .PP If your system is listed in the \*(L"verified\*(R" 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. .PP If your system is not listed, unpack the latest version of IO::Tty, do a 'perl Makefile.PL; make; make test; uname \f(CW\*(C`\-a\*(C'\fR' and send me the results and I'll see what I can deduce from that. .SS "I just want to read the output of a process without \fBexpect()\fPing anything. How can I do this?" .IX Subsection "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 \fBqx()\fR or open(\*(L"prog|\*(R")? ] .PP By using expect without any patterns to match. .PP .Vb 3 \& $process\->expect(undef); # Forever until EOF \& $process\->expect($timeout); # For a few seconds \& $process\->expect(0); # Is there anything ready on the handle now? .Ve .SS "Ok, so now how do I get what was read on the handle?" .IX Subsection "Ok, so now how do I get what was read on the handle?" .Vb 1 \& $read = $process\->before(); .Ve .SS "Where's IO::Pty?" .IX Subsection "Where's IO::Pty?" Find it on \s-1CPAN\s0 as IO-Tty, which provides both. .SS "How come when I automate the passwd program to change passwords for me passwd dies before changing the password sometimes/every time?" .IX Subsection "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 (\s-1SIGPIPE\s0?) telling it that \s-1STDOUT\s0 has gone away. The default behavior for processes is to die in this circumstance. Two ways you can make this not happen are: .PP .Vb 1 \& $process\->soft_close(); .Ve .PP This will wait 15 seconds for a process to come up with an \s-1EOF\s0 by itself before killing it. .PP .Vb 1 \& $process\->expect(undef); .Ve .PP This will wait forever for the process to match an empty set of patterns. It will return when the process hits an \s-1EOF.\s0 .PP As a rule, you should always \fBexpect()\fR the result of your transaction before you continue with processing. .SS "How come when I try to make a logfile with \fBlog_file()\fP or \fBset_group()\fP it doesn't print anything after the last time I run \fBexpect()\fP?" .IX Subsection "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 \fBexpect()\fR, \fBsend_slow()\fR and \fBinterconnect()\fR. One way you can force this is to make use of .PP .Vb 1 \& $process\->expect(undef); .Ve .PP and .PP .Vb 1 \& $process\->expect(0); .Ve .PP which will make \fBexpect()\fR run with an empty pattern set forever or just for an instant to capture the output of \f(CW$process\fR. The output is available in the accumulator, so you can grab it using \&\f(CW$process\fR\->\fBbefore()\fR. .SS "I seem to have problems with terminal settings, double echoing, etc." .IX Subsection "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 \f(CW$exp\fR\->\fBstty()\fR and \fBmanual_stty()\fR 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). .PP 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. .PP Note that IO::Tty returns ptys with your systems default setting regarding echoing, \s-1CRLF\s0 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 '\er' translation would not work anymore. On the other hand, a raw pty works much like a pipe and is more \s-1WYGIWYE\s0 (what you get is what you expect), so I suggest you set it to 'raw' by yourself: .PP .Vb 3 \& $exp = Expect\->new; \& $exp\->raw_pty(1); \& $exp\->spawn(...); .Ve .PP To disable echo: .PP .Vb 1 \& $exp\->slave\->stty(qw(\-echo)); .Ve .SS "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." .IX Subsection "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: .PP .Vb 3 \& my $exp = Expect\->new; \& $exp\->slave\->clone_winsize_from(\e*STDIN); \& $exp\->spawn("telnet somehost); .Ve .PP Also, some applications need the \s-1TERM\s0 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 \f(CW$ENV\fR{\s-1TERM\s0}. This is only a hand-waving explanation, please figure out the details by yourself. .SS "I set the terminal size as explained above, but if I resize the window, the application does not notice this." .IX Subsection "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 \s-1WINCH\s0 (\*(L"window size changed\*(R"), change the terminal size and propagate the signal to the spawned application: .PP .Vb 4 \& my $exp = Expect\->new; \& $exp\->slave\->clone_winsize_from(\e*STDIN); \& $exp\->spawn("ssh somehost); \& $SIG{WINCH} = \e&winch; \& \& sub winch { \& $exp\->slave\->clone_winsize_from(\e*STDIN); \& kill WINCH => $exp\->pid if $exp\->pid; \& $SIG{WINCH} = \e&winch; \& } \& \& $exp\->interact(); .Ve .PP 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 ssh-keygen). .SS "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?" .IX Subsection "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!] .ie n .SS "I get a ""Could not assign a pty"" error when running as a non-root user on an \s-1IRIX\s0 box?" .el .SS "I get a ``Could not assign a pty'' error when running as a non-root user on an \s-1IRIX\s0 box?" .IX Subsection "I get a Could not assign a pty error when running as a non-root user on an IRIX box?" The \s-1OS\s0 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. .SS "How come I don't notice when the spawned process closes its stdin/out/err??" .IX Subsection "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 \&\s-1EOF\s0 when the slave closes stdin/out/err. .PP One possible solution is when you spawn a process, follow it with a unique string that would indicate the process is finished. .PP .Vb 1 \& $process = Expect\->spawn(\*(Aqtelnet somehost; echo _\|_\|_\|_END_\|_\|_\|_\*(Aq); .Ve .PP And then \f(CW$process\fR\->expect($timeout,'_\|_\|_\|_END_\|_\|_\|_','other','patterns'); .SH "Source Examples" .IX Header "Source Examples" .SS "How to automate login" .IX Subsection "How to automate login" .Vb 3 \& my $telnet = Net::Telnet\->new("remotehost") # see Net::Telnet \& or die "Cannot telnet to remotehost: $!\en";; \& my $exp = Expect\->exp_init($telnet); \& \& # deprecated use of spawned telnet command \& # my $exp = Expect\->spawn("telnet localhost") \& # or die "Cannot spawn telnet: $!\en";; \& \& my $spawn_ok; \& $exp\->expect($timeout, \& [ \& qr\*(Aqlogin: $\*(Aq, \& sub { \& $spawn_ok = 1; \& my $fh = shift; \& $fh\->send("$username\en"); \& exp_continue; \& } \& ], \& [ \& \*(AqPassword: $\*(Aq, \& sub { \& my $fh = shift; \& print $fh "$password\en"; \& exp_continue; \& } \& ], \& [ \& eof => \& sub { \& if ($spawn_ok) { \& die "ERROR: premature EOF in login.\en"; \& } else { \& die "ERROR: could not spawn telnet.\en"; \& } \& } \& ], \& [ \& timeout => \& sub { \& die "No login.\en"; \& } \& ], \& \*(Aq\-re\*(Aq, qr\*(Aq[#>:] $\*(Aq, #\*(Aq wait for shell prompt, then exit expect \& ); .Ve .SS "How to expect on multiple spawned commands" .IX Subsection "How to expect on multiple spawned commands" .Vb 3 \& foreach my $cmd (@list_of_commands) { \& push @commands, Expect\->spawn($cmd); \& } \& \& expect($timeout, \& \*(Aq\-i\*(Aq, \e@commands, \& [ \& qr"pattern", # find this pattern in output of all commands \& sub { \& my $obj = shift; # object that matched \& print $obj "something\en"; \& exp_continue; # we don\*(Aqt want to terminate the expect call \& } \& ], \& \*(Aq\-i\*(Aq, $some_other_command, \& [ \& "some other pattern", \& sub { \& my ($obj, $parmref) = @_; \& # ... \& \& # now we exit the expect command \& }, \& \e$parm \& ], \& ); .Ve .SS "How to propagate terminal sizes" .IX Subsection "How to propagate terminal sizes" .Vb 4 \& my $exp = Expect\->new; \& $exp\->slave\->clone_winsize_from(\e*STDIN); \& $exp\->spawn("ssh somehost); \& $SIG{WINCH} = \e&winch; \& \& sub winch { \& $exp\->slave\->clone_winsize_from(\e*STDIN); \& kill WINCH => $exp\->pid if $exp\->pid; \& $SIG{WINCH} = \e&winch; \& } \& \& $exp\->interact(); .Ve .SH "HOMEPAGE" .IX Header "HOMEPAGE" though the source code is now in GitHub: .SH "MAILING LISTS" .IX Header "MAILING LISTS" There are two mailing lists available, expectperl-announce and expectperl-discuss, at .PP .Vb 1 \& http://lists.sourceforge.net/lists/listinfo/expectperl\-announce .Ve .PP and .PP .Vb 1 \& http://lists.sourceforge.net/lists/listinfo/expectperl\-discuss .Ve .SH "BUG TRACKING" .IX Header "BUG TRACKING" You can use the \s-1CPAN\s0 Request Tracker http://rt.cpan.org/ and submit new bugs under .PP .Vb 1 \& http://rt.cpan.org/Ticket/Create.html?Queue=Expect .Ve .SH "AUTHORS" .IX Header "AUTHORS" (c) 1997 Austin Schutz <\fIASchutz@users.sourceforge.net\fR> (retired) .PP \&\fBexpect()\fR interface & functionality enhancements (c) 1999\-2006 Roland Giersig. .PP This module is now maintained by Dave Jacoby <\fIjacoby@cpan.org\fR> .SH "LICENSE" .IX Header "LICENSE" This module can be used under the same terms as Perl. .SH "DISCLAIMER" .IX Header "DISCLAIMER" \&\s-1THIS SOFTWARE IS PROVIDED\s0 ``\s-1AS IS\s0'' \s-1AND 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\s0 (\s-1INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES\s0; \s-1LOSS OF USE, DATA, OR PROFITS\s0; \s-1OR BUSINESS INTERRUPTION\s0) \s-1HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\s0 (\s-1INCLUDING NEGLIGENCE OR OTHERWISE\s0) \s-1ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\s0 .PP In other words: Use at your own risk. Provided as is. Your mileage may vary. Read the source, Luke! .PP And finally, just to be sure: .PP 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. PK!E4nnman/man3/HTTP::Tiny.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "HTTP::Tiny 3" .TH HTTP::Tiny 3 "2023-07-11" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" HTTP::Tiny \- A small, simple, correct HTTP/1.1 client .SH "VERSION" .IX Header "VERSION" version 0.088 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use HTTP::Tiny; \& \& my $response = HTTP::Tiny\->new\->get(\*(Aqhttp://example.com/\*(Aq); \& \& die "Failed!\en" unless $response\->{success}; \& \& print "$response\->{status} $response\->{reason}\en"; \& \& while (my ($k, $v) = each %{$response\->{headers}}) { \& for (ref $v eq \*(AqARRAY\*(Aq ? @$v : $v) { \& print "$k: $_\en"; \& } \& } \& \& print $response\->{content} if length $response\->{content}; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This is a very simple \s-1HTTP/1.1\s0 client, designed for doing simple requests without the overhead of a large framework like LWP::UserAgent. .PP It is more correct and more complete than HTTP::Lite. It supports proxies and redirection. It also correctly resumes after \s-1EINTR.\s0 .PP If IO::Socket::IP 0.25 or later is installed, HTTP::Tiny will use it instead of IO::Socket::INET for transparent support for both IPv4 and IPv6. .PP Cookie support requires HTTP::CookieJar or an equivalent class. .SH "METHODS" .IX Header "METHODS" .SS "new" .IX Subsection "new" .Vb 1 \& $http = HTTP::Tiny\->new( %attributes ); .Ve .PP This constructor returns a new HTTP::Tiny object. Valid attributes include: .IP "\(bu" 4 \&\f(CW\*(C`agent\*(C'\fR — A user-agent string (defaults to 'HTTP\-Tiny/$VERSION'). If \f(CW\*(C`agent\*(C'\fR — ends in a space character, the default user-agent string is appended. .IP "\(bu" 4 \&\f(CW\*(C`cookie_jar\*(C'\fR — An instance of HTTP::CookieJar — or equivalent class that supports the \f(CW\*(C`add\*(C'\fR and \f(CW\*(C`cookie_header\*(C'\fR methods .IP "\(bu" 4 \&\f(CW\*(C`default_headers\*(C'\fR — A hashref of default headers to apply to requests .IP "\(bu" 4 \&\f(CW\*(C`local_address\*(C'\fR — The local \s-1IP\s0 address to bind to .IP "\(bu" 4 \&\f(CW\*(C`keep_alive\*(C'\fR — Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1) .IP "\(bu" 4 \&\f(CW\*(C`max_redirect\*(C'\fR — Maximum number of redirects allowed (defaults to 5) .IP "\(bu" 4 \&\f(CW\*(C`max_size\*(C'\fR — 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. .IP "\(bu" 4 \&\f(CW\*(C`http_proxy\*(C'\fR — \s-1URL\s0 of a proxy server to use for \s-1HTTP\s0 connections (default is \f(CW$ENV{http_proxy}\fR — if set) .IP "\(bu" 4 \&\f(CW\*(C`https_proxy\*(C'\fR — \s-1URL\s0 of a proxy server to use for \s-1HTTPS\s0 connections (default is \f(CW$ENV{https_proxy}\fR — if set) .IP "\(bu" 4 \&\f(CW\*(C`proxy\*(C'\fR — \s-1URL\s0 of a generic proxy server for both \s-1HTTP\s0 and \s-1HTTPS\s0 connections (default is \f(CW$ENV{all_proxy}\fR — if set) .IP "\(bu" 4 \&\f(CW\*(C`no_proxy\*(C'\fR — List of domain suffixes that should not be proxied. Must be a comma-separated string or an array reference. (default is \f(CW$ENV{no_proxy}\fR —) .IP "\(bu" 4 \&\f(CW\*(C`timeout\*(C'\fR — 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. .IP "\(bu" 4 \&\f(CW\*(C`verify_SSL\*(C'\fR — A boolean that indicates whether to validate the \s-1TLS/SSL\s0 certificate of an \f(CW\*(C`https\*(C'\fR — connection (default is true). Changed from false to true in version 0.083. .IP "\(bu" 4 \&\f(CW\*(C`SSL_options\*(C'\fR — A hashref of \f(CW\*(C`SSL_*\*(C'\fR — options to pass through to IO::Socket::SSL .IP "\(bu" 4 \&\f(CW$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}\fR \- Changes the default certificate verification behavior to not check server identity if set to 1. Only effective if \f(CW\*(C`verify_SSL\*(C'\fR is not set. Added in version 0.083. .PP An accessor/mutator method exists for each attribute. .PP Passing an explicit \f(CW\*(C`undef\*(C'\fR for \f(CW\*(C`proxy\*(C'\fR, \f(CW\*(C`http_proxy\*(C'\fR or \f(CW\*(C`https_proxy\*(C'\fR will prevent getting the corresponding proxies from the environment. .PP Errors during request execution will result in a pseudo-HTTP status code of 599 and a reason of \*(L"Internal Exception\*(R". The content field in the response will contain the text of the error. .PP The \f(CW\*(C`keep_alive\*(C'\fR 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 \s-1ID\s0 or thread \s-1ID\s0 change, the persistent connection will be dropped. If you want persistent connections across multiple destinations, use multiple HTTP::Tiny objects. .PP See \*(L"\s-1SSL SUPPORT\*(R"\s0 for more on the \f(CW\*(C`verify_SSL\*(C'\fR and \f(CW\*(C`SSL_options\*(C'\fR attributes. .SS "get|head|put|post|patch|delete" .IX Subsection "get|head|put|post|patch|delete" .Vb 3 \& $response = $http\->get($url); \& $response = $http\->get($url, \e%options); \& $response = $http\->head($url); .Ve .PP These methods are shorthand for calling \f(CW\*(C`request()\*(C'\fR for the given method. The \&\s-1URL\s0 must have unsafe characters escaped and international domain names encoded. See \f(CW\*(C`request()\*(C'\fR for valid options and a description of the response. .PP The \f(CW\*(C`success\*(C'\fR field of the response will be true if the status code is 2XX. .SS "post_form" .IX Subsection "post_form" .Vb 2 \& $response = $http\->post_form($url, $form_data); \& $response = $http\->post_form($url, $form_data, \e%options); .Ve .PP This method executes a \f(CW\*(C`POST\*(C'\fR request and sends the key/value pairs from a form data hash or array reference to the given \s-1URL\s0 with a \f(CW\*(C`content\-type\*(C'\fR of \&\f(CW\*(C`application/x\-www\-form\-urlencoded\*(C'\fR. 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 \&\f(CW\*(C`www_form_urlencode\*(C'\fR method for details on the encoding. .PP The \s-1URL\s0 must have unsafe characters escaped and international domain names encoded. See \f(CW\*(C`request()\*(C'\fR for valid options and a description of the response. Any \f(CW\*(C`content\-type\*(C'\fR header or content in the options hashref will be ignored. .PP The \f(CW\*(C`success\*(C'\fR field of the response will be true if the status code is 2XX. .SS "mirror" .IX Subsection "mirror" .Vb 4 \& $response = $http\->mirror($url, $file, \e%options) \& if ( $response\->{success} ) { \& print "$file is up to date\en"; \& } .Ve .PP Executes a \f(CW\*(C`GET\*(C'\fR request for the \s-1URL\s0 and saves the response body to the file name provided. The \s-1URL\s0 must have unsafe characters escaped and international domain names encoded. If the file already exists, the request will include an \&\f(CW\*(C`If\-Modified\-Since\*(C'\fR header with the modification timestamp of the file. You may specify a different \f(CW\*(C`If\-Modified\-Since\*(C'\fR header yourself in the \f(CW\*(C`$options\->{headers}\*(C'\fR hash. .PP The \f(CW\*(C`success\*(C'\fR field of the response will be true if the status code is 2XX or if the status code is 304 (unmodified). .PP If the file was modified and the server response includes a properly formatted \f(CW\*(C`Last\-Modified\*(C'\fR header, the file modification time will be updated accordingly. .SS "request" .IX Subsection "request" .Vb 2 \& $response = $http\->request($method, $url); \& $response = $http\->request($method, $url, \e%options); .Ve .PP Executes an \s-1HTTP\s0 request of the given method type ('\s-1GET\s0', '\s-1HEAD\s0', '\s-1POST\s0', \&'\s-1PUT\s0', etc.) on the given \s-1URL.\s0 The \s-1URL\s0 must have unsafe characters escaped and international domain names encoded. .PP \&\fB\s-1NOTE\s0\fR: Method names are \fBcase-sensitive\fR per the \s-1HTTP/1.1\s0 specification. Don't use \f(CW\*(C`get\*(C'\fR when you really want \f(CW\*(C`GET\*(C'\fR. See \s-1LIMITATIONS\s0 for how this applies to redirection. .PP If the \s-1URL\s0 includes a \*(L"user:password\*(R" stanza, they will be used for Basic-style authorization headers. (Authorization headers will not be included in a redirected request.) For example: .PP .Vb 1 \& $http\->request(\*(AqGET\*(Aq, \*(Aqhttp://Aladdin:open sesame@example.com/\*(Aq); .Ve .PP If the \*(L"user:password\*(R" stanza contains reserved characters, they must be percent-escaped: .PP .Vb 1 \& $http\->request(\*(AqGET\*(Aq, \*(Aqhttp://john%40example.com:password@example.com/\*(Aq); .Ve .PP A hashref of options may be appended to modify the request. .PP Valid options are: .IP "\(bu" 4 \&\f(CW\*(C`headers\*(C'\fR — 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. .IP "\(bu" 4 \&\f(CW\*(C`content\*(C'\fR — A scalar to include as the body of the request \s-1OR\s0 a code reference that will be called iteratively to produce the body of the request .IP "\(bu" 4 \&\f(CW\*(C`trailer_callback\*(C'\fR — A code reference that will be called if it exists to provide a hashref of trailing headers (only used with chunked transfer-encoding) .IP "\(bu" 4 \&\f(CW\*(C`data_callback\*(C'\fR — A code reference that will be called for each chunks of the response body received. .IP "\(bu" 4 \&\f(CW\*(C`peer\*(C'\fR — Override host resolution and force all connections to go only to a specific peer address, regardless of the \s-1URL\s0 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. .PP The \f(CW\*(C`Host\*(C'\fR header is generated from the \s-1URL\s0 in accordance with \s-1RFC 2616.\s0 It is a fatal error to specify \f(CW\*(C`Host\*(C'\fR in the \f(CW\*(C`headers\*(C'\fR option. Other headers may be ignored or overwritten if necessary for transport compliance. .PP If the \f(CW\*(C`content\*(C'\fR 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. .PP If the \f(CW\*(C`content\*(C'\fR option is the empty string, no \f(CW\*(C`content\-type\*(C'\fR or \&\f(CW\*(C`content\-length\*(C'\fR headers will be generated. .PP If the \f(CW\*(C`data_callback\*(C'\fR 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 \f(CW\*(C`status\*(C'\fR or \f(CW\*(C`headers\*(C'\fR received prior to the content body.) .PP Content data in the request/response is handled as \*(L"raw bytes\*(R". Any encoding/decoding (with associated headers) are the responsibility of the caller. .PP The \f(CW\*(C`request\*(C'\fR method returns a hashref containing the response. The hashref will have the following keys: .IP "\(bu" 4 \&\f(CW\*(C`success\*(C'\fR — Boolean indicating whether the operation returned a 2XX status code .IP "\(bu" 4 \&\f(CW\*(C`url\*(C'\fR — \s-1URL\s0 that provided the response. This is the \s-1URL\s0 of the request unless there were redirections, in which case it is the last \s-1URL\s0 queried in a redirection chain .IP "\(bu" 4 \&\f(CW\*(C`status\*(C'\fR — The \s-1HTTP\s0 status code of the response .IP "\(bu" 4 \&\f(CW\*(C`reason\*(C'\fR — The response phrase returned by the server .IP "\(bu" 4 \&\f(CW\*(C`content\*(C'\fR — 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 .IP "\(bu" 4 \&\f(CW\*(C`headers\*(C'\fR — 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 .IP "\(bu" 4 \&\f(CW\*(C`protocol\*(C'\fR \- If this field exists, it is the protocol of the response such as \s-1HTTP/1.0\s0 or \s-1HTTP/1.1\s0 .IP "\(bu" 4 \&\f(CW\*(C`redirects\*(C'\fR 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. .PP On an error during the execution of the request, the \f(CW\*(C`status\*(C'\fR field will contain 599, and the \f(CW\*(C`content\*(C'\fR field will contain the text of the error. .SS "www_form_urlencode" .IX Subsection "www_form_urlencode" .Vb 2 \& $params = $http\->www_form_urlencode( $data ); \& $response = $http\->get("http://example.com/query?$params"); .Ve .PP This method converts the key/value pairs from a data hash or array reference into a \f(CW\*(C`x\-www\-form\-urlencoded\*(C'\fR string. The keys and values from the data reference will be \s-1UTF\-8\s0 encoded and escaped per \s-1RFC 3986.\s0 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. .SS "can_ssl" .IX Subsection "can_ssl" .Vb 3 \& $ok = HTTP::Tiny\->can_ssl; \& ($ok, $why) = HTTP::Tiny\->can_ssl; \& ($ok, $why) = $http\->can_ssl; .Ve .PP Indicates if \s-1SSL\s0 support is available. When called as a class object, it checks for the correct version of Net::SSLeay and IO::Socket::SSL. When called as an object methods, if \f(CW\*(C`SSL_verify\*(C'\fR is true or if \f(CW\*(C`SSL_verify_mode\*(C'\fR is set in \f(CW\*(C`SSL_options\*(C'\fR, it checks that a \s-1CA\s0 file is available. .PP In scalar context, returns a boolean indicating if \s-1SSL\s0 is available. In list context, returns the boolean and a (possibly multi-line) string of errors indicating why \s-1SSL\s0 isn't available. .SS "connected" .IX Subsection "connected" .Vb 2 \& $host = $http\->connected; \& ($host, $port) = $http\->connected; .Ve .PP Indicates if a connection to a peer is being kept alive, per the \f(CW\*(C`keep_alive\*(C'\fR option. .PP In scalar context, returns the peer host and port, joined with a colon, or \&\f(CW\*(C`undef\*(C'\fR (if no peer is connected). In list context, returns the peer host and port or an empty list (if no peer is connected). .PP \&\fBNote\fR: This method cannot reliably be used to discover whether the remote host has closed its end of the socket. .SH "TLS/SSL SUPPORT" .IX Header "TLS/SSL SUPPORT" Direct \f(CW\*(C`https\*(C'\fR connections are supported only if IO::Socket::SSL 1.56 or greater and Net::SSLeay 1.49 or greater are installed. An error will occur if new enough versions of these modules are not installed or if the \s-1TLS\s0 encryption fails. You can also use \f(CW\*(C`HTTP::Tiny::can_ssl()\*(C'\fR utility function that returns boolean to see if the required modules are installed. .PP An \f(CW\*(C`https\*(C'\fR connection may be made via an \f(CW\*(C`http\*(C'\fR proxy that supports the \s-1CONNECT\s0 command (i.e. \s-1RFC 2817\s0). You may not proxy \f(CW\*(C`https\*(C'\fR via a proxy that itself requires \f(CW\*(C`https\*(C'\fR to communicate. .PP \&\s-1TLS/SSL\s0 provides two distinct capabilities: .IP "\(bu" 4 Encrypted communication channel .IP "\(bu" 4 Verification of server identity .PP \&\fBBy default, HTTP::Tiny verifies server identity\fR. .PP This was changed in version 0.083 due to security concerns. The previous default behavior can be enabled by setting \f(CW$ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT}\fR to 1. .PP Verification is done by checking that that the \s-1TLS/SSL\s0 connection has a valid certificate corresponding to the host name of the connection and that the certificate has been verified by a \s-1CA.\s0 Assuming you trust the \s-1CA,\s0 this will protect against machine-in-the-middle attacks . .PP Certificate verification requires a file containing trusted \s-1CA\s0 certificates. .PP If the environment variable \f(CW\*(C`SSL_CERT_FILE\*(C'\fR is present, HTTP::Tiny will try to find a \s-1CA\s0 certificate file in that location. .PP If the Mozilla::CA module is installed, HTTP::Tiny will use the \s-1CA\s0 file included with it as a source of trusted \s-1CA\s0's. .PP If that module is not available, then HTTP::Tiny will search several system-specific default locations for a \s-1CA\s0 certificate file: .IP "\(bu" 4 /etc/ssl/certs/ca\-certificates.crt .IP "\(bu" 4 /etc/pki/tls/certs/ca\-bundle.crt .IP "\(bu" 4 /etc/ssl/ca\-bundle.pem .IP "\(bu" 4 /etc/openssl/certs/ca\-certificates.crt .IP "\(bu" 4 /etc/ssl/cert.pem .IP "\(bu" 4 /usr/local/share/certs/ca\-root\-nss.crt .IP "\(bu" 4 /etc/pki/tls/cacert.pem .IP "\(bu" 4 /etc/certs/ca\-certificates.crt .PP An error will be occur if \f(CW\*(C`verify_SSL\*(C'\fR is true and no \s-1CA\s0 certificate file is available. .PP If you desire complete control over \s-1TLS/SSL\s0 connections, the \f(CW\*(C`SSL_options\*(C'\fR attribute lets you provide a hash reference that will be passed through to \&\f(CW\*(C`IO::Socket::SSL::start_SSL()\*(C'\fR, overriding any options set by HTTP::Tiny. For example, to provide your own trusted \s-1CA\s0 file: .PP .Vb 3 \& SSL_options => { \& SSL_ca_file => $file_path, \& } .Ve .PP The \f(CW\*(C`SSL_options\*(C'\fR 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 \s-1TLS/SSL\s0 connection. See IO::Socket::SSL documentation for details. .SH "PROXY SUPPORT" .IX Header "PROXY SUPPORT" HTTP::Tiny can proxy both \f(CW\*(C`http\*(C'\fR and \f(CW\*(C`https\*(C'\fR requests. Only Basic proxy authorization is supported and it must be provided as part of the proxy \s-1URL:\s0 \&\f(CW\*(C`http://user:pass@proxy.example.com/\*(C'\fR. .PP HTTP::Tiny supports the following proxy environment variables: .IP "\(bu" 4 http_proxy or \s-1HTTP_PROXY\s0 .IP "\(bu" 4 https_proxy or \s-1HTTPS_PROXY\s0 .IP "\(bu" 4 all_proxy or \s-1ALL_PROXY\s0 .PP If the \f(CW\*(C`REQUEST_METHOD\*(C'\fR environment variable is set, then this might be a \s-1CGI\s0 process and \f(CW\*(C`HTTP_PROXY\*(C'\fR would be set from the \f(CW\*(C`Proxy:\*(C'\fR header, which is a security risk. If \f(CW\*(C`REQUEST_METHOD\*(C'\fR is set, \f(CW\*(C`HTTP_PROXY\*(C'\fR (the upper case variant only) is ignored, but \f(CW\*(C`CGI_HTTP_PROXY\*(C'\fR is considered instead. .PP Tunnelling \f(CW\*(C`https\*(C'\fR over an \f(CW\*(C`http\*(C'\fR proxy using the \s-1CONNECT\s0 method is supported. If your proxy uses \f(CW\*(C`https\*(C'\fR itself, you can not tunnel \f(CW\*(C`https\*(C'\fR over it. .PP Be warned that proxying an \f(CW\*(C`https\*(C'\fR connection opens you to the risk of a man-in-the-middle attack by the proxy server. .PP The \f(CW\*(C`no_proxy\*(C'\fR environment variable is supported in the format of a comma-separated list of domain extensions proxy should not be used for. .PP Proxy arguments passed to \f(CW\*(C`new\*(C'\fR will override their corresponding environment variables. .SH "LIMITATIONS" .IX Header "LIMITATIONS" HTTP::Tiny is \fIconditionally compliant\fR with the \&\s-1HTTP/1.1\s0 specifications : .IP "\(bu" 4 \&\*(L"Message Syntax and Routing\*(R" [\s-1RFC7230\s0] .IP "\(bu" 4 \&\*(L"Semantics and Content\*(R" [\s-1RFC7231\s0] .IP "\(bu" 4 \&\*(L"Conditional Requests\*(R" [\s-1RFC7232\s0] .IP "\(bu" 4 \&\*(L"Range Requests\*(R" [\s-1RFC7233\s0] .IP "\(bu" 4 \&\*(L"Caching\*(R" [\s-1RFC7234\s0] .IP "\(bu" 4 \&\*(L"Authentication\*(R" [\s-1RFC7235\s0] .PP It attempts to meet all \*(L"\s-1MUST\*(R"\s0 requirements of the specification, but does not implement all \*(L"\s-1SHOULD\*(R"\s0 requirements. (Note: it was developed against the earlier \s-1RFC 2616\s0 specification and may not yet meet the revised \s-1RFC 7230\-7235\s0 spec.) Additionally, HTTP::Tiny supports the \f(CW\*(C`PATCH\*(C'\fR method of \s-1RFC 5789.\s0 .PP Some particular limitations of note include: .IP "\(bu" 4 HTTP::Tiny focuses on correct transport. Users are responsible for ensuring that user-defined headers and content are compliant with the \s-1HTTP/1.1\s0 specification. .IP "\(bu" 4 Users must ensure that URLs are properly escaped for unsafe characters and that international domain names are properly encoded to \s-1ASCII.\s0 See URI::Escape, URI::_punycode and Net::IDN::Encode. .IP "\(bu" 4 Redirection is very strict against the specification. Redirection is only automatic for response codes 301, 302, 307 and 308 if the request method is \&'\s-1GET\s0' or '\s-1HEAD\s0'. Response code 303 is always converted into a '\s-1GET\s0' redirection, as mandated by the specification. There is no automatic support for status 305 (\*(L"Use proxy\*(R") redirections. .IP "\(bu" 4 There is no provision for delaying a request body using an \f(CW\*(C`Expect\*(C'\fR header. Unexpected \f(CW\*(C`1XX\*(C'\fR responses are silently ignored as per the specification. .IP "\(bu" 4 Only 'chunked' \f(CW\*(C`Transfer\-Encoding\*(C'\fR is supported. .IP "\(bu" 4 There is no support for a Request-URI of '*' for the '\s-1OPTIONS\s0' request. .IP "\(bu" 4 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. .PP Despite the limitations listed above, HTTP::Tiny is considered feature-complete. New feature requests should be directed to HTTP::Tiny::UA. .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "\(bu" 4 HTTP::Tiny::UA \- Higher level \s-1UA\s0 features for HTTP::Tiny .IP "\(bu" 4 HTTP::Thin \- HTTP::Tiny wrapper with HTTP::Request/HTTP::Response compatibility .IP "\(bu" 4 HTTP::Tiny::Mech \- Wrap WWW::Mechanize instance in HTTP::Tiny compatible interface .IP "\(bu" 4 IO::Socket::IP \- Required for IPv6 support .IP "\(bu" 4 IO::Socket::SSL \- Required for \s-1SSL\s0 support .IP "\(bu" 4 LWP::UserAgent \- If HTTP::Tiny isn't enough for you, this is the \*(L"standard\*(R" way to do things .IP "\(bu" 4 Mozilla::CA \- Required if you want to validate \s-1SSL\s0 certificates .IP "\(bu" 4 Net::SSLeay \- Required for \s-1SSL\s0 support .SH "SUPPORT" .IX Header "SUPPORT" .SS "Bugs / Feature Requests" .IX Subsection "Bugs / Feature Requests" Please report any bugs or feature requests through the issue tracker at . You will be notified automatically of any progress on your issue. .SS "Source Code" .IX Subsection "Source Code" This is open source software. The code repository is available for public review and contribution under the terms of the license. .PP .PP .Vb 1 \& git clone https://github.com/Perl\-Toolchain\-Gang/HTTP\-Tiny.git .Ve .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 Christian Hansen .IP "\(bu" 4 David Golden .SH "CONTRIBUTORS" .IX Header "CONTRIBUTORS" .IP "\(bu" 4 Alan Gardner .IP "\(bu" 4 Alessandro Ghedini .IP "\(bu" 4 A. Sinan Unur .IP "\(bu" 4 Brad Gilbert .IP "\(bu" 4 brian m. carlson .IP "\(bu" 4 Chris Nehren .IP "\(bu" 4 Chris Weyl .IP "\(bu" 4 Claes Jakobsson .IP "\(bu" 4 Clinton Gormley .IP "\(bu" 4 Craig A. Berry .IP "\(bu" 4 Craig Berry .IP "\(bu" 4 David Golden .IP "\(bu" 4 David Mitchell .IP "\(bu" 4 Dean Pearce .IP "\(bu" 4 Edward Zborowski .IP "\(bu" 4 Felipe Gasper .IP "\(bu" 4 Graham Knop .IP "\(bu" 4 Greg Kennedy .IP "\(bu" 4 James E Keenan .IP "\(bu" 4 James Raspass .IP "\(bu" 4 Jeremy Mates .IP "\(bu" 4 Jess Robinson .IP "\(bu" 4 Karen Etheridge .IP "\(bu" 4 Lukas Eklund .IP "\(bu" 4 Martin J. Evans .IP "\(bu" 4 Martin-Louis Bright .IP "\(bu" 4 Matthew Horsfall .IP "\(bu" 4 Michael R. Davis .IP "\(bu" 4 Mike Doherty .IP "\(bu" 4 Nicolas Rochelemagne .IP "\(bu" 4 Olaf Alders .IP "\(bu" 4 Olivier Mengué .IP "\(bu" 4 Petr Písař .IP "\(bu" 4 sanjay-cpu .IP "\(bu" 4 Serguei Trouchelle .IP "\(bu" 4 Shoichi Kaji .IP "\(bu" 4 SkyMarshal .IP "\(bu" 4 Sören Kornetzki .IP "\(bu" 4 Steve Grazzini .IP "\(bu" 4 Stig Palmquist .IP "\(bu" 4 Syohei \s-1YOSHIDA\s0 .IP "\(bu" 4 Tatsuhiko Miyagawa .IP "\(bu" 4 Tom Hukins .IP "\(bu" 4 Tony Cook .IP "\(bu" 4 Xavier Guimard .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2023 by Christian Hansen. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. PK!/LLman/man3/Canary::Stability.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Stability 3" .TH Stability 3 "2019-04-22" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Canary::Stability \- canary to check perl compatibility for schmorp's modules .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& # in Makefile.PL \& use Canary::Stability DISTNAME => 2001, MINIMUM_PERL_VERSION; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module is used by Schmorp's modules during configuration stage to test the installed perl for compatibility with his modules. .PP 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. .PP See the \fIMakefile.PL\fR in Coro or AnyEvent for usage examples. .SH "ENVIRONMENT VARIABLES" .IX Header "ENVIRONMENT VARIABLES" .ie n .IP """PERL_CANARY_STABILITY_NOPROMPT=1""" 4 .el .IP "\f(CWPERL_CANARY_STABILITY_NOPROMPT=1\fR" 4 .IX Item "PERL_CANARY_STABILITY_NOPROMPT=1" Do not prompt the user on alert messages. .ie n .IP """PERL_CANARY_STABILITY_COLOUR=0""" 4 .el .IP "\f(CWPERL_CANARY_STABILITY_COLOUR=0\fR" 4 .IX Item "PERL_CANARY_STABILITY_COLOUR=0" Disable use of colour. .ie n .IP """PERL_CANARY_STABILITY_COLOUR=1""" 4 .el .IP "\f(CWPERL_CANARY_STABILITY_COLOUR=1\fR" 4 .IX Item "PERL_CANARY_STABILITY_COLOUR=1" Force use of colour. .ie n .IP """PERL_CANARY_STABILITY_DISABLE=1""" 4 .el .IP "\f(CWPERL_CANARY_STABILITY_DISABLE=1\fR" 4 .IX Item "PERL_CANARY_STABILITY_DISABLE=1" Disable this modules functionality completely. .ie n .IP """AUTOMATED_TESTING=1""" 4 .el .IP "\f(CWAUTOMATED_TESTING=1\fR" 4 .IX Item "AUTOMATED_TESTING=1" 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. .Sp 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. .SH "AUTHOR" .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://software.schmorp.de/pkg/Canary\-Stability.html .Ve PK!man/man3/common::sense.3pmnu6$PK!O..man/man3/Types::Serialiser.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Serialiser 3" .TH Serialiser 3 "2020-12-01" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Types::Serialiser \- simple data types for common serialisation formats .SH "SYNOPSIS" .IX Header "SYNOPSIS" .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module provides some extra datatypes that are used by common serialisation formats such as \s-1JSON\s0 or \s-1CBOR.\s0 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. .SH "SIMPLE SCALAR CONSTANTS" .IX Header "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. .PP In the following, functions with zero or one arguments have a prototype of \&\f(CW\*(C`()\*(C'\fR and \f(CW\*(C`($)\*(C'\fR, respectively, so act as constants and unary operators. .SS "\s-1BOOLEANS\s0 (Types::Serialiser::Boolean class)" .IX Subsection "BOOLEANS (Types::Serialiser::Boolean class)" This type has only two instances, true and false. A natural representation for these in Perl is \f(CW1\fR and \f(CW0\fR, but serialisation formats need to be able to differentiate between them and mere numbers. .ie n .IP "$Types::Serialiser::true, Types::Serialiser::true" 4 .el .IP "\f(CW$Types::Serialiser::true\fR, Types::Serialiser::true" 4 .IX Item "$Types::Serialiser::true, Types::Serialiser::true" This value represents the \*(L"true\*(R" value. In most contexts is acts like the number \f(CW1\fR. It is up to you whether you use the variable form (\f(CW$Types::Serialiser::true\fR) or the constant form (\f(CW\*(C`Types::Serialiser::true\*(C'\fR). .Sp The constant is represented as a reference to a scalar containing \f(CW1\fR \- implementations are allowed to directly test for this. .ie n .IP "$Types::Serialiser::false, Types::Serialiser::false" 4 .el .IP "\f(CW$Types::Serialiser::false\fR, Types::Serialiser::false" 4 .IX Item "$Types::Serialiser::false, Types::Serialiser::false" This value represents the \*(L"false\*(R" value. In most contexts is acts like the number \f(CW0\fR. It is up to you whether you use the variable form (\f(CW$Types::Serialiser::false\fR) or the constant form (\f(CW\*(C`Types::Serialiser::false\*(C'\fR). .Sp The constant is represented as a reference to a scalar containing \f(CW0\fR \- implementations are allowed to directly test for this. .ie n .IP "Types::Serialiser::as_bool $value" 4 .el .IP "Types::Serialiser::as_bool \f(CW$value\fR" 4 .IX Item "Types::Serialiser::as_bool $value" Converts a Perl scalar into a boolean, which is useful syntactic sugar. Strictly equivalent to: .Sp .Vb 1 \& $value ? $Types::Serialiser::true : $Types::Serialiser::false .Ve .ie n .IP "$is_bool = Types::Serialiser::is_bool $value" 4 .el .IP "\f(CW$is_bool\fR = Types::Serialiser::is_bool \f(CW$value\fR" 4 .IX Item "$is_bool = Types::Serialiser::is_bool $value" Returns true iff the \f(CW$value\fR is either \f(CW$Types::Serialiser::true\fR or \&\f(CW$Types::Serialiser::false\fR. .Sp For example, you could differentiate between a perl true value and a \&\f(CW\*(C`Types::Serialiser::true\*(C'\fR by using this: .Sp .Vb 1 \& $value && Types::Serialiser::is_bool $value .Ve .ie n .IP "$is_true = Types::Serialiser::is_true $value" 4 .el .IP "\f(CW$is_true\fR = Types::Serialiser::is_true \f(CW$value\fR" 4 .IX Item "$is_true = Types::Serialiser::is_true $value" Returns true iff \f(CW$value\fR is \f(CW$Types::Serialiser::true\fR. .ie n .IP "$is_false = Types::Serialiser::is_false $value" 4 .el .IP "\f(CW$is_false\fR = Types::Serialiser::is_false \f(CW$value\fR" 4 .IX Item "$is_false = Types::Serialiser::is_false $value" Returns false iff \f(CW$value\fR is \f(CW$Types::Serialiser::false\fR. .SS "\s-1ERROR\s0 (Types::Serialiser::Error class)" .IX Subsection "ERROR (Types::Serialiser::Error class)" This class has only a single instance, \f(CW\*(C`error\*(C'\fR. It is used to signal an encoding or decoding error. In \s-1CBOR\s0 for example, and object that couldn't be encoded will be represented by a \s-1CBOR\s0 undefined value, which is represented by the error value in Perl. .ie n .IP "$Types::Serialiser::error, Types::Serialiser::error" 4 .el .IP "\f(CW$Types::Serialiser::error\fR, Types::Serialiser::error" 4 .IX Item "$Types::Serialiser::error, Types::Serialiser::error" This value represents the \*(L"error\*(R" value. Accessing values of this type will throw an exception. .Sp The constant is represented as a reference to a scalar containing \f(CW\*(C`undef\*(C'\fR \&\- implementations are allowed to directly test for this. .ie n .IP "$is_error = Types::Serialiser::is_error $value" 4 .el .IP "\f(CW$is_error\fR = Types::Serialiser::is_error \f(CW$value\fR" 4 .IX Item "$is_error = Types::Serialiser::is_error $value" Returns false iff \f(CW$value\fR is \f(CW$Types::Serialiser::error\fR. .SH "NOTES FOR XS USERS" .IX Header "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 \f(CW\*(C`Types::Serialiser::Boolean\*(C'\fR or \&\f(CW\*(C`Types::Serialiser::Error\*(C'\fR stash, and then follow the scalar reference to see if it's \f(CW1\fR (true), \f(CW0\fR (false) or \f(CW\*(C`undef\*(C'\fR (error). .PP While it is possible to use an isa test, directly comparing stash pointers is faster and guaranteed to work. .PP For historical reasons, the \f(CW\*(C`Types::Serialiser::Boolean\*(C'\fR stash is just an alias for \f(CW\*(C`JSON::PP::Boolean\*(C'\fR. When printed, the classname with usually be \f(CW\*(C`JSON::PP::Boolean\*(C'\fR, but isa tests and stash pointer comparison will normally work correctly (i.e. Types::Serialiser::true \s-1ISA\s0 JSON::PP::Boolean, but also \s-1ISA\s0 Types::Serialiser::Boolean). .SH "A GENERIC OBJECT SERIALIATION PROTOCOL" .IX Header "A GENERIC OBJECT SERIALIATION PROTOCOL" This section explains the object serialisation protocol used by \&\s-1CBOR::XS\s0. It is meant to be generic enough to support any kind of generic object serialiser. .PP This protocol is called \*(L"the Types::Serialiser object serialisation protocol\*(R". .SS "\s-1ENCODING\s0" .IX Subsection "ENCODING" When the encoder encounters an object that it cannot otherwise encode (for example, \s-1CBOR::XS\s0 can encode a few special types itself, and will first attempt to use the special \f(CW\*(C`TO_CBOR\*(C'\fR serialisation protocol), it will look up the \f(CW\*(C`FREEZE\*(C'\fR method on the object. .PP Note that the \f(CW\*(C`FREEZE\*(C'\fR method will normally be called \fIduring\fR encoding, and \fI\s-1MUST NOT\s0\fR change the data structure that is being encoded in any way, or it might cause memory corruption or worse. .PP 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 \s-1CBOR::XS\s0 uses \f(CW\*(C`CBOR\*(C'\fR, and the \s-1JSON\s0 and \s-1JSON::XS\s0 modules (or any other \s-1JSON\s0 serialiser), would use \f(CW\*(C`JSON\*(C'\fR as second argument. .PP The \f(CW\*(C`FREEZE\*(C'\fR 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 \s-1CBOR\s0 for example, there is a registered tag number for encoded perl objects. .PP The values that \f(CW\*(C`FREEZE\*(C'\fR 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 \&\s-1JSON\s0 data model). You can always use a more complex format for a specific data model by checking the second argument, the data model. .PP The \*(L"data model\*(R" is not the same as the \*(L"data format\*(R" \- the data model indicates what types and kinds of return values can be returned from \&\f(CW\*(C`FREEZE\*(C'\fR. For example, in \f(CW\*(C`CBOR\*(C'\fR it is permissible to return tagged \s-1CBOR\s0 values, while \s-1JSON\s0 does not support these at all, so \f(CW\*(C`JSON\*(C'\fR would be a valid (but too limited) data model name for \f(CW\*(C`CBOR::XS\*(C'\fR. similarly, a serialising format that supports more or less the same data model as \s-1JSON\s0 could use \f(CW\*(C`JSON\*(C'\fR as data model without losing anything. .SS "\s-1DECODING\s0" .IX Subsection "DECODING" When the decoder then encounters such an encoded perl object, it should look up the \f(CW\*(C`THAW\*(C'\fR 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 \f(CW\*(C`FREEZE\*(C'\fR. .SS "\s-1EXAMPLES\s0" .IX Subsection "EXAMPLES" See the \f(CW\*(C`OBJECT SERIALISATION\*(C'\fR section in the \s-1CBOR::XS\s0 manpage for more details, an example implementation, and code examples. .PP Here is an example \f(CW\*(C`FREEZE\*(C'\fR/\f(CW\*(C`THAW\*(C'\fR method pair: .PP .Vb 2 \& 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) \& } .Ve .SH "BUGS" .IX Header "BUGS" The use of overload makes this module much heavier than it should be (on my system, this module: 4kB \s-1RSS,\s0 overload: 260kB \s-1RSS\s0). .SH "SEE ALSO" .IX Header "SEE ALSO" Currently, \s-1JSON::XS\s0 and \s-1CBOR::XS\s0 use these types. .SH "AUTHOR" .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://home.schmorp.de/ .Ve PK!u{ %man/man3/Types::Serialiser::Error.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Serialiser::Error 3" .TH Serialiser::Error 3 "2013-10-27" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Types::Serialiser::Error \- dummy module for Types::Serialiser .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& # do not "use" yourself .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module exists only to provide overload resolution for Storable and similar modules that assume that class name equals module name. See Types::Serialiser for more info about this class. .SH "AUTHOR" .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://home.schmorp.de/ .Ve PK!qo[[man/man3/JSON::XS.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "XS 3" .TH XS 3 "2020-10-27" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" JSON::XS \- JSON serialising/deserialising, done correctly and fast .PP JSON::XS \- 正しくて高速な JSON シリアライザ/デシリアライザ (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html) .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use JSON::XS; \& \& # 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::XS\->new\->ascii\->pretty\->allow_nonref; \& $pretty_printed_unencoded = $coder\->encode ($perl_scalar); \& $perl_scalar = $coder\->decode ($unicode_json_text); \& \& # Note that JSON version 2.0 and above will automatically use JSON::XS \& # if available, at virtually no speed overhead either, so you should \& # be able to just: \& \& use JSON; \& \& # and do the same things, except that you have a pure\-perl fallback now. .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module converts Perl data structures to \s-1JSON\s0 and vice versa. Its primary goal is to be \fIcorrect\fR and its secondary goal is to be \&\fIfast\fR. To reach the latter goal it was written in C. .PP See \s-1MAPPING,\s0 below, on how \s-1JSON::XS\s0 maps perl values to \s-1JSON\s0 values and vice versa. .SS "\s-1FEATURES\s0" .IX Subsection "FEATURES" .IP "\(bu" 4 correct Unicode handling .Sp This module knows how to handle Unicode, documents how and when it does so, and even documents what \*(L"correct\*(R" means. .IP "\(bu" 4 round-trip integrity .Sp When you serialise a perl data structure using only data types supported by \s-1JSON\s0 and Perl, the deserialised data structure is identical on the Perl level. (e.g. the string \*(L"2.0\*(R" doesn't suddenly become \*(L"2\*(R" just because it looks like a number). There \fIare\fR minor exceptions to this, read the \&\s-1MAPPING\s0 section below to learn about those. .IP "\(bu" 4 strict checking of \s-1JSON\s0 correctness .Sp There is no guessing, no generating of illegal \s-1JSON\s0 texts by default, and only \s-1JSON\s0 is accepted as input by default (the latter is a security feature). .IP "\(bu" 4 fast .Sp Compared to other \s-1JSON\s0 modules and other serialisers such as Storable, this module usually compares favourably in terms of speed, too. .IP "\(bu" 4 simple to use .Sp This module has both a simple functional interface as well as an object oriented interface. .IP "\(bu" 4 reasonably versatile output formats .Sp You can choose between the most compact guaranteed-single-line format possible (nice for simple line-based protocols), a pure-ASCII format (for when your transport is not 8\-bit clean, still supports the whole Unicode range), or a pretty-printed format (for when you want to read that stuff). Or you can combine those features in whatever way you like. .SH "FUNCTIONAL INTERFACE" .IX Header "FUNCTIONAL INTERFACE" The following convenience methods are provided by this module. They are exported by default: .ie n .IP "$json_text = encode_json $perl_scalar" 4 .el .IP "\f(CW$json_text\fR = encode_json \f(CW$perl_scalar\fR" 4 .IX Item "$json_text = encode_json $perl_scalar" Converts the given Perl data structure to a \s-1UTF\-8\s0 encoded, binary string (that is, the string contains octets only). Croaks on error. .Sp This function call is functionally identical to: .Sp .Vb 1 \& $json_text = JSON::XS\->new\->utf8\->encode ($perl_scalar) .Ve .Sp Except being faster. .ie n .IP "$perl_scalar = decode_json $json_text" 4 .el .IP "\f(CW$perl_scalar\fR = decode_json \f(CW$json_text\fR" 4 .IX Item "$perl_scalar = decode_json $json_text" The opposite of \f(CW\*(C`encode_json\*(C'\fR: expects a \s-1UTF\-8\s0 (binary) string and tries to parse that as a \s-1UTF\-8\s0 encoded \s-1JSON\s0 text, returning the resulting reference. Croaks on error. .Sp This function call is functionally identical to: .Sp .Vb 1 \& $perl_scalar = JSON::XS\->new\->utf8\->decode ($json_text) .Ve .Sp Except being faster. .SH "A FEW NOTES ON UNICODE AND PERL" .IX Header "A FEW NOTES ON UNICODE AND PERL" Since this often leads to confusion, here are a few very clear words on how Unicode works in Perl, modulo bugs. .IP "1. Perl strings can store characters with ordinal values > 255." 4 .IX Item "1. Perl strings can store characters with ordinal values > 255." This enables you to store Unicode characters as single characters in a Perl string \- very natural. .IP "2. Perl does \fInot\fR associate an encoding with your strings." 4 .IX Item "2. Perl does not associate an encoding with your strings." \&... until you force it to, e.g. when matching it against a regex, or printing the scalar to a file, in which case Perl either interprets your string as locale-encoded text, octets/binary, or as Unicode, depending on various settings. In no case is an encoding stored together with your data, it is \fIuse\fR that decides encoding, not any magical meta data. .IP "3. The internal utf\-8 flag has no meaning with regards to the encoding of your string." 4 .IX Item "3. The internal utf-8 flag has no meaning with regards to the encoding of your string." Just ignore that flag unless you debug a Perl bug, a module written in \&\s-1XS\s0 or want to dive into the internals of perl. Otherwise it will only confuse you, as, despite the name, it says nothing about how your string is encoded. You can have Unicode strings with that flag set, with that flag clear, and you can have binary data with that flag set and that flag clear. Other possibilities exist, too. .Sp If you didn't know about that flag, just the better, pretend it doesn't exist. .ie n .IP "4. A ""Unicode String"" is simply a string where each character can be validly interpreted as a Unicode code point." 4 .el .IP "4. A ``Unicode String'' is simply a string where each character can be validly interpreted as a Unicode code point." 4 .IX Item "4. A Unicode String is simply a string where each character can be validly interpreted as a Unicode code point." If you have \s-1UTF\-8\s0 encoded data, it is no longer a Unicode string, but a Unicode string encoded in \s-1UTF\-8,\s0 giving you a binary string. .ie n .IP "5. A string containing ""high"" (> 255) character values is \fInot\fR a \s-1UTF\-8\s0 string." 4 .el .IP "5. A string containing ``high'' (> 255) character values is \fInot\fR a \s-1UTF\-8\s0 string." 4 .IX Item "5. A string containing high (> 255) character values is not a UTF-8 string." It's a fact. Learn to live with it. .PP I hope this helps :) .SH "OBJECT-ORIENTED INTERFACE" .IX Header "OBJECT-ORIENTED INTERFACE" The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats. .ie n .IP "$json = new \s-1JSON::XS\s0" 4 .el .IP "\f(CW$json\fR = new \s-1JSON::XS\s0" 4 .IX Item "$json = new JSON::XS" Creates a new \s-1JSON::XS\s0 object that can be used to de/encode \s-1JSON\s0 strings. All boolean flags described below are by default \fIdisabled\fR (with the exception of \f(CW\*(C`allow_nonref\*(C'\fR, which defaults to \fIenabled\fR since version \f(CW4.0\fR). .Sp The mutators for flags all return the \s-1JSON\s0 object again and thus calls can be chained: .Sp .Vb 2 \& my $json = JSON::XS\->new\->utf8\->space_after\->encode ({a => [1,2]}) \& => {"a": [1, 2]} .Ve .ie n .IP "$json = $json\->ascii ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->ascii ([$enable])" 4 .IX Item "$json = $json->ascii ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_ascii" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_ascii" 4 .IX Item "$enabled = $json->get_ascii" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will not generate characters outside the code range \f(CW0..127\fR (which is \s-1ASCII\s0). Any Unicode characters outside that range will be escaped using either a single \euXXXX (\s-1BMP\s0 characters) or a double \euHHHH\euLLLLL escape sequence, as per \s-1RFC4627.\s0 The resulting encoded \s-1JSON\s0 text can be treated as a native Unicode string, an ascii-encoded, latin1\-encoded or \s-1UTF\-8\s0 encoded string, or any other superset of \s-1ASCII.\s0 .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not escape Unicode characters unless required by the \s-1JSON\s0 syntax or other flags. This results in a faster and more compact format. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp The main use for this flag is to produce \s-1JSON\s0 texts that can be transmitted over a 7\-bit channel, as the encoded \s-1JSON\s0 texts will not contain any 8 bit characters. .Sp .Vb 2 \& JSON::XS\->new\->ascii (1)\->encode ([chr 0x10401]) \& => ["\eud801\eudc01"] .Ve .ie n .IP "$json = $json\->latin1 ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->latin1 ([$enable])" 4 .IX Item "$json = $json->latin1 ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_latin1" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_latin1" 4 .IX Item "$enabled = $json->get_latin1" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will encode the resulting \s-1JSON\s0 text as latin1 (or iso\-8859\-1), escaping any characters outside the code range \f(CW0..255\fR. The resulting string can be treated as a latin1\-encoded \s-1JSON\s0 text or a native Unicode string. The \f(CW\*(C`decode\*(C'\fR method will not be affected in any way by this flag, as \f(CW\*(C`decode\*(C'\fR by default expects Unicode, which is a strict superset of latin1. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not escape Unicode characters unless required by the \s-1JSON\s0 syntax or other flags. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp The main use for this flag is efficiently encoding binary data as \s-1JSON\s0 text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting \s-1JSON\s0 text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for \s-1JSON.\s0 It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other \s-1JSON\s0 encoders/decoders. .Sp .Vb 2 \& JSON::XS\->new\->latin1\->encode (["\ex{89}\ex{abc}"] \& => ["\ex{89}\e\eu0abc"] # (perl syntax, U+abc escaped, U+89 not) .Ve .ie n .IP "$json = $json\->utf8 ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->utf8 ([$enable])" 4 .IX Item "$json = $json->utf8 ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_utf8" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_utf8" 4 .IX Item "$enabled = $json->get_utf8" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will encode the \s-1JSON\s0 result into \s-1UTF\-8,\s0 as required by many protocols, while the \&\f(CW\*(C`decode\*(C'\fR method expects to be handed a UTF\-8\-encoded string. Please note that UTF\-8\-encoded strings do not contain any characters outside the range \f(CW0..255\fR, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the \s-1UTF\-16\s0 and \s-1UTF\-32\s0 encoding families, as described in \s-1RFC4627.\s0 .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will return the \s-1JSON\s0 string as a (non-encoded) Unicode string, while \f(CW\*(C`decode\*(C'\fR expects thus a Unicode string. Any decoding or encoding (e.g. to \s-1UTF\-8\s0 or \s-1UTF\-16\s0) needs to be done yourself, e.g. using the Encode module. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp Example, output UTF\-16BE\-encoded \s-1JSON:\s0 .Sp .Vb 2 \& use Encode; \& $jsontext = encode "UTF\-16BE", JSON::XS\->new\->encode ($object); .Ve .Sp Example, decode UTF\-32LE\-encoded \s-1JSON:\s0 .Sp .Vb 2 \& use Encode; \& $object = JSON::XS\->new\->decode (decode "UTF\-32LE", $jsontext); .Ve .ie n .IP "$json = $json\->pretty ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->pretty ([$enable])" 4 .IX Item "$json = $json->pretty ([$enable])" This enables (or disables) all of the \f(CW\*(C`indent\*(C'\fR, \f(CW\*(C`space_before\*(C'\fR and \&\f(CW\*(C`space_after\*(C'\fR (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible. .Sp Example, pretty-print some simple structure: .Sp .Vb 8 \& my $json = JSON::XS\->new\->pretty(1)\->encode ({a => [1,2]}) \& => \& { \& "a" : [ \& 1, \& 2 \& ] \& } .Ve .ie n .IP "$json = $json\->indent ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->indent ([$enable])" 4 .IX Item "$json = $json->indent ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_indent" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_indent" 4 .IX Item "$enabled = $json->get_indent" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly. .Sp If \f(CW$enable\fR is false, no newlines or indenting will be produced, and the resulting \s-1JSON\s0 text is guaranteed not to contain any \f(CW\*(C`newlines\*(C'\fR. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. .ie n .IP "$json = $json\->space_before ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->space_before ([$enable])" 4 .IX Item "$json = $json->space_before ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_space_before" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_space_before" 4 .IX Item "$enabled = $json->get_space_before" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will add an extra optional space before the \f(CW\*(C`:\*(C'\fR separating keys from values in \s-1JSON\s0 objects. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not add any extra space at those places. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. You will also most likely combine this setting with \f(CW\*(C`space_after\*(C'\fR. .Sp Example, space_before enabled, space_after and indent disabled: .Sp .Vb 1 \& {"key" :"value"} .Ve .ie n .IP "$json = $json\->space_after ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->space_after ([$enable])" 4 .IX Item "$json = $json->space_after ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_space_after" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_space_after" 4 .IX Item "$enabled = $json->get_space_after" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will add an extra optional space after the \f(CW\*(C`:\*(C'\fR separating keys from values in \s-1JSON\s0 objects and extra whitespace after the \f(CW\*(C`,\*(C'\fR separating key-value pairs and array members. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not add any extra space at those places. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. .Sp Example, space_before and indent disabled, space_after enabled: .Sp .Vb 1 \& {"key": "value"} .Ve .ie n .IP "$json = $json\->relaxed ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->relaxed ([$enable])" 4 .IX Item "$json = $json->relaxed ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_relaxed" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_relaxed" 4 .IX Item "$enabled = $json->get_relaxed" .PD If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`decode\*(C'\fR will accept some extensions to normal \s-1JSON\s0 syntax (see below). \f(CW\*(C`encode\*(C'\fR will not be affected in any way. \fIBe aware that this option makes you accept invalid \&\s-1JSON\s0 texts as if they were valid!\fR. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.) .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`decode\*(C'\fR will only accept valid \s-1JSON\s0 texts. .Sp Currently accepted extensions are: .RS 4 .IP "\(bu" 4 list items can have an end-comma .Sp \&\s-1JSON\s0 \fIseparates\fR array elements and key-value pairs with commas. This can be annoying if you write \s-1JSON\s0 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: .Sp .Vb 8 \& [ \& 1, \& 2, <\- this comma not normally allowed \& ] \& { \& "k1": "v1", \& "k2": "v2", <\- this comma not normally allowed \& } .Ve .IP "\(bu" 4 shell-style '#'\-comments .Sp Whenever \s-1JSON\s0 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. .Sp .Vb 4 \& [ \& 1, # this comment not allowed in JSON \& # neither this one... \& ] .Ve .IP "\(bu" 4 literal \s-1ASCII TAB\s0 characters in strings .Sp Literal \s-1ASCII TAB\s0 characters are now allowed in strings (and treated as \&\f(CW\*(C`\et\*(C'\fR). .Sp .Vb 4 \& [ \& "Hello\etWorld", \& "HelloWorld", # literal would not normally be allowed \& ] .Ve .RE .RS 4 .RE .ie n .IP "$json = $json\->canonical ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->canonical ([$enable])" 4 .IX Item "$json = $json->canonical ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_canonical" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_canonical" 4 .IX Item "$enabled = $json->get_canonical" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will output \s-1JSON\s0 objects by sorting their keys. This is adding a comparatively high overhead. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script, and can change even within the same run from 5.18 onwards). .Sp This option is useful if you want the same data structure to be encoded as the same \s-1JSON\s0 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. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. .Sp This setting has currently no effect on tied hashes. .ie n .IP "$json = $json\->allow_nonref ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_nonref ([$enable])" 4 .IX Item "$json = $json->allow_nonref ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_nonref" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_nonref" 4 .IX Item "$enabled = $json->get_allow_nonref" .PD Unlike other boolean options, this opotion is enabled by default beginning with version \f(CW4.0\fR. See \*(L"\s-1SECURITY CONSIDERATIONS\*(R"\s0 for the gory details. .Sp If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method can convert a non-reference into its corresponding string, number or null \s-1JSON\s0 value, which is an extension to \s-1RFC4627.\s0 Likewise, \f(CW\*(C`decode\*(C'\fR will accept those \s-1JSON\s0 values instead of croaking. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will croak if it isn't passed an arrayref or hashref, as \s-1JSON\s0 texts must either be an object or array. Likewise, \f(CW\*(C`decode\*(C'\fR will croak if given something that is not a \&\s-1JSON\s0 object or array. .Sp Example, encode a Perl scalar as \s-1JSON\s0 value without enabled \f(CW\*(C`allow_nonref\*(C'\fR, resulting in an error: .Sp .Vb 2 \& JSON::XS\->new\->allow_nonref (0)\->encode ("Hello, World!") \& => hash\- or arrayref expected... .Ve .ie n .IP "$json = $json\->allow_unknown ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_unknown ([$enable])" 4 .IX Item "$json = $json->allow_unknown ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_unknown" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_unknown" 4 .IX Item "$enabled = $json->get_allow_unknown" .PD If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`encode\*(C'\fR will \fInot\fR throw an exception when it encounters values it cannot represent in \s-1JSON\s0 (for example, filehandles) but instead will encode a \s-1JSON\s0 \f(CW\*(C`null\*(C'\fR value. Note that blessed objects are not included here and are handled separately by c. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will throw an exception when it encounters anything it cannot encode as \s-1JSON.\s0 .Sp This option does not affect \f(CW\*(C`decode\*(C'\fR in any way, and it is recommended to leave it off unless you know your communications partner. .ie n .IP "$json = $json\->allow_blessed ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_blessed ([$enable])" 4 .IX Item "$json = $json->allow_blessed ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_blessed" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_blessed" 4 .IX Item "$enabled = $json->get_allow_blessed" .PD See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0 for details. .Sp If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will not barf when it encounters a blessed reference that it cannot convert otherwise. Instead, a \s-1JSON\s0 \f(CW\*(C`null\*(C'\fR value is encoded instead of the object. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will throw an exception when it encounters a blessed object that it cannot convert otherwise. .Sp This setting has no effect on \f(CW\*(C`decode\*(C'\fR. .ie n .IP "$json = $json\->convert_blessed ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->convert_blessed ([$enable])" 4 .IX Item "$json = $json->convert_blessed ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_convert_blessed" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_convert_blessed" 4 .IX Item "$enabled = $json->get_convert_blessed" .PD See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0 for details. .Sp If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`encode\*(C'\fR, upon encountering a blessed object, will check for the availability of the \f(CW\*(C`TO_JSON\*(C'\fR 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. .Sp The \f(CW\*(C`TO_JSON\*(C'\fR method may safely call die if it wants. If \f(CW\*(C`TO_JSON\*(C'\fR returns other blessed objects, those will be handled in the same way. \f(CW\*(C`TO_JSON\*(C'\fR must take care of not causing an endless recursion cycle (== crash) in this case. The name of \f(CW\*(C`TO_JSON\*(C'\fR 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 any \f(CW\*(C`to_json\*(C'\fR function or method. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will not consider this type of conversion. .Sp This setting has no effect on \f(CW\*(C`decode\*(C'\fR. .ie n .IP "$json = $json\->allow_tags ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_tags ([$enable])" 4 .IX Item "$json = $json->allow_tags ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_tags" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_tags" 4 .IX Item "$enabled = $json->get_allow_tags" .PD See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0 for details. .Sp If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`encode\*(C'\fR, upon encountering a blessed object, will check for the availability of the \f(CW\*(C`FREEZE\*(C'\fR method on the object's class. If found, it will be used to serialise the object into a nonstandard tagged \s-1JSON\s0 value (that \s-1JSON\s0 decoders cannot decode). .Sp It also causes \f(CW\*(C`decode\*(C'\fR to parse such tagged \s-1JSON\s0 values and deserialise them via a call to the \f(CW\*(C`THAW\*(C'\fR method. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will not consider this type of conversion, and tagged \s-1JSON\s0 values will cause a parse error in \f(CW\*(C`decode\*(C'\fR, as if tags were not part of the grammar. .ie n .IP "$json\->boolean_values ([$false, $true])" 4 .el .IP "\f(CW$json\fR\->boolean_values ([$false, \f(CW$true\fR])" 4 .IX Item "$json->boolean_values ([$false, $true])" .PD 0 .ie n .IP "($false, $true) = $json\->get_boolean_values" 4 .el .IP "($false, \f(CW$true\fR) = \f(CW$json\fR\->get_boolean_values" 4 .IX Item "($false, $true) = $json->get_boolean_values" .PD By default, \s-1JSON\s0 booleans will be decoded as overloaded \&\f(CW$Types::Serialiser::false\fR and \f(CW$Types::Serialiser::true\fR objects. .Sp With this method you can specify your own boolean values for decoding \- on decode, \s-1JSON\s0 \f(CW\*(C`false\*(C'\fR will be decoded as a copy of \f(CW$false\fR, and \s-1JSON\s0 \&\f(CW\*(C`true\*(C'\fR will be decoded as \f(CW$true\fR (\*(L"copy\*(R" here is the same thing as assigning a value to another variable, i.e. \f(CW\*(C`$copy = $false\*(C'\fR). .Sp Calling this method without any arguments will reset the booleans to their default values. .Sp \&\f(CW\*(C`get_boolean_values\*(C'\fR will return both \f(CW$false\fR and \f(CW$true\fR values, or the empty list when they are set to the default. .ie n .IP "$json = $json\->filter_json_object ([$coderef\->($hashref)])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->filter_json_object ([$coderef\->($hashref)])" 4 .IX Item "$json = $json->filter_json_object ([$coderef->($hashref)])" When \f(CW$coderef\fR is specified, it will be called from \f(CW\*(C`decode\*(C'\fR each time it decodes a \s-1JSON\s0 object. The only argument is a reference to the newly-created hash. If the code reference returns a single scalar (which need not be a reference), this value (or rather a copy of it) is inserted into the deserialised data structure. If it returns an empty list (\s-1NOTE:\s0 \fInot\fR \f(CW\*(C`undef\*(C'\fR, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably. .Sp When \f(CW$coderef\fR is omitted or undefined, any existing callback will be removed and \f(CW\*(C`decode\*(C'\fR will not change the deserialised hash in any way. .Sp Example, convert all \s-1JSON\s0 objects into the integer 5: .Sp .Vb 6 \& my $js = JSON::XS\->new\->filter_json_object (sub { 5 }); \& # returns [5] \& $js\->decode (\*(Aq[{}]\*(Aq) \& # throw an exception because allow_nonref is not enabled \& # so a lone 5 is not allowed. \& $js\->decode (\*(Aq{"a":1, "b":2}\*(Aq); .Ve .ie n .IP "$json = $json\->filter_json_single_key_object ($key [=> $coderef\->($value)])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->filter_json_single_key_object ($key [=> \f(CW$coderef\fR\->($value)])" 4 .IX Item "$json = $json->filter_json_single_key_object ($key [=> $coderef->($value)])" Works remotely similar to \f(CW\*(C`filter_json_object\*(C'\fR, but is only called for \&\s-1JSON\s0 objects having a single key named \f(CW$key\fR. .Sp This \f(CW$coderef\fR is called before the one specified via \&\f(CW\*(C`filter_json_object\*(C'\fR, if any. It gets passed the single value in the \s-1JSON\s0 object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even \f(CW\*(C`undef\*(C'\fR but the empty list), the callback from \f(CW\*(C`filter_json_object\*(C'\fR will be called next, as if no single-key callback were specified. .Sp If \f(CW$coderef\fR is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key. .Sp As this callback gets called less often then the \f(CW\*(C`filter_json_object\*(C'\fR 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 \s-1JSON\s0 objects are as close to the type-tagged value concept as \s-1JSON\s0 gets (it's basically an \s-1ID/VALUE\s0 tuple). Of course, \s-1JSON\s0 does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash. .Sp Typical names for the single object key are \f(CW\*(C`_\|_class_whatever_\|_\*(C'\fR, or \&\f(CW\*(C`$_\|_dollars_are_rarely_used_\|_$\*(C'\fR or \f(CW\*(C`}ugly_brace_placement\*(C'\fR, or even things like \f(CW\*(C`_\|_class_md5sum(classname)_\|_\*(C'\fR, to reduce the risk of clashing with real hashes. .Sp Example, decode \s-1JSON\s0 objects of the form \f(CW\*(C`{ "_\|_widget_\|_" => }\*(C'\fR into the corresponding \f(CW$WIDGET{}\fR object: .Sp .Vb 7 \& # return whatever is in $WIDGET{5}: \& JSON::XS \& \->new \& \->filter_json_single_key_object (_\|_widget_\|_ => sub { \& $WIDGET{ $_[0] } \& }) \& \->decode (\*(Aq{"_\|_widget_\|_": 5\*(Aq) \& \& # 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} } \& } .Ve .ie n .IP "$json = $json\->shrink ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->shrink ([$enable])" 4 .IX Item "$json = $json->shrink ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_shrink" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_shrink" 4 .IX Item "$enabled = $json->get_shrink" .PD Perl usually over-allocates memory a bit when allocating space for strings. This flag optionally resizes strings generated by either \&\f(CW\*(C`encode\*(C'\fR or \f(CW\*(C`decode\*(C'\fR to their minimum size possible. This can save memory when your \s-1JSON\s0 texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less space in general (and some buggy Perl or C code might even rely on that internal representation being used). .Sp The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time. .Sp If \f(CW$enable\fR is true (or missing), the string returned by \f(CW\*(C`encode\*(C'\fR will be shrunk-to-fit, while all strings generated by \f(CW\*(C`decode\*(C'\fR will also be shrunk-to-fit. .Sp If \f(CW$enable\fR is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster. .Sp In the future, this setting might control other things, such as converting strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space. .ie n .IP "$json = $json\->max_depth ([$maximum_nesting_depth])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->max_depth ([$maximum_nesting_depth])" 4 .IX Item "$json = $json->max_depth ([$maximum_nesting_depth])" .PD 0 .ie n .IP "$max_depth = $json\->get_max_depth" 4 .el .IP "\f(CW$max_depth\fR = \f(CW$json\fR\->get_max_depth" 4 .IX Item "$max_depth = $json->get_max_depth" .PD Sets the maximum nesting level (default \f(CW512\fR) accepted while encoding or decoding. If a higher nesting level is detected in \s-1JSON\s0 text or a Perl data structure, then the encoder and decoder will stop and croak at that point. .Sp 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 \f(CW\*(C`{\*(C'\fR or \f(CW\*(C`[\*(C'\fR characters without their matching closing parenthesis crossed to reach a given character in a string. .Sp Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array. .Sp If no argument is given, the highest possible setting will be used, which is rarely useful. .Sp Note that nesting is implemented by recursion in C. The default value has been chosen to be as large as typical operating systems allow without crashing. .Sp See \s-1SECURITY CONSIDERATIONS,\s0 below, for more info on why this is useful. .ie n .IP "$json = $json\->max_size ([$maximum_string_size])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->max_size ([$maximum_string_size])" 4 .IX Item "$json = $json->max_size ([$maximum_string_size])" .PD 0 .ie n .IP "$max_size = $json\->get_max_size" 4 .el .IP "\f(CW$max_size\fR = \f(CW$json\fR\->get_max_size" 4 .IX Item "$max_size = $json->get_max_size" .PD Set the maximum length a \s-1JSON\s0 text may have (in bytes) where decoding is being attempted. The default is \f(CW0\fR, meaning no limit. When \f(CW\*(C`decode\*(C'\fR 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 \f(CW\*(C`encode\*(C'\fR (yet). .Sp If no argument is given, the limit check will be deactivated (same as when \&\f(CW0\fR is specified). .Sp See \s-1SECURITY CONSIDERATIONS,\s0 below, for more info on why this is useful. .ie n .IP "$json_text = $json\->encode ($perl_scalar)" 4 .el .IP "\f(CW$json_text\fR = \f(CW$json\fR\->encode ($perl_scalar)" 4 .IX Item "$json_text = $json->encode ($perl_scalar)" Converts the given Perl value or data structure to its \s-1JSON\s0 representation. Croaks on error. .ie n .IP "$perl_scalar = $json\->decode ($json_text)" 4 .el .IP "\f(CW$perl_scalar\fR = \f(CW$json\fR\->decode ($json_text)" 4 .IX Item "$perl_scalar = $json->decode ($json_text)" The opposite of \f(CW\*(C`encode\*(C'\fR: expects a \s-1JSON\s0 text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error. .ie n .IP "($perl_scalar, $characters) = $json\->decode_prefix ($json_text)" 4 .el .IP "($perl_scalar, \f(CW$characters\fR) = \f(CW$json\fR\->decode_prefix ($json_text)" 4 .IX Item "($perl_scalar, $characters) = $json->decode_prefix ($json_text)" This works like the \f(CW\*(C`decode\*(C'\fR method, but instead of raising an exception when there is trailing garbage after the first \s-1JSON\s0 object, it will silently stop parsing there and return the number of characters consumed so far. .Sp This is useful if your \s-1JSON\s0 texts are not delimited by an outer protocol and you need to know where the \s-1JSON\s0 text ends. .Sp .Vb 2 \& JSON::XS\->new\->decode_prefix ("[1] the tail") \& => ([1], 3) .Ve .SH "INCREMENTAL PARSING" .IX Header "INCREMENTAL PARSING" In some cases, there is the need for incremental parsing of \s-1JSON\s0 texts. While this module always has to keep both \s-1JSON\s0 text and resulting Perl data structure in memory at one time, it does allow you to parse a \&\s-1JSON\s0 stream incrementally. It does so by accumulating text until it has a full \s-1JSON\s0 object, which it then can decode. This process is similar to using \f(CW\*(C`decode_prefix\*(C'\fR to see if a full \s-1JSON\s0 object is available, but is much more efficient (and can be implemented with a minimum of method calls). .PP \&\s-1JSON::XS\s0 will only attempt to parse the \s-1JSON\s0 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 mismatched parentheses. The only thing it guarantees is that it starts decoding as soon as a syntactically valid \s-1JSON\s0 text has been seen. This means you need to set resource limits (e.g. \f(CW\*(C`max_size\*(C'\fR) to ensure the parser will stop parsing in the presence if syntax errors. .PP The following methods implement this incremental parser. .ie n .IP "[void, scalar or list context] = $json\->incr_parse ([$string])" 4 .el .IP "[void, scalar or list context] = \f(CW$json\fR\->incr_parse ([$string])" 4 .IX Item "[void, scalar or list context] = $json->incr_parse ([$string])" 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). .Sp If \f(CW$string\fR is given, then this string is appended to the already existing \s-1JSON\s0 fragment stored in the \f(CW$json\fR object. .Sp 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. .Sp If the method is called in scalar context, then it will try to extract exactly \fIone\fR \s-1JSON\s0 object. If that is successful, it will return this object, otherwise it will return \f(CW\*(C`undef\*(C'\fR. If there is a parse error, this method will croak just as \f(CW\*(C`decode\*(C'\fR would do (one can then use \&\f(CW\*(C`incr_skip\*(C'\fR to skip the erroneous part). This is the most common way of using the method. .Sp 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 (other than whitespace) between the \s-1JSON\s0 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 \s-1JSON\s0 texts will be lost. .Sp Example: Parse some \s-1JSON\s0 arrays/objects in a given string and return them. .Sp .Vb 1 \& my @objs = JSON::XS\->new\->incr_parse ("[5][7][1,2]"); .Ve .ie n .IP "$lvalue_string = $json\->incr_text" 4 .el .IP "\f(CW$lvalue_string\fR = \f(CW$json\fR\->incr_text" 4 .IX Item "$lvalue_string = $json->incr_text" This method returns the currently stored \s-1JSON\s0 fragment as an lvalue, that is, you can manipulate it. This \fIonly\fR works when a preceding call to \&\f(CW\*(C`incr_parse\*(C'\fR in \fIscalar context\fR 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 \fIwill\fR fail under real world conditions). As a special exception, you can also call this method before having parsed anything. .Sp That means you can only use this function to look at or manipulate text before or after complete \s-1JSON\s0 objects, not while the parser is in the middle of parsing a \s-1JSON\s0 object. .Sp This function is useful in two cases: a) finding the trailing text after a \&\s-1JSON\s0 object or b) parsing multiple \s-1JSON\s0 objects separated by non-JSON text (such as commas). .ie n .IP "$json\->incr_skip" 4 .el .IP "\f(CW$json\fR\->incr_skip" 4 .IX Item "$json->incr_skip" This will reset the state of the incremental parser and will remove the parsed text from the input buffer so far. This is useful after \&\f(CW\*(C`incr_parse\*(C'\fR 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. .Sp The difference to \f(CW\*(C`incr_reset\*(C'\fR is that only text until the parse error occurred is removed. .ie n .IP "$json\->incr_reset" 4 .el .IP "\f(CW$json\fR\->incr_reset" 4 .IX Item "$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. .Sp This is useful if you want to repeatedly parse \s-1JSON\s0 objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode. .SS "\s-1LIMITATIONS\s0" .IX Subsection "LIMITATIONS" The incremental parser is a non-exact parser: it works by gathering as much text as possible that \fIcould\fR be a valid \s-1JSON\s0 text, followed by trying to decode it. .PP That means it sometimes needs to read more data than strictly necessary to diagnose an invalid \s-1JSON\s0 text. For example, after parsing the following fragment, the parser \fIcould\fR stop with an error, as this fragment \&\fIcannot\fR be the beginning of a valid \s-1JSON\s0 text: .PP .Vb 1 \& [, .Ve .PP In reality, hopwever, the parser might continue to read data until a length limit is exceeded or it finds a closing bracket. .SS "\s-1EXAMPLES\s0" .IX Subsection "EXAMPLES" Some examples will make all this clearer. First, a simple example that works similarly to \f(CW\*(C`decode_prefix\*(C'\fR: We want to decode the \s-1JSON\s0 object at the start of a string and identify the portion after the \s-1JSON\s0 object: .PP .Vb 1 \& my $text = "[1,2,3] hello"; \& \& my $json = new JSON::XS; \& \& my $obj = $json\->incr_parse ($text) \& or die "expected JSON object or array at beginning of string"; \& \& my $tail = $json\->incr_text; \& # $tail now contains " hello" .Ve .PP Easy, isn't it? .PP Now for a more complicated example: Imagine a hypothetical protocol where you read some requests from a \s-1TCP\s0 stream, and each request is a \s-1JSON\s0 array, without any separation between them (in fact, it is often useful to use newlines as \*(L"separators\*(R", as these get interpreted as whitespace at the start of the \s-1JSON\s0 text, which makes it possible to test said protocol with \f(CW\*(C`telnet\*(C'\fR...). .PP Here is how you'd do it (it is trivial to write this in an event-based manner): .PP .Vb 1 \& my $json = new JSON::XS; \& \& # read some data from the socket \& while (sysread $socket, my $buf, 4096) { \& \& # split and decode as many requests as possible \& for my $request ($json\->incr_parse ($buf)) { \& # act on the $request \& } \& } .Ve .PP Another complicated example: Assume you have a string with \s-1JSON\s0 objects or arrays, all separated by (optional) comma characters (e.g. \f(CW\*(C`[1],[2], [3]\*(C'\fR). To parse them, we have to skip the commas between the \s-1JSON\s0 texts, and here is where the lvalue-ness of \f(CW\*(C`incr_text\*(C'\fR comes in useful: .PP .Vb 2 \& my $text = "[1],[2], [3]"; \& my $json = new JSON::XS; \& \& # void context, so no parsing done \& $json\->incr_parse ($text); \& \& # now extract as many objects as possible. note the \& # use of scalar context so incr_text can be called. \& while (my $obj = $json\->incr_parse) { \& # do something with $obj \& \& # now skip the optional comma \& $json\->incr_text =~ s/^ \es* , //x; \& } .Ve .PP Now lets go for a very complex example: Assume that you have a gigantic \&\s-1JSON\s0 array-of-objects, many gigabytes in size, and you want to parse it, but you cannot load it into memory fully (this has actually happened in the real world :). .PP Well, you lost, you have to implement your own \s-1JSON\s0 parser. But \s-1JSON::XS\s0 can still help you: You implement a (very simple) array parser and let \&\s-1JSON\s0 decode the array elements, which are all full \s-1JSON\s0 objects on their own (this wouldn't work if the array elements could be \s-1JSON\s0 numbers, for example): .PP .Vb 1 \& my $json = new JSON::XS; \& \& # open the monster \& open my $fh, "incr_parse ($buf); # void context, so no parsing \& \& # Exit the loop once we found and removed(!) the initial "[". \& # In essence, we are (ab\-)using the $json object as a simple scalar \& # we append data to. \& last if $json\->incr_text =~ s/^ \es* \e[ //x; \& } \& \& # now we have the skipped the initial "[", so continue \& # parsing all the elements. \& for (;;) { \& # in this loop we read data until we got a single JSON object \& for (;;) { \& if (my $obj = $json\->incr_parse) { \& # do something with $obj \& last; \& } \& \& # add more data \& sysread $fh, my $buf, 65536 \& or die "read error: $!"; \& $json\->incr_parse ($buf); # void context, so no parsing \& } \& \& # in this loop we read data until we either found and parsed the \& # separating "," between elements, or the final "]" \& for (;;) { \& # first skip whitespace \& $json\->incr_text =~ s/^\es*//; \& \& # if we find "]", we are done \& if ($json\->incr_text =~ s/^\e]//) { \& print "finished.\en"; \& exit; \& } \& \& # if we find ",", we can continue with the next element \& if ($json\->incr_text =~ s/^,//) { \& last; \& } \& \& # if we find anything else, we have a parse error! \& if (length $json\->incr_text) { \& die "parse error near ", $json\->incr_text; \& } \& \& # else add more data \& sysread $fh, my $buf, 65536 \& or die "read error: $!"; \& $json\->incr_parse ($buf); # void context, so no parsing \& } .Ve .PP This is a complex example, but most of the complexity comes from the fact that we are trying to be correct (bear with me if I am wrong, I never ran the above example :). .SH "MAPPING" .IX Header "MAPPING" This section describes how \s-1JSON::XS\s0 maps Perl values to \s-1JSON\s0 values and vice versa. These mappings are designed to \*(L"do the right thing\*(R" in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent). .PP For the more enlightened: note that in the following descriptions, lowercase \fIperl\fR refers to the Perl interpreter, while uppercase \fIPerl\fR refers to the abstract Perl language itself. .SS "\s-1JSON\s0 \-> \s-1PERL\s0" .IX Subsection "JSON -> PERL" .IP "object" 4 .IX Item "object" A \s-1JSON\s0 object becomes a reference to a hash in Perl. No ordering of object keys is preserved (\s-1JSON\s0 does not preserve object key ordering itself). .IP "array" 4 .IX Item "array" A \s-1JSON\s0 array becomes a reference to an array in Perl. .IP "string" 4 .IX Item "string" A \s-1JSON\s0 string becomes a string scalar in Perl \- Unicode codepoints in \s-1JSON\s0 are represented by the same codepoints in the Perl string, so no manual decoding is necessary. .IP "number" 4 .IX Item "number" A \s-1JSON\s0 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. .Sp If the number consists of digits only, \s-1JSON::XS\s0 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 \s-1JSON\s0 number will be re-encoded to a \s-1JSON\s0 string). .Sp 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 \s-1JSON\s0 number will still be re-encoded as a \s-1JSON\s0 number). .Sp Note that precision is not accuracy \- binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, \s-1JSON::XS\s0 only guarantees precision up to but not including the least significant bit. .IP "true, false" 4 .IX Item "true, false" These \s-1JSON\s0 atoms become \f(CW\*(C`Types::Serialiser::true\*(C'\fR and \&\f(CW\*(C`Types::Serialiser::false\*(C'\fR, respectively. They are overloaded to act almost exactly like the numbers \f(CW1\fR and \f(CW0\fR. You can check whether a scalar is a \s-1JSON\s0 boolean by using the \f(CW\*(C`Types::Serialiser::is_bool\*(C'\fR function (after \f(CW\*(C`use Types::Serialier\*(C'\fR, of course). .IP "null" 4 .IX Item "null" A \s-1JSON\s0 null atom becomes \f(CW\*(C`undef\*(C'\fR in Perl. .ie n .IP "shell-style comments (""# \fItext\fP"")" 4 .el .IP "shell-style comments (\f(CW# \f(CItext\f(CW\fR)" 4 .IX Item "shell-style comments (# text)" As a nonstandard extension to the \s-1JSON\s0 syntax that is enabled by the \&\f(CW\*(C`relaxed\*(C'\fR setting, shell-style comments are allowed. They can start anywhere outside strings and go till the end of the line. .ie n .IP "tagged values (""(\fItag\fP)\fIvalue\fP"")." 4 .el .IP "tagged values (\f(CW(\f(CItag\f(CW)\f(CIvalue\f(CW\fR)." 4 .IX Item "tagged values ((tag)value)." Another nonstandard extension to the \s-1JSON\s0 syntax, enabled with the \&\f(CW\*(C`allow_tags\*(C'\fR setting, are tagged values. In this implementation, the \&\fItag\fR must be a perl package/class name encoded as a \s-1JSON\s0 string, and the \&\fIvalue\fR must be a \s-1JSON\s0 array encoding optional constructor arguments. .Sp See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0, below, for details. .SS "\s-1PERL\s0 \-> \s-1JSON\s0" .IX Subsection "PERL -> JSON" The mapping from Perl to \s-1JSON\s0 is slightly more difficult, as Perl is a truly typeless language, so we can only guess which \s-1JSON\s0 type is meant by a Perl value. .IP "hash references" 4 .IX Item "hash references" Perl hash references become \s-1JSON\s0 objects. As there is no inherent ordering in hash keys (or \s-1JSON\s0 objects), they will usually be encoded in a pseudo-random order. \s-1JSON::XS\s0 can optionally sort the hash keys (determined by the \fIcanonical\fR flag), so the same datastructure will serialise to the same \s-1JSON\s0 text (given same settings and version of \&\s-1JSON::XS\s0), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some \s-1JSON\s0 text against another for equality. .IP "array references" 4 .IX Item "array references" Perl array references become \s-1JSON\s0 arrays. .IP "other references" 4 .IX Item "other references" Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers \f(CW0\fR and \&\f(CW1\fR, which get turned into \f(CW\*(C`false\*(C'\fR and \f(CW\*(C`true\*(C'\fR atoms in \s-1JSON.\s0 .Sp Since \f(CW\*(C`JSON::XS\*(C'\fR uses the boolean model from Types::Serialiser, you can also \f(CW\*(C`use Types::Serialiser\*(C'\fR and then use \f(CW\*(C`Types::Serialiser::false\*(C'\fR and \f(CW\*(C`Types::Serialiser::true\*(C'\fR to improve readability. .Sp .Vb 2 \& use Types::Serialiser; \& encode_json [\e0, Types::Serialiser::true] # yields [false,true] .Ve .IP "Types::Serialiser::true, Types::Serialiser::false" 4 .IX Item "Types::Serialiser::true, Types::Serialiser::false" These special values from the Types::Serialiser module become \s-1JSON\s0 true and \s-1JSON\s0 false values, respectively. You can also use \f(CW\*(C`\e1\*(C'\fR and \f(CW\*(C`\e0\*(C'\fR directly if you want. .IP "blessed objects" 4 .IX Item "blessed objects" Blessed objects are not directly representable in \s-1JSON,\s0 but \f(CW\*(C`JSON::XS\*(C'\fR allows various ways of handling objects. See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0, below, for details. .IP "simple scalars" 4 .IX Item "simple scalars" Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: \s-1JSON::XS\s0 will encode undefined scalars as \&\s-1JSON\s0 \f(CW\*(C`null\*(C'\fR values, scalars that have last been used in a string context before encoding as \s-1JSON\s0 strings, and anything else as number value: .Sp .Vb 4 \& # 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] .Ve .Sp You can force the type to be a \s-1JSON\s0 string by stringifying it: .Sp .Vb 4 \& 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 .Ve .Sp You can force the type to be a \s-1JSON\s0 number by numifying it: .Sp .Vb 3 \& 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 choice is yours. .Ve .Sp You can not currently force the type in other, less obscure, ways. Tell me if you need this capability (but don't forget to explain why it's needed :). .Sp 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 \s-1JSON,\s0 and it is an error to pass those in. .SS "\s-1OBJECT SERIALISATION\s0" .IX Subsection "OBJECT SERIALISATION" As \s-1JSON\s0 cannot directly represent Perl objects, you have to choose between a pure \s-1JSON\s0 representation (without the ability to deserialise the object automatically again), and a nonstandard extension to the \s-1JSON\s0 syntax, tagged values. .PP \fI\s-1SERIALISATION\s0\fR .IX Subsection "SERIALISATION" .PP What happens when \f(CW\*(C`JSON::XS\*(C'\fR encounters a Perl object depends on the \&\f(CW\*(C`allow_blessed\*(C'\fR, \f(CW\*(C`convert_blessed\*(C'\fR and \f(CW\*(C`allow_tags\*(C'\fR settings, which are used in this order: .ie n .IP "1. ""allow_tags"" is enabled and the object has a ""FREEZE"" method." 4 .el .IP "1. \f(CWallow_tags\fR is enabled and the object has a \f(CWFREEZE\fR method." 4 .IX Item "1. allow_tags is enabled and the object has a FREEZE method." In this case, \f(CW\*(C`JSON::XS\*(C'\fR uses the Types::Serialiser object serialisation protocol to create a tagged \s-1JSON\s0 value, using a nonstandard extension to the \s-1JSON\s0 syntax. .Sp This works by invoking the \f(CW\*(C`FREEZE\*(C'\fR method on the object, with the first argument being the object to serialise, and the second argument being the constant string \f(CW\*(C`JSON\*(C'\fR to distinguish it from other serialisers. .Sp The \f(CW\*(C`FREEZE\*(C'\fR method can return any number of values (i.e. zero or more). These values and the paclkage/classname of the object will then be encoded as a tagged \s-1JSON\s0 value in the following format: .Sp .Vb 1 \& ("classname")[FREEZE return values...] .Ve .Sp e.g.: .Sp .Vb 3 \& ("URI")["http://www.google.com/"] \& ("MyDate")[2013,10,29] \& ("ImageData::JPEG")["Z3...VlCg=="] .Ve .Sp For example, the hypothetical \f(CW\*(C`My::Object\*(C'\fR \f(CW\*(C`FREEZE\*(C'\fR method might use the objects \f(CW\*(C`type\*(C'\fR and \f(CW\*(C`id\*(C'\fR members to encode the object: .Sp .Vb 2 \& sub My::Object::FREEZE { \& my ($self, $serialiser) = @_; \& \& ($self\->{type}, $self\->{id}) \& } .Ve .ie n .IP "2. ""convert_blessed"" is enabled and the object has a ""TO_JSON"" method." 4 .el .IP "2. \f(CWconvert_blessed\fR is enabled and the object has a \f(CWTO_JSON\fR method." 4 .IX Item "2. convert_blessed is enabled and the object has a TO_JSON method." In this case, the \f(CW\*(C`TO_JSON\*(C'\fR method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into \&\s-1JSON.\s0 This scalar replaces the object in the \s-1JSON\s0 text. .Sp For example, the following \f(CW\*(C`TO_JSON\*(C'\fR method will convert all \s-1URI\s0 objects to \s-1JSON\s0 strings when serialised. The fatc that these values originally were \s-1URI\s0 objects is lost. .Sp .Vb 4 \& sub URI::TO_JSON { \& my ($uri) = @_; \& $uri\->as_string \& } .Ve .ie n .IP "3. ""allow_blessed"" is enabled." 4 .el .IP "3. \f(CWallow_blessed\fR is enabled." 4 .IX Item "3. allow_blessed is enabled." The object will be serialised as a \s-1JSON\s0 null value. .IP "4. none of the above" 4 .IX Item "4. none of the above" If none of the settings are enabled or the respective methods are missing, \&\f(CW\*(C`JSON::XS\*(C'\fR throws an exception. .PP \fI\s-1DESERIALISATION\s0\fR .IX Subsection "DESERIALISATION" .PP For deserialisation there are only two cases to consider: either nonstandard tagging was used, in which case \f(CW\*(C`allow_tags\*(C'\fR decides, or objects cannot be automatically be deserialised, in which case you can use postprocessing or the \f(CW\*(C`filter_json_object\*(C'\fR or \&\f(CW\*(C`filter_json_single_key_object\*(C'\fR callbacks to get some real objects our of your \s-1JSON.\s0 .PP This section only considers the tagged value case: I a tagged \s-1JSON\s0 object is encountered during decoding and \f(CW\*(C`allow_tags\*(C'\fR is disabled, a parse error will result (as if tagged values were not part of the grammar). .PP If \f(CW\*(C`allow_tags\*(C'\fR is enabled, \f(CW\*(C`JSON::XS\*(C'\fR will look up the \f(CW\*(C`THAW\*(C'\fR method of the package/classname used during serialisation (it will not attempt to load the package as a Perl module). If there is no such method, the decoding will fail with an error. .PP Otherwise, the \f(CW\*(C`THAW\*(C'\fR method is invoked with the classname as first argument, the constant string \f(CW\*(C`JSON\*(C'\fR as second argument, and all the values from the \s-1JSON\s0 array (the values originally returned by the \&\f(CW\*(C`FREEZE\*(C'\fR method) as remaining arguments. .PP The method must then return the object. While technically you can return any Perl scalar, you might have to enable the \f(CW\*(C`enable_nonref\*(C'\fR setting to make that work in all cases, so better return an actual blessed reference. .PP As an example, let's implement a \f(CW\*(C`THAW\*(C'\fR function that regenerates the \&\f(CW\*(C`My::Object\*(C'\fR from the \f(CW\*(C`FREEZE\*(C'\fR example earlier: .PP .Vb 2 \& sub My::Object::THAW { \& my ($class, $serialiser, $type, $id) = @_; \& \& $class\->new (type => $type, id => $id) \& } .Ve .SH "ENCODING/CODESET FLAG NOTES" .IX Header "ENCODING/CODESET FLAG NOTES" The interested reader might have seen a number of flags that signify encodings or codesets \- \f(CW\*(C`utf8\*(C'\fR, \f(CW\*(C`latin1\*(C'\fR and \f(CW\*(C`ascii\*(C'\fR. There seems to be some confusion on what these do, so here is a short comparison: .PP \&\f(CW\*(C`utf8\*(C'\fR controls whether the \s-1JSON\s0 text created by \f(CW\*(C`encode\*(C'\fR (and expected by \f(CW\*(C`decode\*(C'\fR) is \s-1UTF\-8\s0 encoded or not, while \f(CW\*(C`latin1\*(C'\fR and \f(CW\*(C`ascii\*(C'\fR only control whether \f(CW\*(C`encode\*(C'\fR escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others. .PP Care has been taken to make all flags symmetrical with respect to \&\f(CW\*(C`encode\*(C'\fR and \f(CW\*(C`decode\*(C'\fR, that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used \&\- in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere. .PP Below comes a verbose discussion of these flags. Note that a \*(L"codeset\*(R" is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and \fIencodes\fR them, in our case into octets. Unicode is (among other things) a codeset, \s-1UTF\-8\s0 is an encoding, and \s-1ISO\-8859\-1\s0 (= latin 1) and \s-1ASCII\s0 are both codesets \fIand\fR encodings at the same time, which can be confusing. .ie n .IP """utf8"" flag disabled" 4 .el .IP "\f(CWutf8\fR flag disabled" 4 .IX Item "utf8 flag disabled" When \f(CW\*(C`utf8\*(C'\fR is disabled (the default), then \f(CW\*(C`encode\*(C'\fR/\f(CW\*(C`decode\*(C'\fR generate and expect Unicode strings, that is, characters with high ordinal Unicode values (> 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except \&\*(L"(re\-)interpreting\*(R" them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff). .Sp This is useful when you want to do the encoding yourself (e.g. when you want to have \s-1UTF\-16\s0 encoded \s-1JSON\s0 texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to \s-1UTF\-8\s0 you certainly do \s-1NOT\s0 want to \s-1UTF\-8\s0 encode your data first and have Perl encode it another time). .ie n .IP """utf8"" flag enabled" 4 .el .IP "\f(CWutf8\fR flag enabled" 4 .IX Item "utf8 flag enabled" If the \f(CW\*(C`utf8\*(C'\fR\-flag is enabled, \f(CW\*(C`encode\*(C'\fR/\f(CW\*(C`decode\*(C'\fR will encode all characters using the corresponding \s-1UTF\-8\s0 multi-byte sequence, and will expect your input strings to be encoded as \s-1UTF\-8,\s0 that is, no \*(L"character\*(R" of the input string must have any value > 255, as \s-1UTF\-8\s0 does not allow that. .Sp The \f(CW\*(C`utf8\*(C'\fR flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get a \s-1UTF\-8\s0 encoded octet/binary string in Perl. .ie n .IP """latin1"" or ""ascii"" flags enabled" 4 .el .IP "\f(CWlatin1\fR or \f(CWascii\fR flags enabled" 4 .IX Item "latin1 or ascii flags enabled" With \f(CW\*(C`latin1\*(C'\fR (or \f(CW\*(C`ascii\*(C'\fR) enabled, \f(CW\*(C`encode\*(C'\fR will escape characters with ordinal values > 255 (> 127 with \f(CW\*(C`ascii\*(C'\fR) and encode the remaining characters as specified by the \f(CW\*(C`utf8\*(C'\fR flag. .Sp If \f(CW\*(C`utf8\*(C'\fR is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values < 256 is the same thing as a \&\s-1ISO\-8859\-1\s0 string, and a Unicode string with all character values < 128 is the same thing as an \s-1ASCII\s0 string in Perl). .Sp If \f(CW\*(C`utf8\*(C'\fR is enabled, you still get a correct UTF\-8\-encoded string, regardless of these flags, just some more characters will be escaped using \&\f(CW\*(C`\euXXXX\*(C'\fR then before. .Sp Note that \s-1ISO\-8859\-1\-\s0\fIencoded\fR strings are not compatible with \s-1UTF\-8\s0 encoding, while ASCII-encoded strings are. That is because the \s-1ISO\-8859\-1\s0 encoding is \s-1NOT\s0 a subset of \s-1UTF\-8\s0 (despite the \s-1ISO\-8859\-1\s0 \fIcodeset\fR being a subset of Unicode), while \s-1ASCII\s0 is. .Sp Surprisingly, \f(CW\*(C`decode\*(C'\fR will ignore these flags and so treat all input values as governed by the \f(CW\*(C`utf8\*(C'\fR flag. If it is disabled, this allows you to decode \s-1ISO\-8859\-1\-\s0 and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode \s-1UTF\-8\s0 encoded strings. .Sp So neither \f(CW\*(C`latin1\*(C'\fR nor \f(CW\*(C`ascii\*(C'\fR are incompatible with the \f(CW\*(C`utf8\*(C'\fR flag \- they only govern when the \s-1JSON\s0 output engine escapes a character or not. .Sp The main use for \f(CW\*(C`latin1\*(C'\fR is to relatively efficiently store binary data as \s-1JSON,\s0 at the expense of breaking compatibility with most \s-1JSON\s0 decoders. .Sp The main use for \f(CW\*(C`ascii\*(C'\fR is to force the output to not contain characters with values > 127, which means you can interpret the resulting string as \s-1UTF\-8, ISO\-8859\-1, ASCII, KOI8\-R\s0 or most about any character set and 8\-bit\-encoding, and still get the same data structure back. This is useful when your channel for \s-1JSON\s0 transfer is not 8\-bit clean or the encoding might be mangled in between (e.g. in mail), and works because \s-1ASCII\s0 is a proper subset of most 8\-bit and multibyte encodings in use in the world. .SS "\s-1JSON\s0 and ECMAscript" .IX Subsection "JSON and ECMAscript" \&\s-1JSON\s0 syntax is based on how literals are represented in javascript (the not-standardised predecessor of ECMAscript) which is presumably why it is called \*(L"JavaScript Object Notation\*(R". .PP However, \s-1JSON\s0 is not a subset (and also not a superset of course) of ECMAscript (the standard) or javascript (whatever browsers actually implement). .PP If you want to use javascript's \f(CW\*(C`eval\*(C'\fR function to \*(L"parse\*(R" \s-1JSON,\s0 you might run into parse errors for valid \s-1JSON\s0 texts, or the resulting data structure might not be queryable: .PP One of the problems is that U+2028 and U+2029 are valid characters inside \&\s-1JSON\s0 strings, but are not allowed in ECMAscript string literals, so the following Perl fragment will not output something that can be guaranteed to be parsable by javascript's \f(CW\*(C`eval\*(C'\fR: .PP .Vb 1 \& use JSON::XS; \& \& print encode_json [chr 0x2028]; .Ve .PP The right fix for this is to use a proper \s-1JSON\s0 parser in your javascript programs, and not rely on \f(CW\*(C`eval\*(C'\fR (see for example Douglas Crockford's \&\fIjson2.js\fR parser). .PP If this is not an option, you can, as a stop-gap measure, simply encode to ASCII-only \s-1JSON:\s0 .PP .Vb 1 \& use JSON::XS; \& \& print JSON::XS\->new\->ascii\->encode ([chr 0x2028]); .Ve .PP Note that this will enlarge the resulting \s-1JSON\s0 text quite a bit if you have many non-ASCII characters. You might be tempted to run some regexes to only escape U+2028 and U+2029, e.g.: .PP .Vb 5 \& # DO NOT USE THIS! \& my $json = JSON::XS\->new\->utf8\->encode ([chr 0x2028]); \& $json =~ s/\exe2\ex80\exa8/\e\eu2028/g; # escape U+2028 \& $json =~ s/\exe2\ex80\exa9/\e\eu2029/g; # escape U+2029 \& print $json; .Ve .PP Note that \fIthis is a bad idea\fR: the above only works for U+2028 and U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing javascript implementations, however, have issues with other characters as well \- using \f(CW\*(C`eval\*(C'\fR naively simply \fIwill\fR cause problems. .PP Another problem is that some javascript implementations reserve some property names for their own purposes (which probably makes them non-ECMAscript-compliant). For example, Iceweasel reserves the \&\f(CW\*(C`_\|_proto_\|_\*(C'\fR property name for its own purposes. .PP If that is a problem, you could parse try to filter the resulting \s-1JSON\s0 output for these property strings, e.g.: .PP .Vb 1 \& $json =~ s/"_\|_proto_\|_"\es*:/"_\|_proto_\|_renamed":/g; .Ve .PP This works because \f(CW\*(C`_\|_proto_\|_\*(C'\fR is not valid outside of strings, so every occurrence of \f(CW\*(C`"_\|_proto_\|_"\es*:\*(C'\fR must be a string used as property name. .PP If you know of other incompatibilities, please let me know. .SS "\s-1JSON\s0 and \s-1YAML\s0" .IX Subsection "JSON and YAML" You often hear that \s-1JSON\s0 is a subset of \s-1YAML.\s0 This is, however, a mass hysteria(*) and very far from the truth (as of the time of this writing), so let me state it clearly: \fIin general, there is no way to configure \&\s-1JSON::XS\s0 to output a data structure as valid \s-1YAML\s0\fR that works in all cases. .PP If you really must use \s-1JSON::XS\s0 to generate \s-1YAML,\s0 you should use this algorithm (subject to change in future versions): .PP .Vb 2 \& my $to_yaml = JSON::XS\->new\->utf8\->space_after (1); \& my $yaml = $to_yaml\->encode ($ref) . "\en"; .Ve .PP This will \fIusually\fR generate \s-1JSON\s0 texts that also parse as valid \&\s-1YAML.\s0 Please note that \s-1YAML\s0 has hardcoded limits on (simple) object key lengths that \s-1JSON\s0 doesn't have and also has different and incompatible unicode character escape syntax, so you should make sure that your hash keys are noticeably shorter than the 1024 \*(L"stream characters\*(R" \s-1YAML\s0 allows and that you do not have characters with codepoint values outside the Unicode \s-1BMP\s0 (basic multilingual page). \s-1YAML\s0 also does not allow \f(CW\*(C`\e/\*(C'\fR sequences in strings (which \s-1JSON::XS\s0 does not \fIcurrently\fR generate, but other \s-1JSON\s0 generators might). .PP There might be other incompatibilities that I am not aware of (or the \s-1YAML\s0 specification has been changed yet again \- it does so quite often). In general you should not try to generate \s-1YAML\s0 with a \s-1JSON\s0 generator or vice versa, or try to parse \s-1JSON\s0 with a \s-1YAML\s0 parser or vice versa: chances are high that you will run into severe interoperability problems when you least expect it. .IP "(*)" 4 I have been pressured multiple times by Brian Ingerson (one of the authors of the \s-1YAML\s0 specification) to remove this paragraph, despite him acknowledging that the actual incompatibilities exist. As I was personally bitten by this \*(L"\s-1JSON\s0 is \s-1YAML\*(R"\s0 lie, I refused and said I will continue to educate people about these issues, so others do not run into the same problem again and again. After this, Brian called me a (quote)\fIcomplete and worthless idiot\fR(unquote). .Sp In my opinion, instead of pressuring and insulting people who actually clarify issues with \s-1YAML\s0 and the wrong statements of some of its proponents, I would kindly suggest reading the \s-1JSON\s0 spec (which is not that difficult or long) and finally make \s-1YAML\s0 compatible to it, and educating users about the changes, instead of spreading lies about the real compatibility for many \fIyears\fR and trying to silence people who point out that it isn't true. .Sp Addendum/2009: the \s-1YAML 1.2\s0 spec is still incompatible with \s-1JSON,\s0 even though the incompatibilities have been documented (and are known to Brian) for many years and the spec makes explicit claims that \s-1YAML\s0 is a superset of \s-1JSON.\s0 It would be so easy to fix, but apparently, bullying people and corrupting userdata is so much easier. .SS "\s-1SPEED\s0" .IX Subsection "SPEED" It seems that \s-1JSON::XS\s0 is surprisingly fast, as shown in the following tables. They have been generated with the help of the \f(CW\*(C`eg/bench\*(C'\fR program in the \s-1JSON::XS\s0 distribution, to make it easy to compare on your own system. .PP First comes a comparison between various modules using a very short single-line \s-1JSON\s0 string (also available at ). .PP .Vb 3 \& {"method": "handleMessage", "params": ["user1", \& "we were just talking"], "id": null, "array":[1,11,234,\-5,1e5,1e7, \& 1, 0]} .Ve .PP It shows the number of encodes/decodes per second (\s-1JSON::XS\s0 uses the functional interface, while \s-1JSON::XS/2\s0 uses the \s-1OO\s0 interface with pretty-printing and hashkey sorting enabled, \s-1JSON::XS/3\s0 enables shrink. \s-1JSON::DWIW/DS\s0 uses the deserialise function, while \s-1JSON::DWIW::FJ\s0 uses the from_json method). Higher is better: .PP .Vb 11 \& module | encode | decode | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-| \& JSON::DWIW/DS | 86302.551 | 102300.098 | \& JSON::DWIW/FJ | 86302.551 | 75983.768 | \& JSON::PP | 15827.562 | 6638.658 | \& JSON::Syck | 63358.066 | 47662.545 | \& JSON::XS | 511500.488 | 511500.488 | \& JSON::XS/2 | 291271.111 | 388361.481 | \& JSON::XS/3 | 361577.931 | 361577.931 | \& Storable | 66788.280 | 265462.278 | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .PP That is, \s-1JSON::XS\s0 is almost six times faster than \s-1JSON::DWIW\s0 on encoding, about five times faster on decoding, and over thirty to seventy times faster than \s-1JSON\s0's pure perl implementation. It also compares favourably to Storable for small amounts of data. .PP Using a longer test string (roughly 18KB, generated from Yahoo! Locals search \s-1API\s0 (). .PP .Vb 11 \& module | encode | decode | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-| \& JSON::DWIW/DS | 1647.927 | 2673.916 | \& JSON::DWIW/FJ | 1630.249 | 2596.128 | \& JSON::PP | 400.640 | 62.311 | \& JSON::Syck | 1481.040 | 1524.869 | \& JSON::XS | 20661.596 | 9541.183 | \& JSON::XS/2 | 10683.403 | 9416.938 | \& JSON::XS/3 | 20661.596 | 9400.054 | \& Storable | 19765.806 | 10000.725 | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .PP Again, \s-1JSON::XS\s0 leads by far (except for Storable which non-surprisingly decodes a bit faster). .PP On large strings containing lots of high Unicode characters, some modules (such as \s-1JSON::PC\s0) seem to decode faster than \s-1JSON::XS,\s0 but the result will be broken due to missing (or wrong) Unicode handling. Others refuse to decode or encode properly, so it was impossible to prepare a fair comparison table for that case. .SH "SECURITY CONSIDERATIONS" .IX Header "SECURITY CONSIDERATIONS" When you are using \s-1JSON\s0 in a protocol, talking to untrusted potentially hostile creatures requires relatively few measures. .PP First of all, your \s-1JSON\s0 decoder should be secure, that is, should not have any buffer overflows. Obviously, this module should ensure that and I am trying hard on making that true, but you never know. .PP Second, you need to avoid resource-starving attacks. That means you should limit the size of \s-1JSON\s0 texts you accept, or make sure then when your resources run out, that's just fine (e.g. by using a separate process that can crash safely). The size of a \s-1JSON\s0 text in octets or characters is usually a good indication of the size of the resources required to decode it into a Perl structure. While \s-1JSON::XS\s0 can check the size of the \s-1JSON\s0 text, it might be too late when you already have it in memory, so you might want to check the size before you accept the string. .PP Third, \s-1JSON::XS\s0 recurses using the C stack when decoding objects and arrays. The C stack is a limited resource: for instance, on my amd64 machine with 8MB of stack size I can decode around 180k nested arrays but only 14k nested \s-1JSON\s0 objects (due to perl itself recursing deeply on croak to free the temporary). If that is exceeded, the program crashes. To be conservative, the default nesting limit is set to 512. If your process has a smaller stack, you should adjust this setting accordingly with the \&\f(CW\*(C`max_depth\*(C'\fR method. .PP Something else could bomb you, too, that I forgot to think of. In that case, you get to keep the pieces. I am always open for hints, though... .PP Also keep in mind that \s-1JSON::XS\s0 might leak contents of your Perl data structures in its error messages, so when you serialise sensitive information you might want to make sure that exceptions thrown by \s-1JSON::XS\s0 will not end up in front of untrusted eyes. .PP If you are using \s-1JSON::XS\s0 to return packets to consumption by JavaScript scripts in a browser you should have a look at to see whether you are vulnerable to some common attack vectors (which really are browser design bugs, but it is still you who will have to deal with it, as major browser developers care only for features, not about getting security right). .ie n .SS """\s-1OLD"" VS. ""NEW"" JSON\s0 (\s-1RFC4627 VS. RFC7159\s0)" .el .SS "``\s-1OLD'' VS. ``NEW'' JSON\s0 (\s-1RFC4627 VS. RFC7159\s0)" .IX Subsection "OLD VS. NEW JSON (RFC4627 VS. RFC7159)" \&\s-1JSON\s0 originally required \s-1JSON\s0 texts to represent an array or object \- scalar values were explicitly not allowed. This has changed, and versions of \s-1JSON::XS\s0 beginning with \f(CW4.0\fR reflect this by allowing scalar values by default. .PP One reason why one might not want this is that this removes a fundamental property of \s-1JSON\s0 texts, namely that they are self-delimited and self-contained, or in other words, you could take any number of \*(L"old\*(R" \&\s-1JSON\s0 texts and paste them together, and the result would be unambiguously parseable: .PP .Vb 1 \& [1,3]{"k":5}[][null] # four JSON texts, without doubt .Ve .PP By allowing scalars, this property is lost: in the following example, is this one \s-1JSON\s0 text (the number 12) or two \s-1JSON\s0 texts (the numbers 1 and 2): .PP .Vb 1 \& 12 # could be 12, or 1 and 2 .Ve .PP Another lost property of \*(L"old\*(R" \s-1JSON\s0 is that no lookahead is required to know the end of a \s-1JSON\s0 text, i.e. the \s-1JSON\s0 text definitely ended at the last \f(CW\*(C`]\*(C'\fR or \f(CW\*(C`}\*(C'\fR character, there was no need to read extra characters. .PP For example, a viable network protocol with \*(L"old\*(R" \s-1JSON\s0 was to simply exchange \s-1JSON\s0 texts without delimiter. For \*(L"new\*(R" \s-1JSON,\s0 you have to use a suitable delimiter (such as a newline) after every \s-1JSON\s0 text or ensure you never encode/decode scalar values. .PP Most protocols do work by only transferring arrays or objects, and the easiest way to avoid problems with the \*(L"new\*(R" \s-1JSON\s0 definition is to explicitly disallow scalar values in your encoder and decoder: .PP .Vb 1 \& $json_coder = JSON::XS\->new\->allow_nonref (0) .Ve .PP This is a somewhat unhappy situation, and the blame can fully be put on \&\s-1JSON\s0's inmventor, Douglas Crockford, who unilaterally changed the format in 2006 without consulting the \s-1IETF,\s0 forcing the \s-1IETF\s0 to either fork the format or go with it (as I was told, the \s-1IETF\s0 wasn't amused). .SH "RELATIONSHIP WITH I\-JSON" .IX Header "RELATIONSHIP WITH I-JSON" \&\s-1JSON\s0 is a somewhat sloppily-defined format \- it carries around obvious Javascript baggage, such as not really defining number range, probably because Javascript only has one type of numbers: \s-1IEEE 64\s0 bit floats (\*(L"binary64\*(R"). .PP For this reaosn, \s-1RFC7493\s0 defines \*(L"Internet \s-1JSON\*(R",\s0 which is a restricted subset of \s-1JSON\s0 that is supposedly more interoperable on the internet. .PP While \f(CW\*(C`JSON::XS\*(C'\fR does not offer specific support for I\-JSON, it of course accepts valid I\-JSON and by default implements some of the limitations of I\-JSON, such as parsing numbers as perl numbers, which are usually a superset of binary64 numbers. .PP To generate I\-JSON, follow these rules: .IP "\(bu" 4 always generate \s-1UTF\-8\s0 .Sp I\-JSON must be encoded in \s-1UTF\-8,\s0 the default for \f(CW\*(C`encode_json\*(C'\fR. .IP "\(bu" 4 numbers should be within \s-1IEEE 754\s0 binary64 range .Sp Basically all existing perl installations use binary64 to represent floating point numbers, so all you need to do is to avoid large integers. .IP "\(bu" 4 objects must not have duplicate keys .Sp This is trivially done, as \f(CW\*(C`JSON::XS\*(C'\fR does not allow duplicate keys. .IP "\(bu" 4 do not generate scalar \s-1JSON\s0 texts, use \f(CW\*(C`\->allow_nonref (0)\*(C'\fR .Sp I\-JSON strongly requests you to only encode arrays and objects into \s-1JSON.\s0 .IP "\(bu" 4 times should be strings in \s-1ISO 8601\s0 format .Sp There are a myriad of modules on \s-1CPAN\s0 dealing with \s-1ISO 8601\s0 \- search for \&\f(CW\*(C`ISO8601\*(C'\fR on \s-1CPAN\s0 and use one. .IP "\(bu" 4 encode binary data as base64 .Sp While it's tempting to just dump binary data as a string (and let \&\f(CW\*(C`JSON::XS\*(C'\fR do the escaping), for I\-JSON, it's \fIrecommended\fR to encode binary data as base64. .PP There are some other considerations \- read \s-1RFC7493\s0 for the details if interested. .SH "INTEROPERABILITY WITH OTHER MODULES" .IX Header "INTEROPERABILITY WITH OTHER MODULES" \&\f(CW\*(C`JSON::XS\*(C'\fR uses the Types::Serialiser module to provide boolean constants. That means that the \s-1JSON\s0 true and false values will be comaptible to true and false values of other modules that do the same, such as \s-1JSON::PP\s0 and \s-1CBOR::XS\s0. .SH "INTEROPERABILITY WITH OTHER JSON DECODERS" .IX Header "INTEROPERABILITY WITH OTHER JSON DECODERS" As long as you only serialise data that can be directly expressed in \s-1JSON,\s0 \&\f(CW\*(C`JSON::XS\*(C'\fR is incapable of generating invalid \s-1JSON\s0 output (modulo bugs, but \f(CW\*(C`JSON::XS\*(C'\fR has found more bugs in the official \s-1JSON\s0 testsuite (1) than the official \s-1JSON\s0 testsuite has found in \f(CW\*(C`JSON::XS\*(C'\fR (0)). .PP When you have trouble decoding \s-1JSON\s0 generated by this module using other decoders, then it is very likely that you have an encoding mismatch or the other decoder is broken. .PP When decoding, \f(CW\*(C`JSON::XS\*(C'\fR is strict by default and will likely catch all errors. There are currently two settings that change this: \f(CW\*(C`relaxed\*(C'\fR makes \f(CW\*(C`JSON::XS\*(C'\fR accept (but not generate) some non-standard extensions, and \f(CW\*(C`allow_tags\*(C'\fR will allow you to encode and decode Perl objects, at the cost of not outputting valid \s-1JSON\s0 anymore. .SS "\s-1TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS\s0" .IX Subsection "TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS" When you use \f(CW\*(C`allow_tags\*(C'\fR to use the extended (and also nonstandard and invalid) \s-1JSON\s0 syntax for serialised objects, and you still want to decode the generated When you want to serialise objects, you can run a regex to replace the tagged syntax by standard \s-1JSON\s0 arrays (it only works for \&\*(L"normal\*(R" package names without comma, newlines or single colons). First, the readable Perl version: .PP .Vb 2 \& # if your FREEZE methods return no values, you need this replace first: \& $json =~ s/\e( \es* (" (?: [^\e\e":,]+|\e\e.|::)* ") \es* \e) \es* \e[\es*\e]/[$1]/gx; \& \& # this works for non\-empty constructor arg lists: \& $json =~ s/\e( \es* (" (?: [^\e\e":,]+|\e\e.|::)* ") \es* \e) \es* \e[/[$1,/gx; .Ve .PP And here is a less readable version that is easy to adapt to other languages: .PP .Vb 1 \& $json =~ s/\e(\es*("([^\e\e":,]+|\e\e.|::)*")\es*\e)\es*\e[/[$1,/g; .Ve .PP Here is an ECMAScript version (same regex): .PP .Vb 1 \& json = json.replace (/\e(\es*("([^\e\e":,]+|\e\e.|::)*")\es*\e)\es*\e[/g, "[$1,"); .Ve .PP Since this syntax converts to standard \s-1JSON\s0 arrays, it might be hard to distinguish serialised objects from normal arrays. You can prepend a \&\*(L"magic number\*(R" as first array element to reduce chances of a collision: .PP .Vb 1 \& $json =~ s/\e(\es*("([^\e\e":,]+|\e\e.|::)*")\es*\e)\es*\e[/["XU1peReLzT4ggEllLanBYq4G9VzliwKF",$1,/g; .Ve .PP And after decoding the \s-1JSON\s0 text, you could walk the data structure looking for arrays with a first element of \&\f(CW\*(C`XU1peReLzT4ggEllLanBYq4G9VzliwKF\*(C'\fR. .PP The same approach can be used to create the tagged format with another encoder. First, you create an array with the magic string as first member, the classname as second, and constructor arguments last, encode it as part of your \s-1JSON\s0 structure, and then: .PP .Vb 1 \& $json =~ s/\e[\es*"XU1peReLzT4ggEllLanBYq4G9VzliwKF"\es*,\es*("([^\e\e":,]+|\e\e.|::)*")\es*,/($1)[/g; .Ve .PP Again, this has some limitations \- the magic string must not be encoded with character escapes, and the constructor arguments must be non-empty. .SH "(I\-)THREADS" .IX Header "(I-)THREADS" This module is \fInot\fR guaranteed to be ithread (or \s-1MULTIPLICITY\-\s0) safe and there are no plans to change this. Note that perl's builtin so-called threads/ithreads are officially deprecated and should not be used. .SH "THE PERILS OF SETLOCALE" .IX Header "THE PERILS OF SETLOCALE" Sometimes people avoid the Perl locale support and directly call the system's setlocale function with \f(CW\*(C`LC_ALL\*(C'\fR. .PP This breaks both perl and modules such as \s-1JSON::XS,\s0 as stringification of numbers no longer works correctly (e.g. \f(CW\*(C`$x = 0.1; print "$x"+1\*(C'\fR might print \f(CW1\fR, and \s-1JSON::XS\s0 might output illegal \s-1JSON\s0 as \s-1JSON::XS\s0 relies on perl to stringify numbers). .PP The solution is simple: don't call \f(CW\*(C`setlocale\*(C'\fR, or use it for only those categories you need, such as \f(CW\*(C`LC_MESSAGES\*(C'\fR or \f(CW\*(C`LC_CTYPE\*(C'\fR. .PP If you need \f(CW\*(C`LC_NUMERIC\*(C'\fR, you should enable it only around the code that actually needs it (avoiding stringification of numbers), and restore it afterwards. .SH "SOME HISTORY" .IX Header "SOME HISTORY" At the time this module was created there already were a number of \s-1JSON\s0 modules available on \s-1CPAN,\s0 so what was the reason to write yet another \&\s-1JSON\s0 module? While it seems there are many \s-1JSON\s0 modules, none of them correctly handled all corner cases, and in most cases their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons. .PP Beginning with version 2.0 of the \s-1JSON\s0 module, when both \s-1JSON\s0 and \&\s-1JSON::XS\s0 are installed, then \s-1JSON\s0 will fall back on \s-1JSON::XS\s0 (this can be overridden) with no overhead due to emulation (by inheriting constructor and methods). If \s-1JSON::XS\s0 is not available, it will fall back to the compatible \s-1JSON::PP\s0 module as backend, so using \s-1JSON\s0 instead of \s-1JSON::XS\s0 gives you a portable \s-1JSON API\s0 that can be fast when you need it and doesn't require a C compiler when that is a problem. .PP Somewhere around version 3, this module was forked into \&\f(CW\*(C`Cpanel::JSON::XS\*(C'\fR, because its maintainer had serious trouble understanding \s-1JSON\s0 and insisted on a fork with many bugs \*(L"fixed\*(R" that weren't actually bugs, while spreading \s-1FUD\s0 about this module without actually giving any details on his accusations. You be the judge, but in my personal opinion, if you want quality, you will stay away from dangerous forks like that. .SH "BUGS" .IX Header "BUGS" While the goal of this module is to be correct, that unfortunately does not mean it's bug-free, only that I think its design is bug-free. If you keep reporting bugs they will be fixed swiftly, though. .PP Please refrain from using rt.cpan.org or any other bug reporting service. I put the contact address into my modules for a reason. .SH "SEE ALSO" .IX Header "SEE ALSO" The \fIjson_xs\fR command line utility for quick experiments. .SH "AUTHOR" .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://home.schmorp.de/ .Ve PK!D% % man/man3/JSON::XS::Boolean.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "XS::Boolean 3" .TH XS::Boolean 3 "2013-10-29" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" JSON::XS::Boolean \- dummy module providing JSON::XS::Boolean .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& # do not "use" yourself .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module exists only to provide overload resolution for Storable and similar modules. It's only needed for compatibility with data serialised (by other modules such as Storable) that was decoded by \s-1JSON::XS\s0 versions before 3.0. .PP Since 3.0, JSON::PP::Boolean has replaced it. Support for JSON::XS::Boolean will be removed in a future release. .SH "AUTHOR" .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://home.schmorp.de/ .Ve PK! Y Y!man/man3/POD2::DE::local::lib.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "POD2::DE::local::lib 3" .TH POD2::DE::local::lib 3 "2019-11-14" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" local::lib~[de] \- Erschaffen und benutzen von Perl Modulen in einem lokalen lib/ Verzeichnis mit PERL5LIB .SH "SYNOPSIS" .IX Header "SYNOPSIS" Im Code \- .PP .Vb 1 \& use local::lib; # Benutzt das Verzeichnis ~/perl5 zum anlegen des lokalen lib/ Verzeichnisses \& \& use local::lib \*(Aq~/foo\*(Aq; # das selbe, aber mit ~/foo \& \& # Oder... \& use FindBin; \& use local::lib "$FindBin::Bin/../support"; # Applikationsspezifische Sammlung von Modulen .Ve .PP Von der Shell \- .PP .Vb 2 \& # Installiert LWP und alle notwendigen Abhängigkeiten in das \*(Aq~/perl5\*(Aq Verzeichnis \& perl \-MCPAN \-Mlocal::lib \-e \*(AqCPAN::install(LWP)\*(Aq \& \& # Gibt die Shell Kommandos aus um die Umgebung vorzubereiten \& $ perl \-Mlocal::lib \& export PERL_MB_OPT=\*(Aq\-\-install_base /home/username/perl5\*(Aq \& export PERL_MM_OPT=\*(AqINSTALL_BASE=/home/username/perl5\*(Aq \& export PERL5LIB=\*(Aq/home/username/perl5/lib/perl5/i386\-linux:/home/username/perl5/lib/perl5\*(Aq \& export PATH="/home/username/perl5/bin:$PATH" .Ve .SS "Die Bootstrapping Methode" .IX Subsection "Die Bootstrapping Methode" Ein typischer Weg um local::lib zu benutzen ist die sogenannte \*(L"Bootstrapping\*(R" 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. .PP 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 \s-1CPAN\s0 weiterhin im System installiert und auch Perl Skripte die du startest würden das von local::lib erstellte lib/ Verzeichnis nicht nutzen. .PP Standardmäßig installiert sich local::lib in ~/perl5. .PP Windows Benutzern müssen ausserdem dies hier lesen: \&\*(L"Unterschiede bei Benutzung dieses Module mit Win32\*(R". .PP 1. Lade das Tar-Archiv von \s-1CPAN\s0 runter (Suche nach \*(L"Download\*(R" auf der \s-1CPAN\s0 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. .PP 2. Starte in dem entstandenen Verzeichnis folgenden Befehl: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap .Ve .PP Wenn das System dir vorschlägt gewisse Dinge eigenständig zu konfigurieren ist es in fast allen Fällen vollkommen in Ordnung einfach \*(L"yes\*(R" zu antworten. .PP Falls du local::lib nicht in das Standard Verzeichnis installieren willst, musst du dieses Verzeichnis als Parameter angeben: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap=~/foo .Ve .PP 3. Danach folgenden Befehl starten: (local::lib erwartet make auf dem System) .PP .Vb 1 \& make test && make install .Ve .PP 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: .PP .Vb 1 \& echo \*(Aqeval $(perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib)\*(Aq >>~/.bashrc .Ve .PP Wenn du C Shell benutzt, du kannst das gleiche hiermit erreichen: .PP .Vb 4 \& /bin/csh \& echo $SHELL \& /bin/csh \& perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib >> ~/.cshrc .Ve .PP 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: .PP .Vb 1 \& echo \*(Aqeval $(perl \-I$HOME/foo/lib/perl5 \-Mlocal::lib=$HOME/foo)\*(Aq >>~/.bashrc .Ve .PP 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 \f(CW\*(C`. ~/.bashrc\*(C'\fR, und in C Shell würde man es mit: \&\f(CW\*(C`source ~/.cshrc\*(C'\fR mit. .PP Wenn du eine sehr langsames System hast, oder du unter drakonischen Regulierungen des Plattenplatz leben musst, kann man die automatische Generierung der manpages vom \s-1POD\s0 bei der Installation des Moduls deaktivieren beim bootstrapping mit dem \f(CW\*(C`\-\-no\-manpages\*(C'\fR Parameter: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap \-\-no\-manpages .Ve .PP 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: .PP .Vb 4 \& 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 ... .Ve .PP Für mehrere Umgebungen in dieser Form brauch man eine Modifikation in der Benutzung von \f(CW\*(C`use FindBin\*(C'\fR in dem \*(L"Im Code\*(R" Beispiel oben. Wenn du sowas machst, und du hast damit z.B. Perl Module nach \f(CW\*(C`~/mydir1/lib\*(C'\fR installiert und du hast ein Script in \f(CW\*(C`~/mydir1/scripts/myscript.pl\*(C'\fR, du musst dort angeben das die Module die es braucht im Verzeichnis \f(CW\*(C`~/mydir1/lib\*(C'\fR liegen. .PP In \f(CW\*(C`~/mydir1/scripts/myscript.pl\*(C'\fR steht dann: .PP .Vb 5 \& 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 .Ve .PP Setze das vor jeden \s-1BEGIN\s0 { ... } Block der die Module braucht die du installiert hast. .SS "Unterschiede bei Benutzung dieses Module mit Win32" .IX Subsection "Unterschiede bei Benutzung dieses Module mit Win32" Um die nötigen Umgebungsvariablen für diese Variablen in der derzeitigen Sitzung mit \f(CW\*(C`CMD.EXE\*(C'\fR zu setzen, kann man folgendes kommando nutzen: .PP .Vb 5 \& C:\e>perl \-Mlocal::lib \& set PERL_MB_OPT=\-\-install_base C:\eDOCUME~1\eADMINI~1\eperl5 \& set PERL_MM_OPT=INSTALL_BASE=C:\eDOCUME~1\eADMINI~1\eperl5 \& set PERL5LIB=C:\eDOCUME~1\eADMINI~1\eperl5\elib\eperl5;C:\eDOCUME~1\eADMINI~1\eperl5\elib\eperl5\eMSWin32\-x86\-multi\-thread \& set PATH=C:\eDOCUME~1\eADMINI~1\eperl5\ebin;%PATH% \& \& ### Um die Umgebungsvariablen für diese Shell alleine zu setzen \& C:\e>perl \-Mlocal::lib > %TEMP%\etmp.bat && %TEMP%\etmp.bat && del %TEMP%\etemp.bat \& ### anstelle von $(perl \-Mlocal::lib=./) in bash. .Ve .PP Wenn du willst das die Umgebungsvariablen dauerhaft gesetzt sind, musst du diese in Systemsteuerung / System dauerhaft selber eintragen oder App::local::lib::Win32Helper benutzen. .PP Die \*(L"~\*(R" wird übersetzt zu dem Benutzer Profil Verzeichnis (das Verzeichnis was beim User als \*(L"Dokumente und Einstellungen\*(R" bekannt ist unter Windows \s-1XP\s0 und vorher oder das \*(L"Benutzer\*(R" Verzeichnis bei Windows Vista und später), solange \&\f(CW$ENV\fR{\s-1HOME\s0} 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. .SH "GRUNDPRINZIP" .IX Header "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. .PP local::lib löst dieses Problem, es erlaubt dir dein komplett eigenes Verzeichnis für deine \s-1CPAN\s0 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. .PP 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. .SH "BESCHREIBUNG" .IX Header "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 \f(CW\*(C`SHELL\*(C'\fR angegeben hat, um dann direkt passend in die entsprechenden Konfigurationsdateien der Shell einfügt zu werden. .PP Weitergehend ist local::lib in der Lage Module zu nutzen die nicht im standardmäßigen \f(CW@INC\fR 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. .PP Beim Import setzt local::lib die folgenden Umgebungsvariablen zu den nötigen Werten: .IP "\s-1PERL_MB_OPT\s0" 4 .IX Item "PERL_MB_OPT" .PD 0 .IP "\s-1PERL_MM_OPT\s0" 4 .IX Item "PERL_MM_OPT" .IP "\s-1PERL5LIB\s0" 4 .IX Item "PERL5LIB" .IP "\s-1PATH\s0" 4 .IX Item "PATH" .PD Am \s-1PATH\s0 wird natürlich angehangen, und nicht ersetzt. .PP Diese Werte sind dann verfügbar für jeden Code der danach importiert wurde. .SH "ERSTELLEN EINES EIGENSTÄNDIGE SAMMLUNG VON MODULEN" .IX Header "ERSTELLEN EINES EIGENSTÄNDIGE SAMMLUNG VON MODULEN" Mit lib::core::only 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). .SH "METHODEN" .IX Header "METHODEN" .SS "ensure_dir_structure_for" .IX Subsection "ensure_dir_structure_for" .ie n .IP "Parameter: $path" 4 .el .IP "Parameter: \f(CW$path\fR" 4 .IX Item "Parameter: $path" .PD 0 .IP "Rückgabewert: Keiner" 4 .IX Item "Rückgabewert: Keiner" .PD .PP Versucht den angegebenen Pfad anzulegen, mit allen nötigen drüberliegenden Verzeichnissen. Im Fehlerfall wird eine Exception geworfen. .SS "print_environment_vars_for" .IX Subsection "print_environment_vars_for" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .IP "Rückgabewert: Keiner" 4 .IX Item "Rückgabewert: Keiner" .PD .PP Gibt die Umgebungsvariablen aus, die benötigt werden um den angegebenen Pfad als Basis Verzeichnis zu nutzen. .SS "build_environment_vars_for" .IX Subsection "build_environment_vars_for" .ie n .IP "Parameter: $pfad, $interpolate" 4 .el .IP "Parameter: \f(CW$pfad\fR, \f(CW$interpolate\fR" 4 .IX Item "Parameter: $pfad, $interpolate" .PD 0 .IP "Rückgabewert: \e%umgebungs_variablen" 4 .IX Item "Rückgabewert: %umgebungs_variablen" .PD .PP Gibt ein Hash zurück mit den Variablen die nötig sind in den Umgebungsvariablen um eine Installation in dem gegebenen Pfad zu benutzen. .SS "setup_env_hash_for" .IX Subsection "setup_env_hash_for" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .IP "Rückgabewert: Keiner" 4 .IX Item "Rückgabewert: Keiner" .PD .PP Setzt die \f(CW%ENV\fR Einträge basierend auf dem Aufruf von \&\*(L"build_environment_vars_for\*(R". .SS "install_base_perl_path" .IX Subsection "install_base_perl_path" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $module_installations_pfad" 4 .el .IP "Rückgabewert: \f(CW$module_installations_pfad\fR" 4 .IX Item "Rückgabewert: $module_installations_pfad" .PD .PP Gibt den Pfad zurück der benutzt wird um Perl Module zu installieren bei dem gegebenen Pfad als Basis. Prinzipiell wird nur \f(CW\*(C`lib\*(C'\fR und \f(CW\*(C`perl5\*(C'\fR als Pfadelemente angehangen. .SS "install_base_arch_path" .IX Subsection "install_base_arch_path" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $architektur_module_installations_pfad" 4 .el .IP "Rückgabewert: \f(CW$architektur_module_installations_pfad\fR" 4 .IX Item "Rückgabewert: $architektur_module_installations_pfad" .PD .PP 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"install_base_perl_path\*(R" zurückgibt, and appends the value of \&\f(CW$Config{archname}\fR.asis. .SS "install_base_bin_path" .IX Subsection "install_base_bin_path" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $ausfuehrbare_programme_installations_pfad" 4 .el .IP "Rückgabewert: \f(CW$ausfuehrbare_programme_installations_pfad\fR" 4 .IX Item "Rückgabewert: $ausfuehrbare_programme_installations_pfad" .PD .PP Gibt den Pfad zurück, wo ausführbare Programme installiert werden, basierend auf der Basis des angegebenen Pfad. Basierend auf \*(L"install_base_perl_path\*(R" Rückgabewert, hängt diese Methode noch \f(CW\*(C`bin\*(C'\fR an. .SS "resolve_empty_path" .IX Subsection "resolve_empty_path" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $basis_pfad" 4 .el .IP "Rückgabewert: \f(CW$basis_pfad\fR" 4 .IX Item "Rückgabewert: $basis_pfad" .PD .PP Erstellt und gibt zurück den Pfad der benutzt wird als Basis zur Installation der Module. Standardmäßig dies ist \f(CW\*(C`~/perl5\*(C'\fR. .ie n .SS "resolve_home_path( $path )" .el .SS "resolve_home_path( \f(CW$path\fP )" .IX Subsection "resolve_home_path( $path )" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $home" 4 .el .IP "Rückgabewert: \f(CW$home\fR" 4 .IX Item "Rückgabewert: $home" .PD .PP Versucht das Home Verzeichnis vom aktullen User zu finden. Es wird eine Exception geworfen, wenn kein Home Verzeichnis ermittelt werden konnte. .SS "resolve_relative_path" .IX Subsection "resolve_relative_path" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $absoluter_pfad" 4 .el .IP "Rückgabewert: \f(CW$absoluter_pfad\fR" 4 .IX Item "Rückgabewert: $absoluter_pfad" .PD .PP Macht aus dem angegebenen Pfad einen absoluten Pfad. .SS "resolve_path" .IX Subsection "resolve_path" .ie n .IP "Parameter: $pfad" 4 .el .IP "Parameter: \f(CW$pfad\fR" 4 .IX Item "Parameter: $pfad" .PD 0 .ie n .IP "Rückgabewert: $absoluter_pfad" 4 .el .IP "Rückgabewert: \f(CW$absoluter_pfad\fR" 4 .IX Item "Rückgabewert: $absoluter_pfad" .PD .PP 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"resolve_empty_path\*(R", \&\*(L"resolve_home_path\*(R", \*(L"resolve_relative_path\*(R". Der daraus resultierende Pfad wird zu \*(L"resolve_empty_path\*(R" übergeben, dessen Resultat dann weitergegeben wird an \*(L"resolve_home_path\*(R", wessen Resultat dann weitergegeben wird an \*(L"resolve_relative_path\*(R". Dieses Resultat wird dann final an \*(L"resolve_path\*(R" übergeben, welches dann den Rückgabewert stellt. .SH "EINE WARNUNG VOR UNINST=1" .IX Header "EINE WARNUNG VOR UNINST=1" Wenn man local::lib in Kombination mit \*(L"make install UNINST=1\*(R" 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 \*(L"make install UNINST=1\*(R" und local::lib nur gleichzeitig benutzt wenn man sehr sicher darüber ist welche Konsequenzen einem entgegenkommen. .SH "EINSCHRÄNKUNGEN" .IX Header "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 \fBnach\fR 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 \s-1CPAN\s0 Programm nicht mehr möglich ist. .PP Die Shell Erkennung ist sehr primitiv. Derzeit ist es so das alles was \*(L"csh\*(R" im Namen hat auch als C Shell eingeordnet wird, und alles andere wird als Bourne Shell betrachet, ausser auf Win32 Systemen. Wenn die \f(CW\*(C`SHELL\*(C'\fR Variable nicht gesetzt ist, eine Bourne Shell wird angenommen. .PP Bootstrap ist leider ein Hack, und wird auf jedenfall \s-1CPAN\s0.pm benutzen für ExtUtils::MakeMaker, auch wenn \s-1CPANPLUS\s0 installiert ist. .PP Es setzt definitiv \s-1PERL5LIB, PERL_MM_OPT\s0 und \s-1PERL_MB_OPT\s0 neu und vernichtet jeden Wert der vorher gesetzt war. .PP Es sollte vielleicht eine automatische Korrektur der \s-1CPAN\s0 Config machen, wenn das nicht schon gemacht wurde. .PP \&\*(L"Patches Welcome\*(R" \- Patches sind immer willkommen beim Autor oder den anderen Mitwirkenden. .PP Auf Win32 Systemen werden die Umgebungsvariablen nicht direkt in die Registrierung geschrieben damit sie auch nach dem Neustarten erhalten bleiben. .SH "FEHLERANALYSE" .IX Header "FEHLERANALYSE" Wenn du local::lib konfiguriert hast \s-1CPAN\s0 Module in deinem Home Verzeichnis zu installieren, und du danach versuchst mit \f(CW\*(C`cpan \-i Foo::Bar\*(C'\fR ein Modul zu installieren, und dabei einen Fehler bekommst, wie: \f(CW\*(C`Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64\-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm\*(C'\fR und in der installationsausgabe steht irgendwo ein Fehler der sagt \f(CW\*(C`\*(AqINSTALL_BASE\*(Aq is not a known MakeMaker parameter name\*(C'\fR, dann hast du aus irgendeinem Grund dein neue Version von ExtUtils::MakeMaker verloren. .PP Um dies zu korrigieren, einfach nochmal die bootstrapping Methode laufen lassen, wie oben beschrieben. .PP Dann starte \f(CW\*(C`rm \-r ~/.cpan/build/Foo\-Bar*\*(C'\fR .PP Abschliessend dann nochmal mit \f(CW\*(C`cpan \-i Foo::Bar\*(C'\fR installieren und die Probleme sollten verschwunden sein. .SH "UMGEBUNGSVARIABLEN" .IX Header "UMGEBUNGSVARIABLEN" .IP "\s-1SHELL\s0" 4 .IX Item "SHELL" .PD 0 .IP "\s-1COMSPEC\s0" 4 .IX Item "COMSPEC" .PD local::lib schaut in die \f(CW\*(C`SHELL\*(C'\fR Umgebungsvariable um die korrekten Kommandos zu der Shell Konfiguration hinzuzufügen. .Sp Auf Win32 Systemen, \f(CW\*(C`COMSPEC\*(C'\fR wird auch analysiert. .SH "SUPPORT" .IX Header "SUPPORT" \&\s-1IRC:\s0 .PP .Vb 1 \& Wir sind im Channel #local\-lib auf dem Server irc.perl.org. .Ve .SH "AUTOR DER ÜBERSETZUNG" .IX Header "AUTOR DER ÜBERSETZUNG" Torsten Raudssus http://www.raudssus.de/ .SH "URHEBERRECHT" .IX Header "URHEBERRECHT" Copyright (c) 2007 \- 2010 von den local::lib \*(L"\s-1AUTHOR\*(R"\s0 in local::lib und \*(L"\s-1CONTRIBUTORS\*(R"\s0 in local::lib aufgelistet in local::lib. .SH "LIZENZ" .IX Header "LIZENZ" Diese Sammlung ist freie Software und kann unter der selben Lizenz verbreitet werden wie Perl selber. PK!+YҚXX$man/man3/POD2::PT_BR::local::lib.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "POD2::PT_BR::local::lib 3" .TH POD2::PT_BR::local::lib 3 "2019-11-14" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" local::lib~[pt_br] \- crie e use um diretório lib/ local para módulos perl com PERL5LIB .SH "SINOPSE" .IX Header "SINOPSE" No código \- .PP .Vb 1 \& use local::lib; # configura um lib local em ~/perl5 \& \& use local::lib \*(Aq~/foo\*(Aq; # idem, mas ~/foo \& \& # Ou... \& use FindBin; \& use local::lib "$FindBin::Bin/../suporte"; # bibliotecas de suporte locais à aplicação .Ve .PP Pela linha de comando (shell) \- .PP .Vb 2 \& # Instala o LWP e suas dependências não encontradas no diretório \*(Aq~/perl5\*(Aq \& perl \-MCPAN \-Mlocal::lib \-e \*(AqCPAN::install(LWP)\*(Aq \& \& # Apenas exibe alguns comandos úteis para a shell \& $ perl \-Mlocal::lib \& export PERL_MB_OPT=\*(Aq\-\-install_base /home/username/perl5\*(Aq \& export PERL_MM_OPT=\*(AqINSTALL_BASE=/home/username/perl5\*(Aq \& export PERL5LIB=\*(Aq/home/username/perl5/lib/perl5/i386\-linux:/home/username/perl5/lib/perl5\*(Aq \& export PATH="/home/username/perl5/bin:$PATH" .Ve .SS "A técnica de 'bootstrapping'" .IX Subsection "A técnica de 'bootstrapping'" Uma forma comum de instalar o local::lib é usando o que é conhecido como técnica de \*(L"bootstrapping\*(R". É 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. .PP 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 \s-1CPAN\s0 do sistema e seus scripts Perl não utilizarão o caminho para o lib/ que você definiu com o local::lib. .PP Por padrão, o local::lib instala os módulos do \s-1CPAN\s0 e a si próprio em ~/perl5. .PP Usuários do Windows devem ler \*(L"Diferenças ao usar esse módulo em Win32\*(R". .PP 1. Baixe e descompacte o local::lib do \s-1CPAN\s0 (procure por \*(L"Download\*(R" na página do \s-1CPAN\s0 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. .PP 2. Execute isso: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap .Ve .PP Caso o sistema pergunte se deve configurar tudo que puder automaticamente, você provavelmente deve responder que sim (yes). .PP 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: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap=~/foo .Ve .PP 3. Execute isso: (local::lib assume que você possui o comando 'make' instalado em seu sistema) .PP .Vb 1 \& make test && make install .Ve .PP 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: .PP .Vb 1 \& echo \*(Aqeval $(perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib)\*(Aq >>~/.bashrc .Ve .PP Caso esteja usando a shell C, pode fazer da seguinte forma: .PP .Vb 4 \& /bin/csh \& echo $SHELL \& /bin/csh \& perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib >> ~/.cshrc .Ve .PP 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: .PP .Vb 1 \& echo \*(Aqeval $(perl \-I$HOME/foo/lib/perl5 \-Mlocal::lib=$HOME/foo)\*(Aq >>~/.bashrc .Ve .PP 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 \f(CW\*(C`. ~/.bashrc\*(C'\fR para isso, enquanto shells C usam \f(CW\*(C`source ~/.cshrc\*(C'\fR. .PP 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 \s-1POD\s0 ao instalar módulos. Para isso, basta passar o argumento \&\f(CW\*(C`\-\-no\-manpages\*(C'\fR durante o bootstrap: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap \-\-no\-manpages .Ve .PP 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: .PP .Vb 7 \& 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 ... .Ve .PP Para múltiplos ambientes destinados a múltiplos aplicativos, você pode precisar incluir uma versão modificada das instruções de \f(CW\*(C`use FindBin\*(C'\fR no exemplo \*(L"No código\*(R" acima. Caso tenha feito algo como o que foi descrito acima, terá um conjunto de módulos Perl em \f(CW\*(C`~/meudir1/lib\*(C'\fR. Caso tenha um script em \f(CW\*(C`~/meudir1/scripts/meuscript.pl\*(C'\fR, você precisará indicar a ele onde encontrar os módulos que instalou para ele em \f(CW\*(C`~/meudir1/lib\*(C'\fR. .PP Em \f(CW\*(C`~/meudir1/scripts/meuscript.pl\*(C'\fR: .PP .Vb 4 \& 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 .Ve .PP Coloque isso antes de qualquer bloco \s-1BEGIN\s0 { ... } que precise dos módulos instalados. .SS "Diferenças ao usar esse módulo em Win32" .IX Subsection "Diferenças ao usar esse módulo em Win32" Para configurar as variáveis de ambiente apropriadas para sua sessão atual do \f(CW\*(C`CMD.exe\*(C'\fR, você pode fazer assim: .PP .Vb 5 \& C:\e>perl \-Mlocal::lib \& set PERL_MB_OPT=\-\-install_base C:\eDOCUME~1\eADMINI~1\eperl5 \& set PERL_MM_OPT=INSTALL_BASE=C:\eDOCUME~1\eADMINI~1\eperl5 \& set PERL5LIB=C:\eDOCUME~1\eADMINI~1\eperl5\elib\eperl5;C:\eDOCUME~1\eADMINI~1\eperl5\elib\eperl5\eMSWin32\-x86\-multi\-thread \& set PATH=C:\eDOCUME~1\eADMINI~1\eperl5\ebin;%PATH% \& \& ### Para configurar o ambiente apenas dessa shell \& C:\e>perl \-Mlocal::lib > %TEMP%\etmp.bat && %TEMP%\etmp.bat && del %TEMP%\etemp.bat \& ### em vez de $(perl \-Mlocal::lib=./) .Ve .PP Caso queira que as configurações do ambiente persistam, você precisará adicioná\-las em Painel de Controle \-> Sistema, ou usar o App::local::lib::Win32Helper. .PP O \*(L"~\*(R" é transformado no diretório do perfil do usuário (o diretório com o nome do usuário dentro de \*(L"Documents and Settings\*(R" (Windows \s-1XP\s0 ou anterior) ou \*(L"Usuários\*(R" (Windows Vista e mais recentes)) a menos que \f(CW$ENV\fR{\s-1HOME\s0} 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). .SH "MOTIVAÇÃO" .IX Header "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. .PP local::lib resolve esse problema possibilitando a criação de seu próprio diretório de pacotes Perl obtidos do \s-1CPAN\s0 (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. .PP 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 \s-1CPAN.\s0 Sua versão local dos pacotes será instalada em um diretório completamente diferente das versões instaladas pelo gerenciador de pacotes do sistema. .SH "DESCRIÇÃO" .IX Header "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 \f(CW\*(C`SHELL\*(C'\fR), pronta para ser adicionada diretamente no arquivo de configuração da shell. .PP Generalizando, o local::lib permite a criação e uso de um diretório contendo módulos Perl fora do \f(CW@INC\fR 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. .PP Durante o \f(CW\*(C`import\*(C'\fR, o local::lib define valores apropriados para as seguintes variáveis de ambiente: .IP "\s-1PERL_MB_OPT\s0" 4 .IX Item "PERL_MB_OPT" .PD 0 .IP "\s-1PERL_MM_OPT\s0" 4 .IX Item "PERL_MM_OPT" .IP "\s-1PERL5LIB\s0" 4 .IX Item "PERL5LIB" .IP "\s-1PATH\s0" 4 .IX Item "PATH" .PD valores serão anexados ao \s-1PATH,\s0 em vez de substituí\-lo. .PP Esses valores são então disponibilizados para referência por qualquer outro código após o \f(CW\*(C`import\*(C'\fR. .SH "CRIANDO UM CONJUNTO AUTO-CONTIDO DE MÓDULOS" .IX Header "CRIANDO UM CONJUNTO AUTO-CONTIDO DE MÓDULOS" Veja lib::core::only 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). .SH "MÉTODOS" .IX Header "MÉTODOS" .SS "ensure_dir_structure_for" .IX Subsection "ensure_dir_structure_for" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .IP "Valor de Retorno: Nenhum" 4 .IX Item "Valor de Retorno: Nenhum" .PD .PP Tenta criar o caminho fornecido, e todos os diretórios superiores necessários. Gera uma exceção em caso de falha. .SS "print_environment_vars_for" .IX Subsection "print_environment_vars_for" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .IP "Valor de Retorno: Nenhum" 4 .IX Item "Valor de Retorno: Nenhum" .PD .PP Exibe na saída padrão as variáveis listadas acima, devidamente ajustadas para utilizar o caminho fornecido como diretório base. .SS "build_environment_vars_for" .IX Subsection "build_environment_vars_for" .ie n .IP "Argumentos: $caminho_do_diretorio, $interpolar" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR, \f(CW$interpolar\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio, $interpolar" .PD 0 .ie n .IP "Valor de Retorno: %variaveis_de_ambiente" 4 .el .IP "Valor de Retorno: \f(CW%variaveis_de_ambiente\fR" 4 .IX Item "Valor de Retorno: %variaveis_de_ambiente" .PD .PP Retorna hash contendo as variáveis de ambiente listadas acima, devidamente ajustadas para utilizar o caminho fornecido como diretório base. .SS "setup_env_hash_for" .IX Subsection "setup_env_hash_for" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .IP "Valor de Retorno: Nenhum" 4 .IX Item "Valor de Retorno: Nenhum" .PD .PP Constrói as chaves no \f(CW%ENV\fR para o caminho fornecido, chamando \&\f(CW\*(C`build_environment_vars_for\*(C'\fR. .SS "install_base_perl_path" .IX Subsection "install_base_perl_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_base_de_instalacao" 4 .el .IP "Valor de Retorno: \f(CW$caminho_base_de_instalacao\fR" 4 .IX Item "Valor de Retorno: $caminho_base_de_instalacao" .PD .PP Retorna um caminho de diretório indicando onde instalar os módulos Perl para essa instalação local de bibliotecas. Adiciona os diretórios \f(CW\*(C`lib\*(C'\fR e \f(CW\*(C`perl5\*(C'\fR ao final do caminho fornecido. .SS "install_base_arch_path" .IX Subsection "install_base_arch_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_base_de_instalacao_arch" 4 .el .IP "Valor de Retorno: \f(CW$caminho_base_de_instalacao_arch\fR" 4 .IX Item "Valor de Retorno: $caminho_base_de_instalacao_arch" .PD .PP 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"install_base_perl_path\*(R", adicionando o valor de \f(CW$Config{archname}\fR. .SS "install_base_bin_path" .IX Subsection "install_base_bin_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_base_de_instalacao_bin" 4 .el .IP "Valor de Retorno: \f(CW$caminho_base_de_instalacao_bin\fR" 4 .IX Item "Valor de Retorno: $caminho_base_de_instalacao_bin" .PD .PP 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"install_base_perl_path\*(R", adicionando o diretório \f(CW\*(C`bin\*(C'\fR. .SS "resolve_empty_path" .IX Subsection "resolve_empty_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_base_de_instalacao" 4 .el .IP "Valor de Retorno: \f(CW$caminho_base_de_instalacao\fR" 4 .IX Item "Valor de Retorno: $caminho_base_de_instalacao" .PD .PP Cria e retorna o caminho de diretório raiz em que a instalação local de módulos deve ser feita. O padrão é \f(CW\*(C`~/perl5\*(C'\fR. .SS "resolve_home_path" .IX Subsection "resolve_home_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_para_home" 4 .el .IP "Valor de Retorno: \f(CW$caminho_para_home\fR" 4 .IX Item "Valor de Retorno: $caminho_para_home" .PD .PP Procura pelo diretório padrão (home) do usuário. Gera uma exceção caso não encontre resultado definitivo. .SS "resolve_relative_path" .IX Subsection "resolve_relative_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_absoluto" 4 .el .IP "Valor de Retorno: \f(CW$caminho_absoluto\fR" 4 .IX Item "Valor de Retorno: $caminho_absoluto" .PD .PP Transforma o caminho fornecido em um caminho absoluto. .SS "resolve_path" .IX Subsection "resolve_path" .ie n .IP "Argumentos: $caminho_do_diretorio" 4 .el .IP "Argumentos: \f(CW$caminho_do_diretorio\fR" 4 .IX Item "Argumentos: $caminho_do_diretorio" .PD 0 .ie n .IP "Valor de Retorno: $caminho_absoluto" 4 .el .IP "Valor de Retorno: \f(CW$caminho_absoluto\fR" 4 .IX Item "Valor de Retorno: $caminho_absoluto" .PD .PP 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"resolve_empty_path\*(R", \&\*(L"resolve_home_path\*(R", \*(L"resolve_relative_path\*(R". Passa o caminho de diretório fornecido para \*(L"resolve_empty_path\*(R" que retorna um resultado que é passado para \*(L"resolve_home_path\*(R", que então tem seu resultado passado para \*(L"resolve_relative_path\*(R". O resultado dessa chamada final é então retornado pelo \*(L"resolve_path\*(R". .SH "UM AVISO SOBRE UNINST=1" .IX Header "UM AVISO SOBRE UNINST=1" Tenha cuidado ao usar o local::lib em conjunto com \*(L"make install UNINST=1\*(R". 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 \*(L"make install UNINST=1\*(R" junto com o local::lib se você entende essas possíveis consequências. .SH "LIMITAÇÕES" .IX Header "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 \fBapós\fR ter instalado todos os módulos dentro dele. Mas esteja ciente que você não poderá atualizar ou instalar outros módulos do \s-1CPAN\s0 nesse diretório local após a mudança. .PP 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 \f(CW\*(C`SHELL\*(C'\fR não esteja disponível, assumiremos tratar-se de uma shell compatível com a Bourne. .PP A técnica de bootstrap é um hack e usará o \s-1CPAN\s0.pm para o ExtUtils::MakeMaker mesmo que você tenha o \s-1CPANPLUS\s0 instalado. .PP Destrói qualquer valor pré\-existente nas variáveis de ambiente \s-1PERL5LIB, PERL_MM_OPT\s0 e \s-1PERL_MB_OPT.\s0 .PP Provavelmente deveria auto-configurar o \s-1CPAN\s0 caso isso ainda não tenha sido feito. .PP Correções (patches) são muito bem-vindos para quaisquer dos itens acima. .PP 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. .SH "SOLUÇÃO DE PROBLEMAS" .IX Header "SOLUÇÃO DE PROBLEMAS" Se você configurou o local::lib para instalar módulos do \s-1CPAN\s0 em algum lugar do seu 'home', e mais tarde tentou instalar um módulo fazendo \f(CW\*(C`cpan \-i Foo::Bar\*(C'\fR, mas ele falhou com um erro como: \f(CW\*(C`Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64\-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm\*(C'\fR e em algum lugar no seu log de instalação houver um erro dizendo \f(CW\*(C`\*(AqINSTALL_BASE\*(Aq is not a known MakeMaker parameter name\*(C'\fR, então você de alguma forma perdeu seu ExtUtils::MakeMaker atualizado. .PP Para remediar a situação, execute novamente o procedimento de bootstrap descrito acima. .PP Então, execute \f(CW\*(C`rm \-r ~/.cpan/build/Foo\-Bar*\*(C'\fR .PP Finalmente, execute novamente o \f(CW\*(C`cpan \-i Foo::Bar\*(C'\fR e ele deve instalar sem problemas. .SH "AMBIENTE" .IX Header "AMBIENTE" .IP "\s-1SHELL\s0" 4 .IX Item "SHELL" .PD 0 .IP "\s-1COMSPEC\s0" 4 .IX Item "COMSPEC" .PD O local::lib procura pela variável de ambiente \f(CW\*(C`SHELL\*(C'\fR do usuário ao processar e exibir os comandos a serem adicionados no arquivo de configuração da shell. .Sp Em sistemas Win32, \f(CW\*(C`COMSPEC\*(C'\fR também será examinado. .SH "SUPORTE" .IX Header "SUPORTE" \&\s-1IRC:\s0 .PP .Vb 1 \& Acesse #local\-lib em irc.perl.org. .Ve .SH "AUTOR DA TRADUÇÃO" .IX Header "AUTOR DA TRADUÇÃO" Breno G. de Oliveira, \f(CW\*(C`\*(C'\fR, após ter perdido uma aposta para o Getty durante a Copa de 2010. .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright (c) 2007 \- 2010 \*(L"\s-1AUTHOR\*(R"\s0 in local::lib e \*(L"\s-1CONTRIBUTORS\*(R"\s0 in local::lib do local::lib como listados em local::lib. .SH "LICENÇA" .IX Header "LICENÇA" Esta biblioteca é software livre e pode ser distribuída sob os mesmo termos do perl. PK! ,  man/man3/lib::core::only.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "lib::core::only 3" .TH lib::core::only 3 "2017-11-08" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" lib::core::only \- Remove all non\-core paths from @INC to avoid site/vendor dirs .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use lib::core::only; # now @INC contains only the two core directories .Ve .PP To get only the core directories plus the ones for the local::lib in scope: .PP .Vb 1 \& $ perl \-mlocal::lib \-Mlib::core::only \-Mlocal::lib=~/perl5 myscript.pl .Ve .PP To attempt to do a self-contained build (but note this will not reliably propagate into subprocesses, see the \s-1CAVEATS\s0 below): .PP .Vb 1 \& $ PERL5OPT=\*(Aq\-mlocal::lib \-Mlib::core::only \-Mlocal::lib=~/perl5\*(Aq cpan .Ve .PP Please note that it is necessary to use \f(CW\*(C`local::lib\*(C'\fR twice for this to work. First so that \f(CW\*(C`lib::core::only\*(C'\fR doesn't prevent \f(CW\*(C`local::lib\*(C'\fR from loading (it's not currently in core) and then again after \f(CW\*(C`lib::core::only\*(C'\fR so that the local paths are not removed. .SH "DESCRIPTION" .IX Header "DESCRIPTION" lib::core::only is simply a shortcut to say \*(L"please reduce my \f(CW@INC\fR to only the core lib and archlib (architecture-specific lib) directories of this perl\*(R". .PP You might want to do this to ensure a local::lib contains only the code you need, or to test an App::FatPacker tree, or to avoid known bad vendor packages. .PP 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"\s-1CAVEATS\*(R"\s0). .PP This module was extracted from local::lib's \-\-self\-contained feature, and contains the only part that ever worked. I apologise to anybody who thought anything else did. .SH "CAVEATS" .IX Header "CAVEATS" This does \fBnot\fR propagate properly across perl invocations like local::lib's stuff does. It can't. It's only a module import, so it \fBonly affects the specific perl \s-1VM\s0 instance in which you load and \fBimport()\fB it\fR. .PP If you want to cascade it across invocations, you can set the \s-1PERL5OPT\s0 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. .PP 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 .PP .Vb 1 \& perl \-Mlib::core::only \-Ilib .Ve .PP is unlike to do what you want \- it's exactly equivalent to: .PP .Vb 1 \& perl \-Mlib::core::only .Ve .PP If you want to combine a core-only \f(CW@INC\fR with additional paths, you need to add the additional paths using \-M options and the lib module: .PP .Vb 1 \& perl \-Mlib::core::only \-Mlib=lib \& \& # or if you\*(Aqre trying to test compiled code: \& \& perl \-Mlib::core::only \-Mblib .Ve .PP For more information on the impossibility of sanely propagating this across module builds without help from the build program, see \- and for ways to achieve the old \-\-self\-contained feature's results, look at App::FatPacker's tree function, and at App::cpanminus's \-\-local\-lib\-contained feature. .SH "AUTHOR" .IX Header "AUTHOR" Matt S. Trout .SH "LICENSE" .IX Header "LICENSE" This library is free software under the same terms as perl itself. .SH "COPYRIGHT" .IX Header "COPYRIGHT" (c) 2010 the lib::core::only \*(L"\s-1AUTHOR\*(R"\s0 as specified above. PK!r4J||man/man3/local::lib.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "local::lib 3" .TH local::lib 3 "2022-04-20" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" local::lib \- create and use a local lib/ for perl modules with PERL5LIB .SH "SYNOPSIS" .IX Header "SYNOPSIS" In code \- .PP .Vb 1 \& use local::lib; # sets up a local lib at ~/perl5 \& \& use local::lib \*(Aq~/foo\*(Aq; # same, but ~/foo \& \& # Or... \& use FindBin; \& use local::lib "$FindBin::Bin/../support"; # app\-local support library .Ve .PP From the shell \- .PP .Vb 2 \& # Install LWP and its missing dependencies to the \*(Aq~/perl5\*(Aq directory \& perl \-MCPAN \-Mlocal::lib \-e \*(AqCPAN::install(LWP)\*(Aq \& \& # Just print out useful shell commands \& $ perl \-Mlocal::lib \& PERL_MB_OPT=\*(Aq\-\-install_base /home/username/perl5\*(Aq; export PERL_MB_OPT; \& PERL_MM_OPT=\*(AqINSTALL_BASE=/home/username/perl5\*(Aq; 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; .Ve .PP From a \fI.bash_profile\fR or \fI.bashrc\fR file \- .PP .Vb 1 \& eval "$(perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib)" .Ve .SS "The bootstrapping technique" .IX Subsection "The bootstrapping technique" A typical way to install local::lib is using what is known as the \&\*(L"bootstrapping\*(R" 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. .PP 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 \s-1CPAN\s0 installation and also your Perl scripts will not use the lib/ path you bootstrapped with local::lib. .PP By default local::lib installs itself and the \s-1CPAN\s0 modules into ~/perl5. .PP Windows users must also see \*(L"Differences when using this module under Win32\*(R". .IP "1." 4 Download and unpack the local::lib tarball from \s-1CPAN\s0 (search for \*(L"Download\*(R" on the \s-1CPAN\s0 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. .IP "2." 4 Run this: .Sp .Vb 1 \& perl Makefile.PL \-\-bootstrap .Ve .Sp If the system asks you whether it should automatically configure as much as possible, you would typically answer yes. .IP "3." 4 Run this: (local::lib assumes you have make installed on your system) .Sp .Vb 1 \& make test && make install .Ve .IP "4." 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: .Sp .Vb 1 \& echo \*(Aqeval "$(perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib)"\*(Aq >>~/.bashrc .Ve .Sp If you are using C shell, you can do this as follows: .Sp .Vb 3 \& % echo $SHELL \& /bin/csh \& $ echo \*(Aqeval \`perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib\`\*(Aq >> ~/.cshrc .Ve .Sp 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 \&\f(CW\*(C`. ~/.bashrc\*(C'\fR for this, whereas C shells use \f(CW\*(C`source ~/.cshrc\*(C'\fR. .PP \fIBootstrapping into an alternate directory\fR .IX Subsection "Bootstrapping into an alternate directory" .PP 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: .PP .Vb 4 \& perl Makefile.PL \-\-bootstrap=~/foo \& make test && make install \& echo \*(Aqeval "$(perl \-I$HOME/foo/lib/perl5 \-Mlocal::lib=$HOME/foo)"\*(Aq >>~/.bashrc \& . ~/.bashrc .Ve .PP \fIOther bootstrapping options\fR .IX Subsection "Other bootstrapping options" .PP If you're on a slower machine, or are operating under draconian disk space limitations, you can disable the automatic generation of manpages from \s-1POD\s0 when installing modules by using the \f(CW\*(C`\-\-no\-manpages\*(C'\fR argument when bootstrapping: .PP .Vb 1 \& perl Makefile.PL \-\-bootstrap \-\-no\-manpages .Ve .PP 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: .PP .Vb 7 \& 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 ... .Ve .PP If you use \fI.bashrc\fR 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 \&\fI.bash_profile\fR rather than \fI.bashrc\fR, or protect the local::lib invocation with a \f(CW$SHLVL\fR check: .PP .Vb 1 \& [ $SHLVL \-eq 1 ] && eval "$(perl \-I$HOME/perl5/lib/perl5 \-Mlocal::lib)" .Ve .PP If you are working with several \f(CW\*(C`local::lib\*(C'\fR 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): .PP .Vb 1 \& eval $(perl \-Mlocal::lib=\-\-deactivate,~/path) .Ve .PP which will generate and run the commands needed to remove \f(CW\*(C`~/path\*(C'\fR from your various search paths. Whichever environment was \fBactivated most recently\fR will remain the target for module installations. That is, if you activate \&\f(CW\*(C`~/path_A\*(C'\fR and then you activate \f(CW\*(C`~/path_B\*(C'\fR, new modules you install will go in \f(CW\*(C`~/path_B\*(C'\fR. If you deactivate \f(CW\*(C`~/path_B\*(C'\fR then modules will be installed into \f(CW\*(C`~/pathA\*(C'\fR \*(-- but if you deactivate \f(CW\*(C`~/path_A\*(C'\fR then they will still be installed in \f(CW\*(C`~/pathB\*(C'\fR because pathB was activated later. .PP You can also ask \f(CW\*(C`local::lib\*(C'\fR to clean itself completely out of the current shell's environment with the \f(CW\*(C`\-\-deactivate\-all\*(C'\fR option. For multiple environments for multiple apps you may need to include a modified version of the \f(CW\*(C`use FindBin\*(C'\fR instructions in the \*(L"In code\*(R" sample above. If you did something like the above, you have a set of Perl modules at \f(CW\*(C`~/mydir1/lib\*(C'\fR. If you have a script at \f(CW\*(C`~/mydir1/scripts/myscript.pl\*(C'\fR, you need to tell it where to find the modules you installed for it at \f(CW\*(C`~/mydir1/lib\*(C'\fR. .PP In \f(CW\*(C`~/mydir1/scripts/myscript.pl\*(C'\fR: .PP .Vb 4 \& 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 .Ve .PP Put this before any \s-1BEGIN\s0 { ... } blocks that require the modules you installed. .SS "Differences when using this module under Win32" .IX Subsection "Differences when using this module under Win32" To set up the proper environment variables for your current session of \&\f(CW\*(C`CMD.exe\*(C'\fR, you can use this: .PP .Vb 5 \& C:\e>perl \-Mlocal::lib \& set PERL_MB_OPT=\-\-install_base C:\eDOCUME~1\eADMINI~1\eperl5 \& set PERL_MM_OPT=INSTALL_BASE=C:\eDOCUME~1\eADMINI~1\eperl5 \& set PERL5LIB=C:\eDOCUME~1\eADMINI~1\eperl5\elib\eperl5 \& set PATH=C:\eDOCUME~1\eADMINI~1\eperl5\ebin;%PATH% \& \& ### To set the environment for this shell alone \& C:\e>perl \-Mlocal::lib > %TEMP%\etmp.bat && %TEMP%\etmp.bat && del %TEMP%\etmp.bat \& ### instead of $(perl \-Mlocal::lib=./) .Ve .PP If you want the environment entries to persist, you'll need to add them to the Control Panel's System applet yourself or use App::local::lib::Win32Helper. .PP The \*(L"~\*(R" is translated to the user's profile directory (the directory named for the user under \*(L"Documents and Settings\*(R" (Windows \s-1XP\s0 or earlier) or \*(L"Users\*(R" (Windows Vista or later)) unless \f(CW$ENV\fR{\s-1HOME\s0} exists. After that, the home directory is translated to a short name (which means the directory must exist) and the subdirectories are created. .PP \fIPowerShell\fR .IX Subsection "PowerShell" .PP local::lib also supports PowerShell, and can be used with the \&\f(CW\*(C`Invoke\-Expression\*(C'\fR cmdlet. .PP .Vb 1 \& Invoke\-Expression "$(perl \-Mlocal::lib)" .Ve .SH "RATIONALE" .IX Header "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. .PP local::lib solves this problem by allowing you to create your own directory of Perl packages downloaded from \s-1CPAN\s0 (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. .PP If you are using a package management system (such as Debian), you don't need to worry about Debian and \s-1CPAN\s0 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. .SH "DESCRIPTION" .IX Header "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 \f(CW\*(C`SHELL\*(C'\fR environment variable), suitable for directly adding to one's shell configuration file. .PP More generally, local::lib allows for the bootstrapping and usage of a directory containing Perl modules outside of Perl's \f(CW@INC\fR. 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. .PP On import, local::lib sets the following environment variables to appropriate values: .IP "\s-1PERL_MB_OPT\s0" 4 .IX Item "PERL_MB_OPT" .PD 0 .IP "\s-1PERL_MM_OPT\s0" 4 .IX Item "PERL_MM_OPT" .IP "\s-1PERL5LIB\s0" 4 .IX Item "PERL5LIB" .IP "\s-1PATH\s0" 4 .IX Item "PATH" .IP "\s-1PERL_LOCAL_LIB_ROOT\s0" 4 .IX Item "PERL_LOCAL_LIB_ROOT" .PD .PP When possible, these will be appended to instead of overwritten entirely. .PP These values are then available for reference by any code after import. .SH "CREATING A SELF-CONTAINED SET OF MODULES" .IX Header "CREATING A SELF-CONTAINED SET OF MODULES" See lib::core::only 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). .SH "IMPORT OPTIONS" .IX Header "IMPORT OPTIONS" Options are values that can be passed to the \f(CW\*(C`local::lib\*(C'\fR import besides the directory to use. They are specified as \f(CW\*(C`use local::lib \*(Aq\-\-option\*(Aq[, path];\*(C'\fR or \f(CW\*(C`perl \-Mlocal::lib=\-\-option[,path]\*(C'\fR. .SS "\-\-deactivate" .IX Subsection "--deactivate" Remove the chosen path (or the default path) from the module search paths if it was added by \f(CW\*(C`local::lib\*(C'\fR, instead of adding it. .SS "\-\-deactivate\-all" .IX Subsection "--deactivate-all" Remove all directories that were added to search paths by \f(CW\*(C`local::lib\*(C'\fR from the search paths. .SS "\-\-quiet" .IX Subsection "--quiet" Don't output any messages about directories being created. .SS "\-\-always" .IX Subsection "--always" Always add directories to environment variables, ignoring if they are already included. .SS "\-\-shelltype" .IX Subsection "--shelltype" Specify the shell type to use for output. By default, the shell will be detected based on the environment. Should be one of: \f(CW\*(C`bourne\*(C'\fR, \f(CW\*(C`csh\*(C'\fR, \&\f(CW\*(C`cmd\*(C'\fR, or \f(CW\*(C`powershell\*(C'\fR. .SS "\-\-no\-create" .IX Subsection "--no-create" Prevents \f(CW\*(C`local::lib\*(C'\fR from creating directories when activating dirs. This is likely to cause issues on Win32 systems. .SH "CLASS METHODS" .IX Header "CLASS METHODS" .SS "ensure_dir_structure_for" .IX Subsection "ensure_dir_structure_for" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .IP "Return value: None" 4 .IX Item "Return value: None" .PD .PP Attempts to create a local::lib directory, including subdirectories and all required parent directories. Throws an exception on failure. .SS "print_environment_vars_for" .IX Subsection "print_environment_vars_for" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .IP "Return value: None" 4 .IX Item "Return value: None" .PD .PP Prints to standard output the variables listed above, properly set to use the given path as the base directory. .SS "build_environment_vars_for" .IX Subsection "build_environment_vars_for" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: %environment_vars" 4 .el .IP "Return value: \f(CW%environment_vars\fR" 4 .IX Item "Return value: %environment_vars" .PD .PP Returns a hash with the variables listed above, properly set to use the given path as the base directory. .SS "setup_env_hash_for" .IX Subsection "setup_env_hash_for" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .IP "Return value: None" 4 .IX Item "Return value: None" .PD .PP Constructs the \f(CW%ENV\fR keys for the given path, by calling \&\*(L"build_environment_vars_for\*(R". .SS "active_paths" .IX Subsection "active_paths" .IP "Arguments: None" 4 .IX Item "Arguments: None" .PD 0 .ie n .IP "Return value: @paths" 4 .el .IP "Return value: \f(CW@paths\fR" 4 .IX Item "Return value: @paths" .PD .PP Returns a list of active \f(CW\*(C`local::lib\*(C'\fR paths, according to the \&\f(CW\*(C`PERL_LOCAL_LIB_ROOT\*(C'\fR environment variable and verified against what is really in \f(CW@INC\fR. .SS "install_base_perl_path" .IX Subsection "install_base_perl_path" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $install_base_perl_path" 4 .el .IP "Return value: \f(CW$install_base_perl_path\fR" 4 .IX Item "Return value: $install_base_perl_path" .PD .PP Returns a path describing where to install the Perl modules for this local library installation. Appends the directories \f(CW\*(C`lib\*(C'\fR and \f(CW\*(C`perl5\*(C'\fR to the given path. .SS "lib_paths_for" .IX Subsection "lib_paths_for" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: @lib_paths" 4 .el .IP "Return value: \f(CW@lib_paths\fR" 4 .IX Item "Return value: @lib_paths" .PD .PP 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. .SS "install_base_bin_path" .IX Subsection "install_base_bin_path" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $install_base_bin_path" 4 .el .IP "Return value: \f(CW$install_base_bin_path\fR" 4 .IX Item "Return value: $install_base_bin_path" .PD .PP Returns a path describing where to install the executable programs for this local library installation. Appends the directory \f(CW\*(C`bin\*(C'\fR to the given path. .SS "installer_options_for" .IX Subsection "installer_options_for" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: %installer_env_vars" 4 .el .IP "Return value: \f(CW%installer_env_vars\fR" 4 .IX Item "Return value: %installer_env_vars" .PD .PP Returns a hash of environment variables that should be set to cause installation into the given path. .SS "resolve_empty_path" .IX Subsection "resolve_empty_path" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $base_path" 4 .el .IP "Return value: \f(CW$base_path\fR" 4 .IX Item "Return value: $base_path" .PD .PP Builds and returns the base path into which to set up the local module installation. Defaults to \f(CW\*(C`~/perl5\*(C'\fR. .SS "resolve_home_path" .IX Subsection "resolve_home_path" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $home_path" 4 .el .IP "Return value: \f(CW$home_path\fR" 4 .IX Item "Return value: $home_path" .PD .PP Attempts to find the user's home directory. If no definite answer is available, throws an exception. .SS "resolve_relative_path" .IX Subsection "resolve_relative_path" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $absolute_path" 4 .el .IP "Return value: \f(CW$absolute_path\fR" 4 .IX Item "Return value: $absolute_path" .PD .PP Translates the given path into an absolute path. .SS "resolve_path" .IX Subsection "resolve_path" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $absolute_path" 4 .el .IP "Return value: \f(CW$absolute_path\fR" 4 .IX Item "Return value: $absolute_path" .PD .PP 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"resolve_empty_path\*(R", \*(L"resolve_home_path\*(R", \&\*(L"resolve_relative_path\*(R". Passes the given path argument to \&\*(L"resolve_empty_path\*(R" which then returns a result that is passed to \&\*(L"resolve_home_path\*(R", which then has its result passed to \&\*(L"resolve_relative_path\*(R". The result of this final call is returned from \&\*(L"resolve_path\*(R". .SH "OBJECT INTERFACE" .IX Header "OBJECT INTERFACE" .SS "new" .IX Subsection "new" .ie n .IP "Arguments: %attributes" 4 .el .IP "Arguments: \f(CW%attributes\fR" 4 .IX Item "Arguments: %attributes" .PD 0 .ie n .IP "Return value: $local_lib" 4 .el .IP "Return value: \f(CW$local_lib\fR" 4 .IX Item "Return value: $local_lib" .PD .PP Constructs a new \f(CW\*(C`local::lib\*(C'\fR object, representing the current state of \&\f(CW@INC\fR and the relevant environment variables. .SH "ATTRIBUTES" .IX Header "ATTRIBUTES" .SS "roots" .IX Subsection "roots" An arrayref representing active \f(CW\*(C`local::lib\*(C'\fR directories. .SS "inc" .IX Subsection "inc" An arrayref representing \f(CW@INC\fR. .SS "libs" .IX Subsection "libs" An arrayref representing the \s-1PERL5LIB\s0 environment variable. .SS "bins" .IX Subsection "bins" An arrayref representing the \s-1PATH\s0 environment variable. .SS "extra" .IX Subsection "extra" A hashref of extra environment variables (e.g. \f(CW\*(C`PERL_MM_OPT\*(C'\fR and \&\f(CW\*(C`PERL_MB_OPT\*(C'\fR) .SS "no_create" .IX Subsection "no_create" If set, \f(CW\*(C`local::lib\*(C'\fR will not try to create directories when activating them. .SH "OBJECT METHODS" .IX Header "OBJECT METHODS" .SS "clone" .IX Subsection "clone" .ie n .IP "Arguments: %attributes" 4 .el .IP "Arguments: \f(CW%attributes\fR" 4 .IX Item "Arguments: %attributes" .PD 0 .ie n .IP "Return value: $local_lib" 4 .el .IP "Return value: \f(CW$local_lib\fR" 4 .IX Item "Return value: $local_lib" .PD .PP Constructs a new \f(CW\*(C`local::lib\*(C'\fR object based on the existing one, overriding the specified attributes. .SS "activate" .IX Subsection "activate" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $new_local_lib" 4 .el .IP "Return value: \f(CW$new_local_lib\fR" 4 .IX Item "Return value: $new_local_lib" .PD .PP Constructs a new instance with the specified path active. .SS "deactivate" .IX Subsection "deactivate" .ie n .IP "Arguments: $path" 4 .el .IP "Arguments: \f(CW$path\fR" 4 .IX Item "Arguments: $path" .PD 0 .ie n .IP "Return value: $new_local_lib" 4 .el .IP "Return value: \f(CW$new_local_lib\fR" 4 .IX Item "Return value: $new_local_lib" .PD .PP Constructs a new instance with the specified path deactivated. .SS "deactivate_all" .IX Subsection "deactivate_all" .IP "Arguments: None" 4 .IX Item "Arguments: None" .PD 0 .ie n .IP "Return value: $new_local_lib" 4 .el .IP "Return value: \f(CW$new_local_lib\fR" 4 .IX Item "Return value: $new_local_lib" .PD .PP Constructs a new instance with all \f(CW\*(C`local::lib\*(C'\fR directories deactivated. .SS "environment_vars_string" .IX Subsection "environment_vars_string" .ie n .IP "Arguments: [ $shelltype ]" 4 .el .IP "Arguments: [ \f(CW$shelltype\fR ]" 4 .IX Item "Arguments: [ $shelltype ]" .PD 0 .ie n .IP "Return value: $shell_env_string" 4 .el .IP "Return value: \f(CW$shell_env_string\fR" 4 .IX Item "Return value: $shell_env_string" .PD .PP Returns a string to set up the \f(CW\*(C`local::lib\*(C'\fR, meant to be run by a shell. .SS "build_environment_vars" .IX Subsection "build_environment_vars" .IP "Arguments: None" 4 .IX Item "Arguments: None" .PD 0 .ie n .IP "Return value: %environment_vars" 4 .el .IP "Return value: \f(CW%environment_vars\fR" 4 .IX Item "Return value: %environment_vars" .PD .PP Returns a hash with the variables listed above, properly set to use the given path as the base directory. .SS "setup_env_hash" .IX Subsection "setup_env_hash" .IP "Arguments: None" 4 .IX Item "Arguments: None" .PD 0 .IP "Return value: None" 4 .IX Item "Return value: None" .PD .PP Constructs the \f(CW%ENV\fR keys for the given path, by calling \&\*(L"build_environment_vars\*(R". .SS "setup_local_lib" .IX Subsection "setup_local_lib" Constructs the \f(CW%ENV\fR hash using \*(L"setup_env_hash\*(R", and set up \f(CW@INC\fR. .SH "A WARNING ABOUT UNINST=1" .IX Header "A WARNING ABOUT UNINST=1" Be careful about using local::lib in combination with \*(L"make install UNINST=1\*(R". 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 \*(L"make install UNINST=1\*(R" and local::lib if you understand these possible consequences. .SH "LIMITATIONS" .IX Header "LIMITATIONS" .IP "\(bu" 4 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 \&\fBafter\fR you installed all modules inside your local::lib bootstrap. But be aware that you can't update or install \s-1CPAN\s0 modules after the move. .IP "\(bu" 4 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 \f(CW\*(C`SHELL\*(C'\fR environment variable is not set, a Bourne-compatible shell is assumed. .IP "\(bu" 4 Kills any existing \s-1PERL_MM_OPT\s0 or \s-1PERL_MB_OPT.\s0 .IP "\(bu" 4 Should probably auto-fixup \s-1CPAN\s0 config if not already done. .IP "\(bu" 4 On \s-1VMS\s0 and MacOS Classic (pre-OS X), local::lib loads File::Spec. This means any File::Spec version installed in the local::lib will be ignored by scripts using local::lib. A workaround for this is using \&\f(CW\*(C`use lib "$local_lib/lib/perl5";\*(C'\fR instead of using \f(CW\*(C`local::lib\*(C'\fR directly. .IP "\(bu" 4 Conflicts with ExtUtils::MakeMaker's \f(CW\*(C`PREFIX\*(C'\fR option. \&\f(CW\*(C`local::lib\*(C'\fR uses the \f(CW\*(C`INSTALL_BASE\*(C'\fR option, as it has more predictable and sane behavior. If something attempts to use the \f(CW\*(C`PREFIX\*(C'\fR option when running a \fIMakefile.PL\fR, ExtUtils::MakeMaker will refuse to run, as the two options conflict. This can be worked around by temporarily unsetting the \&\f(CW\*(C`PERL_MM_OPT\*(C'\fR environment variable. .IP "\(bu" 4 Conflicts with Module::Build's \f(CW\*(C`\-\-prefix\*(C'\fR option. Similar to the previous limitation, but any \f(CW\*(C`\-\-prefix\*(C'\fR option specified will be ignored. This can be worked around by temporarily unsetting the \f(CW\*(C`PERL_MB_OPT\*(C'\fR environment variable. .PP Patches very much welcome for any of the above. .IP "\(bu" 4 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. .SH "TROUBLESHOOTING" .IX Header "TROUBLESHOOTING" If you've configured local::lib to install \s-1CPAN\s0 modules somewhere in to your home directory, and at some point later you try to install a module with \f(CW\*(C`cpan \&\-i Foo::Bar\*(C'\fR, but it fails with an error like: \f(CW\*(C`Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64\-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm\*(C'\fR and buried within the install log is an error saying \f(CW\*(C`\*(AqINSTALL_BASE\*(Aq is not a known MakeMaker parameter name\*(C'\fR, then you've somehow lost your updated ExtUtils::MakeMaker module. .PP To remedy this situation, rerun the bootstrapping procedure documented above. .PP Then, run \f(CW\*(C`rm \-r ~/.cpan/build/Foo\-Bar*\*(C'\fR .PP Finally, re-run \f(CW\*(C`cpan \-i Foo::Bar\*(C'\fR and it should install without problems. .SH "ENVIRONMENT" .IX Header "ENVIRONMENT" .IP "\s-1SHELL\s0" 4 .IX Item "SHELL" .PD 0 .IP "\s-1COMSPEC\s0" 4 .IX Item "COMSPEC" .PD local::lib looks at the user's \f(CW\*(C`SHELL\*(C'\fR environment variable when printing out commands to add to the shell configuration file. .Sp On Win32 systems, \f(CW\*(C`COMSPEC\*(C'\fR is also examined. .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "\(bu" 4 Perl Advent article, 2011 .SH "SUPPORT" .IX Header "SUPPORT" \&\s-1IRC:\s0 .PP .Vb 1 \& Join #toolchain on irc.perl.org. .Ve .SH "AUTHOR" .IX Header "AUTHOR" Matt S Trout http://www.shadowcat.co.uk/ .PP auto_install fixes kindly sponsored by http://www.takkle.com/ .SH "CONTRIBUTORS" .IX Header "CONTRIBUTORS" Patches to correctly output commands for csh style shells, as well as some documentation additions, contributed by Christopher Nehren . .PP Doc patches for a custom local::lib directory, more cleanups in the english documentation and a german documentation contributed by Torsten Raudssus . .PP 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! .PP pattern of Freenode \s-1IRC\s0 contributed the beginnings of the Troubleshooting section. Many thanks! .PP Patch to add Win32 support contributed by Curtis Jewell . .PP Warnings for missing \s-1PATH/PERL5LIB\s0 (as when not running interactively) silenced by a patch from Marco Emilio Poleggi. .PP Mark Stosberg provided the code for the now deleted \&'\-\-self\-contained' option. .PP Documentation patches to make win32 usage clearer by David Mertens (run4flat). .PP Brazilian portuguese translation and minor doc patches contributed by Breno G. de Oliveira . .PP Improvements to stacking multiple local::lib dirs and removing them from the environment later on contributed by Andrew Rodland . .PP Patch for Carp version mismatch contributed by Hakim Cassimally . .PP Rewrite of internals and numerous bug fixes and added features contributed by Graham Knop . .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright (c) 2007 \- 2013 the local::lib \*(L"\s-1AUTHOR\*(R"\s0 and \*(L"\s-1CONTRIBUTORS\*(R"\s0 as listed above. .SH "LICENSE" .IX Header "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. PK!+ihA@Q@Qman/man3/Try::Tiny.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Try::Tiny 3" .TH Try::Tiny 3 "2021-11-23" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Try::Tiny \- Minimal try/catch with proper preservation of $@ .SH "VERSION" .IX Header "VERSION" version 0.31 .SH "SYNOPSIS" .IX Header "SYNOPSIS" You can use Try::Tiny's \f(CW\*(C`try\*(C'\fR and \f(CW\*(C`catch\*(C'\fR to expect and handle exceptional conditions, avoiding quirks in Perl and common mistakes: .PP .Vb 6 \& # handle errors with a catch handler \& try { \& die "foo"; \& } catch { \& warn "caught error: $_"; # not $@ \& }; .Ve .PP You can also use it like a standalone \f(CW\*(C`eval\*(C'\fR to catch and ignore any error conditions. Obviously, this is an extreme measure not to be undertaken lightly: .PP .Vb 4 \& # just silence errors \& try { \& die "foo"; \& }; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module provides bare bones \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`catch\*(C'\fR/\f(CW\*(C`finally\*(C'\fR statements that are designed to minimize common mistakes with eval blocks, and \s-1NOTHING\s0 else. .PP This is unlike TryCatch which provides a nice syntax and avoids adding another call stack layer, and supports calling \f(CW\*(C`return\*(C'\fR from the \f(CW\*(C`try\*(C'\fR block to return from the parent subroutine. These extra features come at a cost of a few dependencies, namely Devel::Declare and Scope::Upper which are occasionally problematic, and the additional catch filtering uses Moose type constraints which may not be desirable either. .PP The main focus of this module is to provide simple and reliable error handling for those having a hard time installing TryCatch, but who still want to write correct \f(CW\*(C`eval\*(C'\fR blocks without 5 lines of boilerplate each time. .PP It's designed to work as correctly as possible in light of the various pathological edge cases (see \*(L"\s-1BACKGROUND\*(R"\s0) and to be compatible with any style of error values (simple strings, references, objects, overloaded objects, etc). .PP If the \f(CW\*(C`try\*(C'\fR block dies, it returns the value of the last statement executed in the \f(CW\*(C`catch\*(C'\fR block, if there is one. Otherwise, it returns \f(CW\*(C`undef\*(C'\fR in scalar context or the empty list in list context. The following examples all assign \f(CW"bar"\fR to \f(CW$x\fR: .PP .Vb 3 \& 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"; .Ve .PP You can add \f(CW\*(C`finally\*(C'\fR blocks, yielding the following: .PP .Vb 3 \& my $x; \& try { die \*(Aqfoo\*(Aq } finally { $x = \*(Aqbar\*(Aq }; \& try { die \*(Aqfoo\*(Aq } catch { warn "Got a die: $_" } finally { $x = \*(Aqbar\*(Aq }; .Ve .PP \&\f(CW\*(C`finally\*(C'\fR blocks are always executed making them suitable for cleanup code which cannot be handled using local. You can add as many \f(CW\*(C`finally\*(C'\fR blocks to a given \f(CW\*(C`try\*(C'\fR block as you like. .PP Note that adding a \f(CW\*(C`finally\*(C'\fR block without a preceding \f(CW\*(C`catch\*(C'\fR block suppresses any errors. This behaviour is consistent with using a standalone \&\f(CW\*(C`eval\*(C'\fR, but it is not consistent with \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`finally\*(C'\fR patterns found in other programming languages, such as Java, Python, Javascript or C#. If you learned the \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`finally\*(C'\fR pattern from one of these languages, watch out for this. .SH "EXPORTS" .IX Header "EXPORTS" All functions are exported by default using Exporter. .PP If you need to rename the \f(CW\*(C`try\*(C'\fR, \f(CW\*(C`catch\*(C'\fR or \f(CW\*(C`finally\*(C'\fR keyword consider using Sub::Import to get Sub::Exporter's flexibility. .IP "try (&;@)" 4 .IX Item "try (&;@)" Takes one mandatory \f(CW\*(C`try\*(C'\fR subroutine, an optional \f(CW\*(C`catch\*(C'\fR subroutine and \f(CW\*(C`finally\*(C'\fR subroutine. .Sp The mandatory subroutine is evaluated in the context of an \f(CW\*(C`eval\*(C'\fR block. .Sp If no error occurred the value from the first block is returned, preserving list/scalar context. .Sp If there was an error and the second subroutine was given it will be invoked with the error in \f(CW$_\fR (localized) and as that block's first and only argument. .Sp \&\f(CW$@\fR does \fBnot\fR contain the error. Inside the \f(CW\*(C`catch\*(C'\fR block it has the same value it had before the \f(CW\*(C`try\*(C'\fR block was executed. .Sp Note that the error may be false, but if that happens the \f(CW\*(C`catch\*(C'\fR block will still be invoked. .Sp Once all execution is finished then the \f(CW\*(C`finally\*(C'\fR block, if given, will execute. .IP "catch (&;@)" 4 .IX Item "catch (&;@)" Intended to be used in the second argument position of \f(CW\*(C`try\*(C'\fR. .Sp Returns a reference to the subroutine it was given but blessed as \&\f(CW\*(C`Try::Tiny::Catch\*(C'\fR which allows try to decode correctly what to do with this code reference. .Sp .Vb 1 \& catch { ... } .Ve .Sp Inside the \f(CW\*(C`catch\*(C'\fR block the caught error is stored in \f(CW$_\fR, while previous value of \f(CW$@\fR is still available for use. This value may or may not be meaningful depending on what happened before the \f(CW\*(C`try\*(C'\fR, but it might be a good idea to preserve it in an error stack. .Sp For code that captures \f(CW$@\fR when throwing new errors (i.e. Class::Throwable), you'll need to do: .Sp .Vb 1 \& local $@ = $_; .Ve .IP "finally (&;@)" 4 .IX Item "finally (&;@)" .Vb 3 \& try { ... } \& catch { ... } \& finally { ... }; .Ve .Sp Or .Sp .Vb 2 \& try { ... } \& finally { ... }; .Ve .Sp Or even .Sp .Vb 3 \& try { ... } \& finally { ... } \& catch { ... }; .Ve .Sp Intended to be the second or third element of \f(CW\*(C`try\*(C'\fR. \f(CW\*(C`finally\*(C'\fR blocks are always executed in the event of a successful \f(CW\*(C`try\*(C'\fR or if \f(CW\*(C`catch\*(C'\fR is run. This allows you to locate cleanup code which cannot be done via \f(CW\*(C`local()\*(C'\fR e.g. closing a file handle. .Sp When invoked, the \f(CW\*(C`finally\*(C'\fR block is passed the error that was caught. If no error was caught, it is passed nothing. (Note that the \f(CW\*(C`finally\*(C'\fR block does not localize \f(CW$_\fR with the error, since unlike in a \f(CW\*(C`catch\*(C'\fR block, there is no way to know if \f(CW\*(C`$_ == undef\*(C'\fR implies that there were no errors.) In other words, the following code does just what you would expect: .Sp .Vb 11 \& try { \& die_sometimes(); \& } catch { \& # ...code run in case of error \& } finally { \& if (@_) { \& print "The try block died with: @_\en"; \& } else { \& print "The try block ran without error.\en"; \& } \& }; .Ve .Sp \&\fBYou must always do your own error handling in the \f(CB\*(C`finally\*(C'\fB block\fR. \f(CW\*(C`Try::Tiny\*(C'\fR will not do anything about handling possible errors coming from code located in these blocks. .Sp Furthermore \fBexceptions in \f(CB\*(C`finally\*(C'\fB blocks are not trappable and are unable to influence the execution of your program\fR. This is due to limitation of \&\f(CW\*(C`DESTROY\*(C'\fR\-based scope guards, which \f(CW\*(C`finally\*(C'\fR is implemented on top of. This may change in a future version of Try::Tiny. .Sp In the same way \f(CW\*(C`catch()\*(C'\fR blesses the code reference this subroutine does the same except it bless them as \f(CW\*(C`Try::Tiny::Finally\*(C'\fR. .SH "BACKGROUND" .IX Header "BACKGROUND" There are a number of issues with \f(CW\*(C`eval\*(C'\fR. .SS "Clobbering $@" .IX Subsection "Clobbering $@" When you run an \f(CW\*(C`eval\*(C'\fR block and it succeeds, \f(CW$@\fR will be cleared, potentially clobbering an error that is currently being caught. .PP This causes action at a distance, clearing previous errors your caller may have not yet handled. .PP \&\f(CW$@\fR must be properly localized before invoking \f(CW\*(C`eval\*(C'\fR in order to avoid this issue. .PP More specifically, before Perl version 5.14.0 \&\f(CW$@\fR was clobbered at the beginning of the \f(CW\*(C`eval\*(C'\fR, which also made it impossible to capture the previous error before you die (for instance when making exception objects with error stacks). .PP For this reason \f(CW\*(C`try\*(C'\fR will actually set \f(CW$@\fR to its previous value (the one available before entering the \f(CW\*(C`try\*(C'\fR block) in the beginning of the \f(CW\*(C`eval\*(C'\fR block. .SS "Localizing $@ silently masks errors" .IX Subsection "Localizing $@ silently masks errors" Inside an \f(CW\*(C`eval\*(C'\fR block, \f(CW\*(C`die\*(C'\fR behaves sort of like: .PP .Vb 4 \& sub die { \& $@ = $_[0]; \& return_undef_from_eval(); \& } .Ve .PP This means that if you were polite and localized \f(CW$@\fR you can't die in that scope, or your error will be discarded (printing \*(L"Something's wrong\*(R" instead). .PP The workaround is very ugly: .PP .Vb 5 \& my $error = do { \& local $@; \& eval { ... }; \& $@; \& }; \& \& ... \& die $error; .Ve .SS "$@ might not be a true value" .IX Subsection "$@ might not be a true value" This code is wrong: .PP .Vb 3 \& if ( $@ ) { \& ... \& } .Ve .PP because due to the previous caveats it may have been unset. .PP \&\f(CW$@\fR could also be an overloaded error object that evaluates to false, but that's asking for trouble anyway. .PP The classic failure mode (fixed in Perl 5.14.0) is: .PP .Vb 3 \& sub Object::DESTROY { \& eval { ... } \& } \& \& eval { \& my $obj = Object\->new; \& \& die "foo"; \& }; \& \& if ( $@ ) { \& \& } .Ve .PP In this case since \f(CW\*(C`Object::DESTROY\*(C'\fR is not localizing \f(CW$@\fR but still uses \&\f(CW\*(C`eval\*(C'\fR, it will set \f(CW$@\fR to \f(CW""\fR. .PP The destructor is called when the stack is unwound, after \f(CW\*(C`die\*(C'\fR sets \f(CW$@\fR to \&\f(CW"foo at Foo.pm line 42\en"\fR, so by the time \f(CW\*(C`if ( $@ )\*(C'\fR is evaluated it has been cleared by \f(CW\*(C`eval\*(C'\fR in the destructor. .PP The workaround for this is even uglier than the previous ones. Even though we can't save the value of \f(CW$@\fR from code that doesn't localize, we can at least be sure the \f(CW\*(C`eval\*(C'\fR was aborted due to an error: .PP .Vb 2 \& my $failed = not eval { \& ... \& \& return 1; \& }; .Ve .PP This is because an \f(CW\*(C`eval\*(C'\fR that caught a \f(CW\*(C`die\*(C'\fR will always return a false value. .SH "ALTERNATE SYNTAX" .IX Header "ALTERNATE SYNTAX" Using Perl 5.10 you can use \*(L"Switch statements\*(R" in perlsyn (but please don't, because that syntax has since been deprecated because there was too much unexpected magical behaviour). .PP The \f(CW\*(C`catch\*(C'\fR block is invoked in a topicalizer context (like a \f(CW\*(C`given\*(C'\fR block), but note that you can't return a useful value from \f(CW\*(C`catch\*(C'\fR using the \f(CW\*(C`when\*(C'\fR blocks without an explicit \f(CW\*(C`return\*(C'\fR. .PP This is somewhat similar to Perl 6's \f(CW\*(C`CATCH\*(C'\fR blocks. You can use it to concisely match errors: .PP .Vb 6 \& try { \& require Foo; \& } catch { \& when (/^Can\*(Aqt locate .*?\e.pm in \e@INC/) { } # ignore \& default { die $_ } \& }; .Ve .SH "CAVEATS" .IX Header "CAVEATS" .IP "\(bu" 4 \&\f(CW@_\fR is not available within the \f(CW\*(C`try\*(C'\fR block, so you need to copy your argument list. In case you want to work with argument values directly via \f(CW@_\fR aliasing (i.e. allow \f(CW\*(C`$_[1] = "foo"\*(C'\fR), you need to pass \f(CW@_\fR by reference: .Sp .Vb 4 \& sub foo { \& my ( $self, @args ) = @_; \& try { $self\->bar(@args) } \& } .Ve .Sp or .Sp .Vb 5 \& sub bar_in_place { \& my $self = shift; \& my $args = \e@_; \& try { $_ = $self\->bar($_) for @$args } \& } .Ve .IP "\(bu" 4 \&\f(CW\*(C`return\*(C'\fR returns from the \f(CW\*(C`try\*(C'\fR block, not from the parent sub (note that this is also how \f(CW\*(C`eval\*(C'\fR works, but not how TryCatch works): .Sp .Vb 7 \& sub parent_sub { \& try { \& die; \& } \& catch { \& return; \& }; \& \& say "this text WILL be displayed, even though an exception is thrown"; \& } .Ve .Sp Instead, you should capture the return value: .Sp .Vb 6 \& 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!"; \& } .Ve .Sp Note that if you have a \f(CW\*(C`catch\*(C'\fR block, it must return \f(CW\*(C`undef\*(C'\fR for this to work, since if a \f(CW\*(C`catch\*(C'\fR block exists, its return value is returned in place of \f(CW\*(C`undef\*(C'\fR when an exception is thrown. .IP "\(bu" 4 \&\f(CW\*(C`try\*(C'\fR introduces another caller stack frame. Sub::Uplevel is not used. Carp will not report this when using full stack traces, though, because \&\f(CW%Carp::Internal\fR is used. This lack of magic is considered a feature. .IP "\(bu" 4 The value of \f(CW$_\fR in the \f(CW\*(C`catch\*(C'\fR block is not guaranteed to be the value of the exception thrown (\f(CW$@\fR) in the \f(CW\*(C`try\*(C'\fR block. There is no safe way to ensure this, since \f(CW\*(C`eval\*(C'\fR may be used unhygienically in destructors. The only guarantee is that the \f(CW\*(C`catch\*(C'\fR will be called if an exception is thrown. .IP "\(bu" 4 The return value of the \f(CW\*(C`catch\*(C'\fR 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 \f(CW\*(C`catch\*(C'\fR block: .Sp .Vb 4 \& my $obj = try { \& MightFail\->new; \& } catch { \& ... \& \& return; # avoid returning a true value; \& }; \& \& return unless $obj; .Ve .IP "\(bu" 4 \&\f(CW$SIG{_\|_DIE_\|_}\fR is still in effect. .Sp Though it can be argued that \f(CW$SIG{_\|_DIE_\|_}\fR should be disabled inside of \&\f(CW\*(C`eval\*(C'\fR blocks, since it isn't people have grown to rely on it. Therefore in the interests of compatibility, \f(CW\*(C`try\*(C'\fR does not disable \f(CW$SIG{_\|_DIE_\|_}\fR for the scope of the error throwing code. .IP "\(bu" 4 Lexical \f(CW$_\fR may override the one set by \f(CW\*(C`catch\*(C'\fR. .Sp For example Perl 5.10's \f(CW\*(C`given\*(C'\fR form uses a lexical \f(CW$_\fR, creating some confusing behavior: .Sp .Vb 10 \& given ($foo) { \& when (...) { \& try { \& ... \& } catch { \& warn $_; # will print $foo, not the error \& warn $_[0]; # instead, get the error like this \& } \& } \& } .Ve .Sp Note that this behavior was changed once again in Perl5 version 18 . However, since the entirety of lexical \f(CW$_\fR is now considered experimental , it is unclear whether the new version 18 behavior is final. .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "Syntax::Keyword::Try" 4 .IX Item "Syntax::Keyword::Try" Only available on perls >= 5.14, with a slightly different syntax (e.g. no trailing \f(CW\*(C`;\*(C'\fR because it's actually a keyword, not a sub, but this means you can \f(CW\*(C`return\*(C'\fR and \f(CW\*(C`next\*(C'\fR within it). Use Feature::Compat::Try to automatically switch to the native \f(CW\*(C`try\*(C'\fR syntax in newer perls (when available). See also Try Catch Exception Handling. .IP "TryCatch" 4 .IX Item "TryCatch" Much more feature complete, more convenient semantics, but at the cost of implementation complexity. .IP "autodie" 4 .IX Item "autodie" Automatic error throwing for builtin functions and more. Also designed to work well with \f(CW\*(C`given\*(C'\fR/\f(CW\*(C`when\*(C'\fR. .IP "Throwable" 4 .IX Item "Throwable" A lightweight role for rolling your own exception classes. .IP "Error" 4 .IX Item "Error" Exception object implementation with a \f(CW\*(C`try\*(C'\fR statement. Does not localize \&\f(CW$@\fR. .IP "Exception::Class::TryCatch" 4 .IX Item "Exception::Class::TryCatch" Provides a \f(CW\*(C`catch\*(C'\fR statement, but properly calling \f(CW\*(C`eval\*(C'\fR is your responsibility. .Sp The \f(CW\*(C`try\*(C'\fR keyword pushes \f(CW$@\fR onto an error stack, avoiding some of the issues with \f(CW$@\fR, but you still need to localize to prevent clobbering. .SH "LIGHTNING TALK" .IX Header "LIGHTNING TALK" I gave a lightning talk about this module, you can see the slides (Firefox only): .PP .PP Or read the source: .PP .SH "SUPPORT" .IX Header "SUPPORT" Bugs may be submitted through the \s-1RT\s0 bug tracker (or bug\-Try\-Tiny@rt.cpan.org ). .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 יובל קוג'מן (Yuval Kogman) .IP "\(bu" 4 Jesse Luehrs .SH "CONTRIBUTORS" .IX Header "CONTRIBUTORS" .IP "\(bu" 4 Karen Etheridge .IP "\(bu" 4 Peter Rabbitson .IP "\(bu" 4 Ricardo Signes .IP "\(bu" 4 Mark Fowler .IP "\(bu" 4 Graham Knop .IP "\(bu" 4 Aristotle Pagaltzis .IP "\(bu" 4 Dagfinn Ilmari Mannsåker .IP "\(bu" 4 Lukas Mai .IP "\(bu" 4 Alex .IP "\(bu" 4 anaxagoras .IP "\(bu" 4 Andrew Yates .IP "\(bu" 4 awalker .IP "\(bu" 4 chromatic .IP "\(bu" 4 cm-perl .IP "\(bu" 4 David Lowe .IP "\(bu" 4 Glenn Fowler .IP "\(bu" 4 Hans Dieter Pearcey .IP "\(bu" 4 Jens Berthold .IP "\(bu" 4 Jonathan Yu .IP "\(bu" 4 Marc Mims .IP "\(bu" 4 Mark Stosberg .IP "\(bu" 4 Pali .IP "\(bu" 4 Paul Howarth .IP "\(bu" 4 Rudolf Leermakers .SH "COPYRIGHT AND LICENCE" .IX Header "COPYRIGHT AND LICENCE" This software is Copyright (c) 2009 by יובל קוג'מן (Yuval Kogman). .PP This is free software, licensed under: .PP .Vb 1 \& The MIT (X11) License .Ve PK!j:j:man/man3/version.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "version 3" .TH version 3 "2024-04-28" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" version \- Perl extension for Version Objects .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& # Parsing version strings (decimal or dotted\-decimal) \& \& use version 0.77; # get latest bug\-fixes and API \& $ver = version\->parse($string) \& \& # Declaring a dotted\-decimal $VERSION (keep on one line!) \& \& use version; our $VERSION = version\->declare("v1.2.3"); # formal \& use version; our $VERSION = qv("v1.2.3"); # deprecated \& use version; our $VERSION = qv("v1.2_3"); # deprecated \& \& # Declaring an old\-style decimal $VERSION (use quotes!) \& \& our $VERSION = "1.0203"; # recommended \& use version; our $VERSION = version\->parse("1.0203"); # formal \& use version; our $VERSION = version\->parse("1.02_03"); # alpha \& \& # Comparing mixed version styles (decimals, dotted\-decimals, objects) \& \& if ( version\->parse($v1) == version\->parse($v2) ) { \& # do stuff \& } \& \& # Sorting mixed version styles \& \& @ordered = sort { version\->parse($a) <=> version\->parse($b) } @list; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" Version objects were added to Perl in 5.10. This module implements version objects for older version of Perl and provides the version object \s-1API\s0 for all versions of Perl. All previous releases before 0.74 are deprecated and should not be used due to incompatible \s-1API\s0 changes. Version 0.77 introduces the new \&'parse' and 'declare' methods to standardize usage. You are strongly urged to set 0.77 as a minimum in your code, e.g. .PP .Vb 1 \& use version 0.77; # even for Perl v.5.10.0 .Ve .SH "TYPES OF VERSION OBJECTS" .IX Header "TYPES OF VERSION OBJECTS" There are two different types of version objects, corresponding to the two different styles of versions in use: .IP "Decimal Versions" 2 .IX Item "Decimal Versions" The classic floating-point number \f(CW$VERSION\fR. The advantage to this style is that you don't need to do anything special, just type a number into your source file. Quoting is recommended, as it ensures that trailing zeroes (\*(L"1.50\*(R") are preserved in any warnings or other output. .IP "Dotted Decimal Versions" 2 .IX Item "Dotted Decimal Versions" The more modern form of version assignment, with 3 (or potentially more) integers separated by decimal points (e.g. v1.2.3). This is the form that Perl itself has used since 5.6.0 was released. The leading 'v' is now strongly recommended for clarity, and will throw a warning in a future release if omitted. A leading 'v' character is required to pass the \&\*(L"\fBis_strict()\fR\*(R" test. .SH "DECLARING VERSIONS" .IX Header "DECLARING VERSIONS" If you have a module that uses a decimal \f(CW$VERSION\fR (floating point), and you do not intend to ever change that, this module is not for you. There is nothing that version.pm gains you over a simple \f(CW$VERSION\fR assignment: .PP .Vb 1 \& our $VERSION = "1.02"; .Ve .PP Since Perl v5.10.0 includes the version.pm comparison logic anyways, you don't need to do anything at all. .SS "How to convert a module from decimal to dotted-decimal" .IX Subsection "How to convert a module from decimal to dotted-decimal" If you have used a decimal \f(CW$VERSION\fR in the past and wish to switch to a dotted-decimal \f(CW$VERSION\fR, then you need to make a one-time conversion to the new format. .PP \&\fBImportant Note\fR: you must ensure that your new \f(CW$VERSION\fR is numerically greater than your current decimal \f(CW$VERSION\fR; this is not always obvious. First, convert your old decimal version (e.g. 1.02) to a normalized dotted-decimal form: .PP .Vb 2 \& $ perl \-Mversion \-e \*(Aqprint version\->parse("1.02")\->normal\*(Aq \& v1.20.0 .Ve .PP Then increment any of the dotted-decimal components (v1.20.1 or v1.21.0). .ie n .SS "How to ""declare()"" a dotted-decimal version" .el .SS "How to \f(CWdeclare()\fP a dotted-decimal version" .IX Subsection "How to declare() a dotted-decimal version" .Vb 1 \& use version; our $VERSION = version\->declare("v1.2.3"); .Ve .PP The \f(CW\*(C`declare()\*(C'\fR method always creates dotted-decimal version objects. When used in a module, you \fBmust\fR put it on the same line as \*(L"use version\*(R" to ensure that \f(CW$VERSION\fR is read correctly by \s-1PAUSE\s0 and installer tools. You should also add 'version' to the 'configure_requires' section of your module metadata file. See instructions in ExtUtils::MakeMaker or Module::Build for details. .PP \&\fBImportant Note\fR: Even if you pass in what looks like a decimal number (\*(L"1.2\*(R"), a dotted-decimal will be created (\*(L"v1.200.0\*(R"). To avoid confusion or unintentional errors on older Perls, follow these guidelines: .IP "\(bu" 2 Always use a dotted-decimal with (at least) three components .IP "\(bu" 2 Always use a leading-v .IP "\(bu" 2 Always quote the version .PP If you really insist on using version.pm with an ordinary decimal version, use \f(CW\*(C`parse()\*(C'\fR instead of declare. See the \*(L"\s-1PARSING AND COMPARING VERSIONS\*(R"\s0 for details. .PP See also version::Internals for more on version number conversion, quoting, calculated version numbers and declaring developer or \*(L"alpha\*(R" version numbers. .SH "PARSING AND COMPARING VERSIONS" .IX Header "PARSING AND COMPARING VERSIONS" If you need to compare version numbers, but can't be sure whether they are expressed as numbers, strings, v\-strings or version objects, then you should use version.pm to parse them all into objects for comparison. .ie n .SS "How to ""parse()"" a version" .el .SS "How to \f(CWparse()\fP a version" .IX Subsection "How to parse() a version" The \f(CW\*(C`parse()\*(C'\fR method takes in anything that might be a version and returns a corresponding version object, doing any necessary conversion along the way. .IP "\(bu" 2 Dotted-decimal: bare v\-strings (v1.2.3) and strings with more than one decimal point and a leading 'v' (\*(L"v1.2.3\*(R"); \s-1NOTE\s0 you can technically use a v\-string or strings with a leading-v and only one decimal point (v1.2 or \&\*(L"v1.2\*(R"), but you will confuse both yourself and others. .IP "\(bu" 2 Decimal: regular decimal numbers (literal or in a string) .PP Some examples: .PP .Vb 8 \& $variable version\->parse($variable) \& \-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& 1.23 v1.230.0 \& "1.23" v1.230.0 \& v1.23 v1.23.0 \& "v1.23" v1.23.0 \& "1.2.3" v1.2.3 \& "v1.2.3" v1.2.3 .Ve .PP See version::Internals for more on version number conversion. .SS "How to check for a legal version string" .IX Subsection "How to check for a legal version string" If you do not want to actually create a full blown version object, but would still like to verify that a given string meets the criteria to be parsed as a version, there are two helper functions that can be employed directly: .ie n .IP """is_lax()""" 4 .el .IP "\f(CWis_lax()\fR" 4 .IX Item "is_lax()" The lax criteria corresponds to what is currently allowed by the version parser. All of the following formats are acceptable for dotted-decimal formats strings: .Sp .Vb 5 \& v1.2 \& 1.2345.6 \& v1.23_4 \& 1.2345 \& 1.2345_01 .Ve .ie n .IP """is_strict()""" 4 .el .IP "\f(CWis_strict()\fR" 4 .IX Item "is_strict()" If you want to limit yourself to a much more narrow definition of what a version string constitutes, \f(CW\*(C`is_strict()\*(C'\fR is limited to version strings like the following list: .Sp .Vb 2 \& v1.234.5 \& 2.3456 .Ve .PP See version::Internals for details of the regular expressions that define the legal version string forms, as well as how to use those regular expressions in your own code if \f(CW\*(C`is_lax()\*(C'\fR and \&\f(CW\*(C`is_strict()\*(C'\fR are not sufficient for your needs. .SS "How to compare version objects" .IX Subsection "How to compare version objects" Version objects overload the \f(CW\*(C`cmp\*(C'\fR and \f(CW\*(C`<=>\*(C'\fR operators. Perl automatically generates all of the other comparison operators based on those two so all the normal logical comparisons will work. .PP .Vb 3 \& if ( version\->parse($v1) == version\->parse($v2) ) { \& # do stuff \& } .Ve .PP If a version object is compared against a non-version object, the non-object term will be converted to a version object using \f(CW\*(C`parse()\*(C'\fR. This may give surprising results: .PP .Vb 2 \& $v1 = version\->parse("v0.95.0"); \& $bool = $v1 < 0.94; # TRUE since 0.94 is v0.940.0 .Ve .PP Always comparing to a version object will help avoid surprises: .PP .Vb 1 \& $bool = $v1 < version\->parse("v0.94.0"); # FALSE .Ve .PP Note that \*(L"alpha\*(R" version objects (where the version string contains a trailing underscore segment) compare as less than the equivalent version without an underscore: .PP .Vb 1 \& $bool = version\->parse("1.23_45") < version\->parse("1.2345"); # TRUE .Ve .PP See version::Internals for more details on \*(L"alpha\*(R" versions. .SH "OBJECT METHODS" .IX Header "OBJECT METHODS" .SS "\fBis_alpha()\fP" .IX Subsection "is_alpha()" True if and only if the version object was created with a underscore, e.g. .PP .Vb 2 \& version\->parse(\*(Aq1.002_03\*(Aq)\->is_alpha; # TRUE \& version\->declare(\*(Aq1.2.3_4\*(Aq)\->is_alpha; # TRUE .Ve .SS "\fBis_qv()\fP" .IX Subsection "is_qv()" True only if the version object is a dotted-decimal version, e.g. .PP .Vb 4 \& version\->parse(\*(Aqv1.2.0\*(Aq)\->is_qv; # TRUE \& version\->declare(\*(Aqv1.2\*(Aq)\->is_qv; # TRUE \& qv(\*(Aq1.2\*(Aq)\->is_qv; # TRUE \& version\->parse(\*(Aq1.2\*(Aq)\->is_qv; # FALSE .Ve .SS "\fBnormal()\fP" .IX Subsection "normal()" Returns a string with a standard 'normalized' dotted-decimal form with a leading-v and at least 3 components. .PP .Vb 2 \& version\->declare(\*(Aqv1.2\*(Aq)\->normal; # v1.2.0 \& version\->parse(\*(Aq1.2\*(Aq)\->normal; # v1.200.0 .Ve .SS "\fBnumify()\fP" .IX Subsection "numify()" Returns a value representing the object in a pure decimal. .PP .Vb 2 \& version\->declare(\*(Aqv1.2\*(Aq)\->numify; # 1.002000 \& version\->parse(\*(Aq1.2\*(Aq)\->numify; # 1.200 .Ve .SS "to_decimal" .IX Subsection "to_decimal" This returns a new version object for the numified version, much like \f(CW\*(C`version\->parse($v\->numify)\*(C'\fR would. .PP .Vb 1 \& version\->parse(\*(Aqv1.2\*(Aq)\->to_decimal; # 1.002000 .Ve .SS "to_dotted_decimal" .IX Subsection "to_dotted_decimal" This returns a new version object for the normalized version, much like \f(CW\*(C`version\->parse($v\->normal)\*(C'\fR would. .PP .Vb 1 \& version\->parse(\*(Aq1.002\*(Aq)\->to_dotted_decimal; # v1.2.0 .Ve .SS "\fBtuple()\fP" .IX Subsection "tuple()" This turns the components of the version into a list. E.g. .PP .Vb 1 \& version\->parse(\*(Aq1.2.3\*(Aq)\->tuple; # (1, 2, 3) .Ve .SS "from_tuple(...)" .IX Subsection "from_tuple(...)" This takes a list of components and creates a dotted decimal version out of it. E.g. .PP .Vb 1 \& version\->from_tuple(1, 2, 3) # v1.2.3 .Ve .SS "\fBstringify()\fP" .IX Subsection "stringify()" Returns a string that is as close to the original representation as possible. If the original representation was a numeric literal, it will be returned the way perl would normally represent it in a string. This method is used whenever a version object is interpolated into a string. .PP .Vb 3 \& version\->declare(\*(Aqv1.2\*(Aq)\->stringify; # v1.2 \& version\->parse(\*(Aq1.200\*(Aq)\->stringify; # 1.2 \& version\->parse(1.02_30)\->stringify; # 1.023 .Ve .SS "tuple" .IX Subsection "tuple" Returns an array of non-negative integers that is used for comparison purposes with other version objects. .SH "EXPORTED FUNCTIONS" .IX Header "EXPORTED FUNCTIONS" .SS "\fBqv()\fP" .IX Subsection "qv()" This function is no longer recommended for use, but is maintained for compatibility with existing code. If you do not want to have it exported to your namespace, use this form: .PP .Vb 1 \& use version 0.77 (); .Ve .SS "\fBis_lax()\fP" .IX Subsection "is_lax()" (Not exported by default) .PP This function takes a scalar argument and returns a boolean value indicating whether the argument meets the \*(L"lax\*(R" rules for a version number. Leading and trailing spaces are not allowed. .SS "\fBis_strict()\fP" .IX Subsection "is_strict()" (Not exported by default) .PP This function takes a scalar argument and returns a boolean value indicating whether the argument meets the \*(L"strict\*(R" rules for a version number. Leading and trailing spaces are not allowed. .SH "AUTHOR" .IX Header "AUTHOR" John Peacock .SH "SEE ALSO" .IX Header "SEE ALSO" version::Internals. .PP perl. PK!F?sDoDoman/man3/version::Internals.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "version::Internals 3" .TH version::Internals 3 "2024-04-28" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" version::Internals \- Perl extension for Version Objects .SH "DESCRIPTION" .IX Header "DESCRIPTION" Overloaded version objects for all modern versions of Perl. This documents the internal data representation and underlying code for version.pm. See \&\fIversion.pod\fR for daily usage. This document is only useful for users interested in the gory details. .SH "WHAT IS A VERSION?" .IX Header "WHAT IS A VERSION?" For the purposes of this module, a version \*(L"number\*(R" is a sequence of positive integer values separated by one or more decimal points and optionally a single underscore. This corresponds to what Perl itself uses for a version, as well as extending the \*(L"version as number\*(R" that is discussed in the various editions of the Camel book. .PP There are actually two distinct kinds of version objects: .IP "Decimal versions" 4 .IX Item "Decimal versions" Any version which \*(L"looks like a number\*(R", see \*(L"Decimal Versions\*(R". This also includes versions with a single decimal point and a single embedded underscore, see \*(L"Alpha Versions\*(R", even though these must be quoted to preserve the underscore formatting. .IP "Dotted-Decimal versions" 4 .IX Item "Dotted-Decimal versions" Also referred to as \*(L"Dotted-Integer\*(R", these contains more than one decimal point and may have an optional embedded underscore, see Dotted-Decimal Versions. This is what is commonly used in most open source software as the \*(L"external\*(R" version (the one used as part of the tag or tarfile name). A leading 'v' character is now required and will warn if it missing. .PP Both of these methods will produce similar version objects, in that the default stringification will yield the version \*(L"Normal Form\*(R" only if required: .PP .Vb 3 \& $v = version\->new(1.002); # 1.002, but compares like 1.2.0 \& $v = version\->new(1.002003); # 1.002003 \& $v2 = version\->new("v1.2.3"); # v1.2.3 .Ve .PP In specific, version numbers initialized as \*(L"Decimal Versions\*(R" will stringify as they were originally created (i.e. the same string that was passed to \f(CW\*(C`new()\*(C'\fR. Version numbers initialized as \*(L"Dotted-Decimal Versions\*(R" will be stringified as \*(L"Normal Form\*(R". .SS "Decimal Versions" .IX Subsection "Decimal Versions" These correspond to historical versions of Perl itself prior to 5.6.0, as well as all other modules which follow the Camel rules for the \&\f(CW$VERSION\fR scalar. A Decimal version is initialized with what looks like a floating point number. Leading zeros \fBare\fR significant and trailing zeros are implied so that a minimum of three places is maintained between subversions. What this means is that any subversion (digits to the right of the decimal place) that contains less than three digits will have trailing zeros added to make up the difference, but only for purposes of comparison with other version objects. For example: .PP .Vb 7 \& # Prints Equivalent to \& $v = version\->new( 1.2); # 1.2 v1.200.0 \& $v = version\->new( 1.02); # 1.02 v1.20.0 \& $v = version\->new( 1.002); # 1.002 v1.2.0 \& $v = version\->new( 1.0023); # 1.0023 v1.2.300 \& $v = version\->new( 1.00203); # 1.00203 v1.2.30 \& $v = version\->new( 1.002003); # 1.002003 v1.2.3 .Ve .PP All of the preceding examples are true whether or not the input value is quoted. The important feature is that the input value contains only a single decimal. See also \*(L"Alpha Versions\*(R". .PP \&\s-1IMPORTANT NOTE:\s0 As shown above, if your Decimal version contains more than 3 significant digits after the decimal place, it will be split on each multiple of 3, so 1.0003 is equivalent to v1.0.300, due to the need to remain compatible with Perl's own 5.005_03 == 5.5.30 interpretation. Any trailing zeros are ignored for mathematical comparison purposes. .SS "Dotted-Decimal Versions" .IX Subsection "Dotted-Decimal Versions" These are the newest form of versions, and correspond to Perl's own version style beginning with 5.6.0. Starting with Perl 5.10.0, and most likely Perl 6, this is likely to be the preferred form. This method normally requires that the input parameter be quoted, although Perl's after 5.8.1 can use v\-strings as a special form of quoting, but this is highly discouraged. .PP Unlike \*(L"Decimal Versions\*(R", Dotted-Decimal Versions have more than a single decimal point, e.g.: .PP .Vb 6 \& # Prints \& $v = version\->new( "v1.200"); # v1.200.0 \& $v = version\->new("v1.20.0"); # v1.20.0 \& $v = qv("v1.2.3"); # v1.2.3 \& $v = qv("1.2.3"); # v1.2.3 \& $v = qv("1.20"); # v1.20.0 .Ve .PP In general, Dotted-Decimal Versions permit the greatest amount of freedom to specify a version, whereas Decimal Versions enforce a certain uniformity. .PP Just like \*(L"Decimal Versions\*(R", Dotted-Decimal Versions can be used as \&\*(L"Alpha Versions\*(R". .SS "Alpha Versions" .IX Subsection "Alpha Versions" For module authors using \s-1CPAN,\s0 the convention has been to note unstable releases with an underscore in the version string. (See \s-1CPAN\s0.) version.pm follows this convention and alpha releases will test as being newer than the more recent stable release, and less than the next stable release. Only the last element may be separated by an underscore: .PP .Vb 2 \& # Declaring \& use version 0.77; our $VERSION = version\->declare("v1.2_3"); \& \& # Parsing \& $v1 = version\->parse("v1.2_3"); \& $v1 = version\->parse("1.002_003"); .Ve .PP Note that you \fBmust\fR quote the version when writing an alpha Decimal version. The stringified form of Decimal versions will always be the same string that was used to initialize the version object. .SS "Regular Expressions for Version Parsing" .IX Subsection "Regular Expressions for Version Parsing" A formalized definition of the legal forms for version strings is included in the \f(CW\*(C`version::regex\*(C'\fR class. Primitives are included for common elements, although they are scoped to the file so they are useful for reference purposes only. There are two publicly accessible scalars that can be used in other code (not exported): .ie n .IP "$version::LAX" 4 .el .IP "\f(CW$version::LAX\fR" 4 .IX Item "$version::LAX" This regexp covers all of the legal forms allowed under the current version string parser. This is not to say that all of these forms are recommended, and some of them can only be used when quoted. .Sp For dotted decimals: .Sp .Vb 3 \& v1.2 \& 1.2345.6 \& v1.23_4 .Ve .Sp The leading 'v' is optional if two or more decimals appear. If only a single decimal is included, then the leading 'v' is required to trigger the dotted-decimal parsing. A leading zero is permitted, though not recommended except when quoted, because of the risk that Perl will treat the number as octal. A trailing underscore plus one or more digits denotes an alpha or development release (and must be quoted to be parsed properly). .Sp For decimal versions: .Sp .Vb 3 \& 1 \& 1.2345 \& 1.2345_01 .Ve .Sp an integer portion, an optional decimal point, and optionally one or more digits to the right of the decimal are all required. A trailing underscore is permitted and a leading zero is permitted. Just like the lax dotted-decimal version, quoting the values is required for alpha/development forms to be parsed correctly. .ie n .IP "$version::STRICT" 4 .el .IP "\f(CW$version::STRICT\fR" 4 .IX Item "$version::STRICT" This regexp covers a much more limited set of formats and constitutes the best practices for initializing version objects. Whether you choose to employ decimal or dotted-decimal for is a personal preference however. .RS 4 .IP "v1.234.5" 4 .IX Item "v1.234.5" For dotted-decimal versions, a leading 'v' is required, with three or more sub-versions of no more than three digits. A leading 0 (zero) before the first sub-version (in the above example, '1') is also prohibited. .IP "2.3456" 4 .IX Item "2.3456" For decimal versions, an integer portion (no leading 0), a decimal point, and one or more digits to the right of the decimal are all required. .RE .RS 4 .RE .PP Both of the provided scalars are already compiled as regular expressions and do not contain either anchors or implicit groupings, so they can be included in your own regular expressions freely. For example, consider the following code: .PP .Vb 6 \& ($pkg, $ver) =~ / \& ^[ \et]* \& use [ \et]+($PKGNAME) \& (?:[ \et]+($version::STRICT))? \& [ \et]*; \& /x; .Ve .PP This would match a line of the form: .PP .Vb 1 \& use Foo::Bar::Baz v1.2.3; # legal only in Perl 5.8.1+ .Ve .PP where \f(CW$PKGNAME\fR is another regular expression that defines the legal forms for package names. .SH "IMPLEMENTATION DETAILS" .IX Header "IMPLEMENTATION DETAILS" .SS "Equivalence between Decimal and Dotted-Decimal Versions" .IX Subsection "Equivalence between Decimal and Dotted-Decimal Versions" When Perl 5.6.0 was released, the decision was made to provide a transformation between the old-style decimal versions and new-style dotted-decimal versions: .PP .Vb 2 \& 5.6.0 == 5.006000 \& 5.005_04 == 5.5.40 .Ve .PP The floating point number is taken and split first on the single decimal place, then each group of three digits to the right of the decimal makes up the next digit, and so on until the number of significant digits is exhausted, \&\fBplus\fR enough trailing zeros to reach the next multiple of three. .PP This was the method that version.pm adopted as well. Some examples may be helpful: .PP .Vb 9 \& equivalent \& decimal zero\-padded dotted\-decimal \& \-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\- \& 1.2 1.200 v1.200.0 \& 1.02 1.020 v1.20.0 \& 1.002 1.002 v1.2.0 \& 1.0023 1.002300 v1.2.300 \& 1.00203 1.002030 v1.2.30 \& 1.002003 1.002003 v1.2.3 .Ve .SS "Quoting Rules" .IX Subsection "Quoting Rules" Because of the nature of the Perl parsing and tokenizing routines, certain initialization values \fBmust\fR be quoted in order to correctly parse as the intended version, especially when using the \f(CW\*(C`declare\*(C'\fR or \&\*(L"\fBqv()\fR\*(R" methods. While you do not have to quote decimal numbers when creating version objects, it is always safe to quote \fBall\fR initial values when using version.pm methods, as this will ensure that what you type is what is used. .PP Additionally, if you quote your initializer, then the quoted value that goes \&\fBin\fR will be exactly what comes \fBout\fR when your \f(CW$VERSION\fR is printed (stringified). If you do not quote your value, Perl's normal numeric handling comes into play and you may not get back what you were expecting. .PP If you use a mathematic formula that resolves to a floating point number, you are dependent on Perl's conversion routines to yield the version you expect. You are pretty safe by dividing by a power of 10, for example, but other operations are not likely to be what you intend. For example: .PP .Vb 4 \& $VERSION = version\->new((qw$Revision: 1.4)[1]/10); \& print $VERSION; # yields 0.14 \& $V2 = version\->new(100/9); # Integer overflow in decimal number \& print $V2; # yields something like 11.111.111.100 .Ve .PP Perl 5.8.1 and beyond are able to automatically quote v\-strings but that is not possible in earlier versions of Perl. In other words: .PP .Vb 2 \& $version = version\->new("v2.5.4"); # legal in all versions of Perl \& $newvers = version\->new(v2.5.4); # legal only in Perl >= 5.8.1 .Ve .SS "What about v\-strings?" .IX Subsection "What about v-strings?" There are two ways to enter v\-strings: a bare number with two or more decimal points, or a bare number with one or more decimal points and a leading 'v' character (also bare). For example: .PP .Vb 2 \& $vs1 = 1.2.3; # encoded as \e1\e2\e3 \& $vs2 = v1.2; # encoded as \e1\e2 .Ve .PP However, the use of bare v\-strings to initialize version objects is \&\fBstrongly\fR discouraged in all circumstances. Also, bare v\-strings are not completely supported in any version of Perl prior to 5.8.1. .PP If you insist on using bare v\-strings with Perl > 5.6.0, be aware of the following limitations: .PP 1) For Perl releases 5.6.0 through 5.8.0, the v\-string code merely guesses, based on some characteristics of v\-strings. You \fBmust\fR use a three part version, e.g. 1.2.3 or v1.2.3 in order for this heuristic to be successful. .PP 2) For Perl releases 5.8.1 and later, v\-strings have changed in the Perl core to be magical, which means that the version.pm code can automatically determine whether the v\-string encoding was used. .PP 3) In all cases, a version created using v\-strings will have a stringified form that has a leading 'v' character, for the simple reason that sometimes it is impossible to tell whether one was present initially. .SS "Replacement \s-1UNIVERSAL::VERSION\s0" .IX Subsection "Replacement UNIVERSAL::VERSION" In addition to the version objects, this modules also replaces the core \&\s-1UNIVERSAL::VERSION\s0 function with one that uses version objects for its comparisons. The return from this operator is always the stringified form as a simple scalar (i.e. not an object), but the warning message generated includes either the stringified form or the normal form, depending on how it was called. .PP For example: .PP .Vb 2 \& package Foo; \& $VERSION = 1.2; \& \& package Bar; \& $VERSION = "v1.3.5"; # works with all Perl\*(Aqs (since it is quoted) \& \& package main; \& use version; \& \& print $Foo::VERSION; # prints 1.2 \& \& print $Bar::VERSION; # prints 1.003005 \& \& eval "use foo 10"; \& print $@; # prints "foo version 10 required..." \& eval "use foo 1.3.5; # work in Perl 5.6.1 or better \& print $@; # prints "foo version 1.3.5 required..." \& \& eval "use bar 1.3.6"; \& print $@; # prints "bar version 1.3.6 required..." \& eval "use bar 1.004"; # note Decimal version \& print $@; # prints "bar version 1.004 required..." .Ve .PP \&\s-1IMPORTANT NOTE:\s0 This may mean that code which searches for a specific string (to determine whether a given module is available) may need to be changed. It is always better to use the built-in comparison implicit in \&\f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR, rather than manually poking at \f(CW\*(C`class\->VERSION\*(C'\fR and then doing a comparison yourself. .PP The replacement \s-1UNIVERSAL::VERSION,\s0 when used as a function, like this: .PP .Vb 1 \& print $module\->VERSION; .Ve .PP will also exclusively return the stringified form. See \*(L"Stringification\*(R" for more details. .SH "USAGE DETAILS" .IX Header "USAGE DETAILS" .SS "Using modules that use version.pm" .IX Subsection "Using modules that use version.pm" As much as possible, the version.pm module remains compatible with all current code. However, if your module is using a module that has defined \&\f(CW$VERSION\fR using the version class, there are a couple of things to be aware of. For purposes of discussion, we will assume that we have the following module installed: .PP .Vb 4 \& package Example; \& use version; $VERSION = qv(\*(Aq1.2.2\*(Aq); \& ...module code here... \& 1; .Ve .IP "Decimal versions always work" 4 .IX Item "Decimal versions always work" Code of the form: .Sp .Vb 1 \& use Example 1.002003; .Ve .Sp will always work correctly. The \f(CW\*(C`use\*(C'\fR will perform an automatic \&\f(CW$VERSION\fR comparison using the floating point number given as the first term after the module name (e.g. above 1.002.003). In this case, the installed module is too old for the requested line, so you would see an error like: .Sp .Vb 1 \& Example version 1.002003 (v1.2.3) required\-\-this is only version 1.002002 (v1.2.2)... .Ve .IP "Dotted-Decimal version work sometimes" 4 .IX Item "Dotted-Decimal version work sometimes" With Perl >= 5.6.2, you can also use a line like this: .Sp .Vb 1 \& use Example 1.2.3; .Ve .Sp and it will again work (i.e. give the error message as above), even with releases of Perl which do not normally support v\-strings (see \*(L"What about v\-strings?\*(R" above). This has to do with that fact that \f(CW\*(C`use\*(C'\fR only checks to see if the second term \fIlooks like a number\fR and passes that to the replacement \s-1UNIVERSAL::VERSION\s0. This is not true in Perl 5.005_04, however, so you are \fBstrongly encouraged\fR to always use a Decimal version in your code, even for those versions of Perl which support the Dotted-Decimal version. .SS "Object Methods" .IX Subsection "Object Methods" .IP "\fBnew()\fR" 4 .IX Item "new()" Like many \s-1OO\s0 interfaces, the \fBnew()\fR method is used to initialize version objects. If two arguments are passed to \f(CW\*(C`new()\*(C'\fR, the \fBsecond\fR one will be used as if it were prefixed with \*(L"v\*(R". This is to support historical use of the \&\f(CW\*(C`qw\*(C'\fR operator with the \s-1CVS\s0 variable \f(CW$Revision\fR, which is automatically incremented by \s-1CVS\s0 every time the file is committed to the repository. .Sp In order to facilitate this feature, the following code can be employed: .Sp .Vb 1 \& $VERSION = version\->new(qw$Revision: 2.7 $); .Ve .Sp and the version object will be created as if the following code were used: .Sp .Vb 1 \& $VERSION = version\->new("v2.7"); .Ve .Sp In other words, the version will be automatically parsed out of the string, and it will be quoted to preserve the meaning \s-1CVS\s0 normally carries for versions. The \s-1CVS\s0 \f(CW$Revision\fR$ increments differently from Decimal versions (i.e. 1.10 follows 1.9), so it must be handled as if it were a Dotted-Decimal Version. .Sp A new version object can be created as a copy of an existing version object, either as a class method: .Sp .Vb 2 \& $v1 = version\->new(12.3); \& $v2 = version\->new($v1); .Ve .Sp or as an object method: .Sp .Vb 2 \& $v1 = version\->new(12.3); \& $v2 = $v1\->new(12.3); .Ve .Sp and in each case, \f(CW$v1\fR and \f(CW$v2\fR will be identical. \s-1NOTE:\s0 if you create a new object using an existing object like this: .Sp .Vb 1 \& $v2 = $v1\->new(); .Ve .Sp the new object \fBwill not\fR be a clone of the existing object. In the example case, \f(CW$v2\fR will be an empty object of the same type as \f(CW$v1\fR. .IP "\fBqv()\fR" 4 .IX Item "qv()" An alternate way to create a new version object is through the exported \&\fBqv()\fR sub. This is not strictly like other q? operators (like qq, qw), in that the only delimiters supported are parentheses (or spaces). It is the best way to initialize a short version without triggering the floating point interpretation. For example: .Sp .Vb 2 \& $v1 = qv(1.2); # v1.2.0 \& $v2 = qv("1.2"); # also v1.2.0 .Ve .Sp As you can see, either a bare number or a quoted string can usually be used interchangeably, except in the case of a trailing zero, which must be quoted to be converted properly. For this reason, it is strongly recommended that all initializers to \fBqv()\fR be quoted strings instead of bare numbers. .Sp To prevent the \f(CW\*(C`qv()\*(C'\fR function from being exported to the caller's namespace, either use version with a null parameter: .Sp .Vb 1 \& use version (); .Ve .Sp or just require version, like this: .Sp .Vb 1 \& require version; .Ve .Sp Both methods will prevent the \fBimport()\fR method from firing and exporting the \&\f(CW\*(C`qv()\*(C'\fR sub. .PP For the subsequent examples, the following three objects will be used: .PP .Vb 3 \& $ver = version\->new("1.2.3.4"); # see "Quoting Rules" \& $alpha = version\->new("1.2.3_4"); # see "Alpha Versions" \& $nver = version\->new(1.002); # see "Decimal Versions" .Ve .IP "Normal Form" 4 .IX Item "Normal Form" For any version object which is initialized with multiple decimal places (either quoted or if possible v\-string), or initialized using the \fBqv()\fR operator, the stringified representation is returned in a normalized or reduced form (no extraneous zeros), and with a leading 'v': .Sp .Vb 6 \& print $ver\->normal; # prints as v1.2.3.4 \& print $ver\->stringify; # ditto \& print $ver; # ditto \& print $nver\->normal; # prints as v1.2.0 \& print $nver\->stringify; # prints as 1.002, \& # see "Stringification" .Ve .Sp In order to preserve the meaning of the processed version, the normalized representation will always contain at least three sub terms. In other words, the following is guaranteed to always be true: .Sp .Vb 3 \& my $newver = version\->new($ver\->stringify); \& if ($newver eq $ver ) # always true \& {...} .Ve .IP "Numification" 4 .IX Item "Numification" Although all mathematical operations on version objects are forbidden by default, it is possible to retrieve a number which corresponds to the version object through the use of the \f(CW$obj\fR\->numify method. For formatting purposes, when displaying a number which corresponds a version object, all sub versions are assumed to have three decimal places. So for example: .Sp .Vb 2 \& print $ver\->numify; # prints 1.002003004 \& print $nver\->numify; # prints 1.002 .Ve .Sp Unlike the stringification operator, there is never any need to append trailing zeros to preserve the correct version value. .IP "Stringification" 4 .IX Item "Stringification" The default stringification for version objects returns exactly the same string as was used to create it, whether you used \f(CW\*(C`new()\*(C'\fR or \f(CW\*(C`qv()\*(C'\fR, with one exception. The sole exception is if the object was created using \&\f(CW\*(C`qv()\*(C'\fR and the initializer did not have two decimal places or a leading \&'v' (both optional), then the stringified form will have a leading 'v' prepended, in order to support round-trip processing. .Sp For example: .Sp .Vb 7 \& Initialized as Stringifies to \& ============== ============== \& version\->new("1.2") 1.2 \& version\->new("v1.2") v1.2 \& qv("1.2.3") 1.2.3 \& qv("v1.3.5") v1.3.5 \& qv("1.2") v1.2 ### exceptional case .Ve .Sp See also \s-1UNIVERSAL::VERSION\s0, as this also returns the stringified form when used as a class method. .Sp \&\s-1IMPORTANT NOTE:\s0 There is one exceptional cases shown in the above table where the \*(L"initializer\*(R" is not stringwise equivalent to the stringified representation. If you use the \f(CW\*(C`qv\*(C'\fR() operator on a version without a leading 'v' \fBand\fR with only a single decimal place, the stringified output will have a leading 'v', to preserve the sense. See the \*(L"\fBqv()\fR\*(R" operator for more details. .Sp \&\s-1IMPORTANT NOTE 2:\s0 Attempting to bypass the normal stringification rules by manually applying \fBnumify()\fR and \fBnormal()\fR will sometimes yield surprising results: .Sp .Vb 1 \& print version\->new(version\->new("v1.0")\->numify)\->normal; # v1.0.0 .Ve .Sp The reason for this is that the \fBnumify()\fR operator will turn \*(L"v1.0\*(R" into the equivalent string \*(L"1.000000\*(R". Forcing the outer version object to \fBnormal()\fR form will display the mathematically equivalent \*(L"v1.0.0\*(R". .Sp As the example in \*(L"\fBnew()\fR\*(R" shows, you can always create a copy of an existing version object with the same value by the very compact: .Sp .Vb 1 \& $v2 = $v1\->new($v1); .Ve .Sp and be assured that both \f(CW$v1\fR and \f(CW$v2\fR will be completely equivalent, down to the same internal representation as well as stringification. .IP "Comparison operators" 4 .IX Item "Comparison operators" Both \f(CW\*(C`cmp\*(C'\fR and \f(CW\*(C`<=>\*(C'\fR operators perform the same comparison between terms (upgrading to a version object automatically). Perl automatically generates all of the other comparison operators based on those two. In addition to the obvious equalities listed below, appending a single trailing 0 term does not change the value of a version for comparison purposes. In other words \*(L"v1.2\*(R" and \*(L"1.2.0\*(R" will compare as identical. .Sp For example, the following relations hold: .Sp .Vb 7 \& As Number As String Truth Value \& \-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\- \& $ver > 1.0 $ver gt "1.0" true \& $ver < 2.5 $ver lt true \& $ver != 1.3 $ver ne "1.3" true \& $ver == 1.2 $ver eq "1.2" false \& $ver == 1.2.3.4 $ver eq "1.2.3.4" see discussion below .Ve .Sp It is probably best to chose either the Decimal notation or the string notation and stick with it, to reduce confusion. Perl6 version objects \&\fBmay\fR only support Decimal comparisons. See also \*(L"Quoting Rules\*(R". .Sp \&\s-1WARNING:\s0 Comparing version with unequal numbers of decimal points (whether explicitly or implicitly initialized), may yield unexpected results at first glance. For example, the following inequalities hold: .Sp .Vb 2 \& version\->new(0.96) > version\->new(0.95); # 0.960.0 > 0.950.0 \& version\->new("0.96.1") < version\->new(0.95); # 0.096.1 < 0.950.0 .Ve .Sp For this reason, it is best to use either exclusively \*(L"Decimal Versions\*(R" or \&\*(L"Dotted-Decimal Versions\*(R" with multiple decimal points. .IP "Logical Operators" 4 .IX Item "Logical Operators" If you need to test whether a version object has been initialized, you can simply test it directly: .Sp .Vb 2 \& $vobj = version\->new($something); \& if ( $vobj ) # true only if $something was non\-blank .Ve .Sp You can also test whether a version object is an alpha version, for example to prevent the use of some feature not present in the main release: .Sp .Vb 3 \& $vobj = version\->new("1.2_3"); # MUST QUOTE \& ...later... \& if ( $vobj\->is_alpha ) # True .Ve .SH "AUTHOR" .IX Header "AUTHOR" John Peacock .SH "SEE ALSO" .IX Header "SEE ALSO" perl. PK!Wman/man3/JSON::Syck.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "JSON::Syck 3" .TH JSON::Syck 3 "2020-10-26" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" JSON::Syck \- JSON is YAML (but consider using JSON::XS instead!) .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use JSON::Syck; # no exports by default \& \& my $data = JSON::Syck::Load($json); \& my $json = JSON::Syck::Dump($data); \& \& # $file can be an IO object, or a filename \& my $data = JSON::Syck::LoadFile($file); \& JSON::Syck::DumpFile($file, $data); \& \& # Dump into a pre\-existing buffer \& my $json; \& JSON::Syck::DumpInto(\e$json, $data); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" JSON::Syck is a syck implementation of \s-1JSON\s0 parsing and generation. Because \&\s-1JSON\s0 is \s-1YAML\s0 (), using syck gives you a fast and memory-efficient parser and dumper for \s-1JSON\s0 data representation. .PP However, a newer module \s-1JSON::XS\s0, has since emerged. It is more flexible, efficient and robust, so please consider using it instead of this module. .SH "DIFFERENCE WITH JSON" .IX Header "DIFFERENCE WITH JSON" You might want to know the difference between the \fI\s-1JSON\s0\fR module and this one. .PP Since \s-1JSON\s0 is a pure-perl module and JSON::Syck is based on libsyck, JSON::Syck is supposed to be very fast and memory efficient. See chansen's benchmark table at .PP \&\s-1JSON\s0.pm comes with dozens of ways to do the same thing and lots of options, while JSON::Syck doesn't. There's only \f(CW\*(C`Load\*(C'\fR and \f(CW\*(C`Dump\*(C'\fR. .PP Oh, and JSON::Syck doesn't use camelCase method names :\-) .SH "REFERENCES" .IX Header "REFERENCES" .SS "\s-1SCALAR REFERENCE\s0" .IX Subsection "SCALAR REFERENCE" For now, when you pass a scalar reference to JSON::Syck, it dereferences to get the actual scalar value. .PP JSON::Syck raises an exception when you pass in circular references. .PP If you want to serialize self referencing stuff, you should use \&\s-1YAML\s0 which supports it. .SS "\s-1SUBROUTINE REFERENCE\s0" .IX Subsection "SUBROUTINE REFERENCE" When you pass subroutine reference, JSON::Syck dumps it as null. .SH "UTF\-8 FLAGS" .IX Header "UTF-8 FLAGS" By default this module doesn't touch any of utf\-8 flags set in strings, and assumes \s-1UTF\-8\s0 bytes to be passed and emit. .PP However, when you set \f(CW$JSON::Syck::ImplicitUnicode\fR to 1, this module properly decodes \s-1UTF\-8\s0 binaries and sets \s-1UTF\-8\s0 flag everywhere, as in: .PP .Vb 4 \& JSON (UTF\-8 bytes) => Perl (UTF\-8 flagged) \& JSON (UTF\-8 flagged) => Perl (UTF\-8 flagged) \& Perl (UTF\-8 bytes) => JSON (UTF\-8 flagged) \& Perl (UTF\-8 flagged) => JSON (UTF\-8 flagged) .Ve .PP By default, JSON::Syck::Dump will only transverse up to 512 levels of a datastructure in order to avoid an infinite loop when it is presented with an circular reference. .PP However, you set \f(CW$JSON::Syck::MaxLevels\fR to a larger value if you have very complex structures. .PP Unfortunately, there's no implicit way to dump Perl \s-1UTF\-8\s0 flagged data structure to utf\-8 encoded \s-1JSON.\s0 To do this, simply use Encode module, e.g.: .PP .Vb 2 \& use Encode; \& use JSON::Syck qw(Dump); \& \& my $json = encode_utf8( Dump($data) ); .Ve .PP Alternatively you can use Encode::JavaScript::UCS to encode Unicode strings as in \fI\f(CI%uXXXX\fI\fR form. .PP .Vb 3 \& use Encode; \& use Encode::JavaScript::UCS; \& use JSON::Syck qw(Dump); \& \& my $json_unicode_escaped = encode( \*(AqJavaScript\-UCS\*(Aq, Dump($data) ); .Ve .SH "QUOTING" .IX Header "QUOTING" According to the \s-1JSON\s0 specification, all \s-1JSON\s0 strings are to be double-quoted. However, when embedding JavaScript in \s-1HTML\s0 attributes, it may be more convenient to use single quotes. .PP Set \f(CW$JSON::Syck::SingleQuote\fR to 1 will make both \f(CW\*(C`Dump\*(C'\fR and \f(CW\*(C`Load\*(C'\fR expect single-quoted string literals. .SH "BUGS" .IX Header "BUGS" Dumping into tied (or other magic variables) with \f(CW\*(C`DumpInto\*(C'\fR might not work properly in all cases. .PP When dumping with \f(CW\*(C`DumpFile\*(C'\fR, some spacing might be wrong and \&\f(CW$JSON::Syck::SingleQuote\fR might be handled incorrectly. .SH "SEE ALSO" .IX Header "SEE ALSO" \&\s-1JSON::XS\s0, YAML::Syck .SH "AUTHORS" .IX Header "AUTHORS" Audrey Tang .PP Tatsuhiko Miyagawa .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright 2005\-2009 by Audrey Tang . .PP This software is released under the \s-1MIT\s0 license cited below. .PP The \fIlibsyck\fR code bundled with this library is released by \&\*(L"why the lucky stiff\*(R", under a BSD-style license. See the \fI\s-1COPYING\s0\fR file for details. .ie n .SS "The ""\s-1MIT""\s0 License" .el .SS "The ``\s-1MIT''\s0 License" .IX Subsection "The MIT License" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \*(L"Software\*(R"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: .PP The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. .PP \&\s-1THE SOFTWARE IS PROVIDED \*(L"AS IS\*(R", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\s0 PK!I*I*man/man3/YAML::Syck.3pmnu6$.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "YAML::Syck 3" .TH YAML::Syck 3 "2020-10-26" "perl v5.26.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" YAML::Syck \- Fast, lightweight YAML loader and dumper .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use YAML::Syck; \& \& # Set this for interoperability with other YAML/Syck bindings: \& # e.g. Load(\*(AqYes\*(Aq) becomes 1 and Load(\*(AqNo\*(Aq) becomes \*(Aq\*(Aq. \& $YAML::Syck::ImplicitTyping = 1; \& \& $data = Load($yaml); \& $yaml = Dump($data); \& \& # $file can be an IO object, or a filename \& $data = LoadFile($file); \& DumpFile($file, $data); \& \& # A string with multiple YAML streams in it \& $yaml = Dump(@data); \& @data = Load($yaml); \& \& # Dumping into a pre\-existing output buffer \& my $yaml; \& DumpInto(\e$yaml, @data); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module provides a Perl interface to the \fBlibsyck\fR data serialization library. It exports the \f(CW\*(C`Dump\*(C'\fR and \f(CW\*(C`Load\*(C'\fR functions for converting Perl data structures to \s-1YAML\s0 strings, and the other way around. .PP \&\fB\s-1NOTE\s0\fR: If you are working with other language's YAML/Syck bindings (such as Ruby), please set \f(CW$YAML::Syck::ImplicitTyping\fR to \f(CW1\fR before calling the \f(CW\*(C`Load\*(C'\fR/\f(CW\*(C`Dump\*(C'\fR functions. The default setting is for preserving backward-compatibility with \f(CW\*(C`YAML.pm\*(C'\fR. .SH "Differences Between YAML::Syck and YAML" .IX Header "Differences Between YAML::Syck and YAML" .SS "Error handling" .IX Subsection "Error handling" Some calls are designed to die rather than returning \s-1YAML.\s0 You should wrap your calls in eval to assure you do not get unexpected results. .SH "FLAGS" .IX Header "FLAGS" .ie n .SS "$YAML::Syck::Headless" .el .SS "\f(CW$YAML::Syck::Headless\fP" .IX Subsection "$YAML::Syck::Headless" Defaults to false. Setting this to a true value will make \f(CW\*(C`Dump\*(C'\fR omit the leading \f(CW\*(C`\-\-\-\en\*(C'\fR marker. .ie n .SS "$YAML::Syck::SortKeys" .el .SS "\f(CW$YAML::Syck::SortKeys\fP" .IX Subsection "$YAML::Syck::SortKeys" Defaults to false. Setting this to a true value will make \f(CW\*(C`Dump\*(C'\fR sort hash keys. .ie n .SS "$YAML::Syck::SingleQuote" .el .SS "\f(CW$YAML::Syck::SingleQuote\fP" .IX Subsection "$YAML::Syck::SingleQuote" Defaults to false. Setting this to a true value will make \f(CW\*(C`Dump\*(C'\fR always emit single quotes instead of bare strings. .ie n .SS "$YAML::Syck::ImplicitTyping" .el .SS "\f(CW$YAML::Syck::ImplicitTyping\fP" .IX Subsection "$YAML::Syck::ImplicitTyping" Defaults to false. Setting this to a true value will make \f(CW\*(C`Load\*(C'\fR recognize various implicit types in \s-1YAML,\s0 such as unquoted \f(CW\*(C`true\*(C'\fR, \f(CW\*(C`false\*(C'\fR, as well as integers and floating-point numbers. Otherwise, only \f(CW\*(C`~\*(C'\fR is recognized to be \f(CW\*(C`undef\*(C'\fR. .ie n .SS "$YAML::Syck::ImplicitUnicode" .el .SS "\f(CW$YAML::Syck::ImplicitUnicode\fP" .IX Subsection "$YAML::Syck::ImplicitUnicode" Defaults to false. For Perl 5.8.0 or later, setting this to a true value will make \f(CW\*(C`Load\*(C'\fR set Unicode flag on for every string that contains valid \s-1UTF8\s0 sequences, and make \f(CW\*(C`Dump\*(C'\fR return a unicode string. .PP Regardless of this flag, Unicode strings are dumped verbatim without escaping; byte strings with high-bit set will be dumped with backslash escaping. .PP However, because \s-1YAML\s0 does not distinguish between these two kinds of strings, so this flag will affect loading of both variants of strings. .PP If you want to use LoadFile or DumpFile with unicode, you are required to open your own file in order to assure it's \s-1UTF8\s0 encoded: .PP .Vb 2 \& open(my $fh, ">:encoding(UTF\-8)", "out.yml"); \& DumpFile($fh, $hashref); .Ve .ie n .SS "$YAML::Syck::ImplicitBinary" .el .SS "\f(CW$YAML::Syck::ImplicitBinary\fP" .IX Subsection "$YAML::Syck::ImplicitBinary" Defaults to false. For Perl 5.8.0 or later, setting this to a true value will make \f(CW\*(C`Dump\*(C'\fR generate Base64\-encoded \f(CW\*(C`!!binary\*(C'\fR data for all non-Unicode scalars containing high-bit bytes. .ie n .SS "$YAML::Syck::UseCode / $YAML::Syck::LoadCode / $YAML::Syck::DumpCode" .el .SS "\f(CW$YAML::Syck::UseCode\fP / \f(CW$YAML::Syck::LoadCode\fP / \f(CW$YAML::Syck::DumpCode\fP" .IX Subsection "$YAML::Syck::UseCode / $YAML::Syck::LoadCode / $YAML::Syck::DumpCode" These flags control whether or not to try and eval/deparse perl source code; each of them defaults to false. .PP Setting \f(CW$YAML::Syck::UseCode\fR to a true value is equivalent to setting both \f(CW$YAML::Syck::LoadCode\fR and \f(CW$YAML::Syck::DumpCode\fR to true. .ie n .SS "$YAML::Syck::LoadBlessed" .el .SS "\f(CW$YAML::Syck::LoadBlessed\fP" .IX Subsection "$YAML::Syck::LoadBlessed" Defaults to false. Setting to true will allow YAML::Syck to bless objects as it imports objects. This default changed in 1.32. .PP You can create any kind of object with \s-1YAML.\s0 The creation itself is not the critical part. If the class has a \s-1DESTROY\s0 method, it will be called once the object is deleted. An example with File::Temp removing files can be found at .SH "BUGS" .IX Header "BUGS" Dumping Glob/IO values do not work yet. .PP Dumping of Tied variables is unsupported. .PP Dumping into tied (or other magic variables) with \f(CW\*(C`DumpInto\*(C'\fR might not work properly in all cases. .SH "CAVEATS" .IX Header "CAVEATS" This module implements the \s-1YAML 1.0\s0 spec. To deal with data in \s-1YAML 1.1,\s0 please use the \f(CW\*(C`YAML::XS\*(C'\fR module instead. .PP The current implementation bundles libsyck source code; if your system has a site-wide shared libsyck, it will \fInot\fR be used. .PP Tag names such as \f(CW\*(C`!!perl/hash:Foo\*(C'\fR is blessed into the package \f(CW\*(C`Foo\*(C'\fR, but the \f(CW\*(C`!hs/foo\*(C'\fR and \f(CW\*(C`!!hs/Foo\*(C'\fR tags are blessed into \f(CW\*(C`hs::Foo\*(C'\fR. Note that this holds true even if the tag contains non-word characters; for example, \&\f(CW\*(C`!haskell.org/Foo\*(C'\fR is blessed into \f(CW\*(C`haskell.org::Foo\*(C'\fR. Please use Class::Rebless to cast it into other user-defined packages. You can also set the LoadBlessed flag false to disable all blessing. .PP This module has a lot of known issues and has only been semi-actively maintained since 2007. If you encounter an issue with it probably won't be fixed unless you offer up a patch in Git that's ready for release. .PP There are still good reasons to use this module, such as better interoperability with other syck wrappers (like Ruby's), or some edge case of \s-1YAML\s0's syntax that it handles better. It'll probably work perfectly for you, but if it doesn't you may want to look at \&\s-1YAML::XS\s0, or perhaps at looking another serialization format like \&\s-1JSON\s0. .SH "SEE ALSO" .IX Header "SEE ALSO" \&\s-1YAML\s0, JSON::Syck .PP .SH "AUTHORS" .IX Header "AUTHORS" Audrey Tang .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright 2005\-2009 by Audrey Tang . .PP This software is released under the \s-1MIT\s0 license cited below. .PP The \fIlibsyck\fR code bundled with this library is released by \&\*(L"why the lucky stiff\*(R", under a BSD-style license. See the \fI\s-1COPYING\s0\fR file for details. .ie n .SS "The ""\s-1MIT""\s0 License" .el .SS "The ``\s-1MIT''\s0 License" .IX Subsection "The MIT License" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \*(L"Software\*(R"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: .PP The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. .PP \&\s-1THE SOFTWARE IS PROVIDED \*(L"AS IS\*(R", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\s0 PK!qperl5/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 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!Qperl5/App/Cpan.pmnu6$package App::Cpan; use strict; use warnings; use vars qw($VERSION); use if $] < 5.008 => 'IO::Scalar'; $VERSION = '1.678'; =head1 NAME App::Cpan - easily interact with CPAN from the command line =head1 SYNOPSIS # with arguments and no switches, installs specified modules cpan module_name [ module_name ... ] # with switches, installs modules with extra behavior cpan [-cfFimtTw] module_name [ module_name ... ] # use local::lib cpan -I module_name [ module_name ... ] # one time mirror override for faster mirrors cpan -p ... # with just the dot, install from the distribution in the # current directory cpan . # without arguments, starts CPAN.pm shell cpan # without arguments, but some switches cpan [-ahpruvACDLOPX] =head1 DESCRIPTION This script provides a command interface (not a shell) to CPAN. At the moment it uses CPAN.pm to do the work, but it is not a one-shot command runner for CPAN.pm. =head2 Options =over 4 =item -a Creates a CPAN.pm autobundle with CPAN::Shell->autobundle. =item -A module [ module ... ] Shows the primary maintainers for the specified modules. =item -c module Runs a `make clean` in the specified module's directories. =item -C module [ module ... ] Show the F files for the specified modules =item -D module [ module ... ] Show the module details. This prints one line for each out-of-date module (meaning, modules locally installed but have newer versions on CPAN). Each line has three columns: module name, local version, and CPAN version. =item -f Force the specified action, when it normally would have failed. Use this to install a module even if its tests fail. When you use this option, -i is not optional for installing a module when you need to force it: % cpan -f -i Module::Foo =item -F Turn off CPAN.pm's attempts to lock anything. You should be careful with this since you might end up with multiple scripts trying to muck in the same directory. This isn't so much of a concern if you're loading a special config with C<-j>, and that config sets up its own work directories. =item -g module [ module ... ] Downloads to the current directory the latest distribution of the module. =item -G module [ module ... ] UNIMPLEMENTED Download to the current directory the latest distribution of the modules, unpack each distribution, and create a git repository for each distribution. If you want this feature, check out Yanick Champoux's C distribution. =item -h Print a help message and exit. When you specify C<-h>, it ignores all of the other options and arguments. =item -i module [ module ... ] Install the specified modules. With no other switches, this switch is implied. =item -I Load C (think like C<-I> for loading lib paths). Too bad C<-l> was already taken. =item -j Config.pm Load the file that has the CPAN configuration data. This should have the same format as the standard F file, which defines C<$CPAN::Config> as an anonymous hash. If the file does not exist, C dies. =item -J Dump the configuration in the same format that CPAN.pm uses. This is useful for checking the configuration as well as using the dump as a starting point for a new, custom configuration. =item -l List all installed modules with their versions =item -L author [ author ... ] List the modules by the specified authors. =item -m Make the specified modules. =item -M mirror1,mirror2,... A comma-separated list of mirrors to use for just this run. The C<-P> option can find them for you automatically. =item -n Do a dry run, but don't actually install anything. (unimplemented) =item -O Show the out-of-date modules. =item -p Ping the configured mirrors and print a report =item -P Find the best mirrors you could be using and use them for the current session. =item -r Recompiles dynamically loaded modules with CPAN::Shell->recompile. =item -s Drop in the CPAN.pm shell. This command does this automatically if you don't specify any arguments. =item -t module [ module ... ] Run a `make test` on the specified modules. =item -T Do not test modules. Simply install them. =item -u Upgrade all installed modules. Blindly doing this can really break things, so keep a backup. =item -v Print the script version and CPAN.pm version then exit. =item -V Print detailed information about the cpan client. =item -w UNIMPLEMENTED Turn on cpan warnings. This checks various things, like directory permissions, and tells you about problems you might have. =item -x module [ module ... ] Find close matches to the named modules that you think you might have mistyped. This requires the optional installation of Text::Levenshtein or Text::Levenshtein::Damerau. =item -X Dump all the namespaces to standard output. =back =head2 Examples # print a help message cpan -h # print the version numbers cpan -v # create an autobundle cpan -a # recompile modules cpan -r # upgrade all installed modules cpan -u # install modules ( sole -i is optional ) cpan -i Netscape::Booksmarks Business::ISBN # force install modules ( must use -i ) cpan -fi CGI::Minimal URI # install modules but without testing them cpan -Ti CGI::Minimal URI =head2 Environment variables There are several components in CPAN.pm that use environment variables. The build tools, L and L use some, while others matter to the levels above them. Some of these are specified by the Perl Toolchain Gang: Lancaster Consensus: L Oslo Consensus: L =over 4 =item NONINTERACTIVE_TESTING Assume no one is paying attention and skips prompts for distributions that do that correctly. C sets this to C<1> unless it already has a value (even if that value is false). =item PERL_MM_USE_DEFAULT Use the default answer for a prompted questions. C sets this to C<1> unless it already has a value (even if that value is false). =item CPAN_OPTS As with C, a string of additional C options to add to those you specify on the command line. =item CPANSCRIPT_LOGLEVEL The log level to use, with either the embedded, minimal logger or L if it is installed. Possible values are the same as the C levels: C, C, C, C, C, and C. The default is C. =item GIT_COMMAND The path to the C binary to use for the Git features. The default is C. =back =head2 Methods =over 4 =cut use autouse Carp => qw(carp croak cluck); use CPAN 1.80 (); # needs no test use Config; use autouse Cwd => qw(cwd); use autouse 'Data::Dumper' => qw(Dumper); use File::Spec::Functions qw(catfile file_name_is_absolute rel2abs); use File::Basename; use Getopt::Std; # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Internal constants use constant TRUE => 1; use constant FALSE => 0; # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # The return values use constant HEY_IT_WORKED => 0; use constant I_DONT_KNOW_WHAT_HAPPENED => 1; # 0b0000_0001 use constant ITS_NOT_MY_FAULT => 2; use constant THE_PROGRAMMERS_AN_IDIOT => 4; use constant A_MODULE_FAILED_TO_INSTALL => 8; # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # set up the order of options that we layer over CPAN::Shell BEGIN { # most of this should be in methods use vars qw( @META_OPTIONS $Default %CPAN_METHODS @CPAN_OPTIONS @option_order %Method_table %Method_table_index ); @META_OPTIONS = qw( h v V I g G M: C A D O l L a r p P j: J w x X ); $Default = 'default'; %CPAN_METHODS = ( # map switches to method names in CPAN::Shell $Default => 'install', 'c' => 'clean', 'f' => 'force', 'i' => 'install', 'm' => 'make', 't' => 'test', 'u' => 'upgrade', 'T' => 'notest', 's' => 'shell', ); @CPAN_OPTIONS = grep { $_ ne $Default } sort keys %CPAN_METHODS; @option_order = ( @META_OPTIONS, @CPAN_OPTIONS ); # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # map switches to the subroutines in this script, along with other information. # use this stuff instead of hard-coded indices and values sub NO_ARGS () { 0 } sub ARGS () { 1 } sub GOOD_EXIT () { 0 } %Method_table = ( # key => [ sub ref, takes args?, exit value, description ] # options that do their thing first, then exit h => [ \&_print_help, NO_ARGS, GOOD_EXIT, 'Printing help' ], v => [ \&_print_version, NO_ARGS, GOOD_EXIT, 'Printing version' ], V => [ \&_print_details, NO_ARGS, GOOD_EXIT, 'Printing detailed version' ], X => [ \&_list_all_namespaces, NO_ARGS, GOOD_EXIT, 'Listing all namespaces' ], # options that affect other options j => [ \&_load_config, ARGS, GOOD_EXIT, 'Use specified config file' ], J => [ \&_dump_config, NO_ARGS, GOOD_EXIT, 'Dump configuration to stdout' ], F => [ \&_lock_lobotomy, NO_ARGS, GOOD_EXIT, 'Turn off CPAN.pm lock files' ], I => [ \&_load_local_lib, NO_ARGS, GOOD_EXIT, 'Loading local::lib' ], M => [ \&_use_these_mirrors, ARGS, GOOD_EXIT, 'Setting per session mirrors' ], P => [ \&_find_good_mirrors, NO_ARGS, GOOD_EXIT, 'Finding good mirrors' ], w => [ \&_turn_on_warnings, NO_ARGS, GOOD_EXIT, 'Turning on warnings' ], # options that do their one thing g => [ \&_download, ARGS, GOOD_EXIT, 'Download the latest distro' ], G => [ \&_gitify, ARGS, GOOD_EXIT, 'Down and gitify the latest distro' ], C => [ \&_show_Changes, ARGS, GOOD_EXIT, 'Showing Changes file' ], A => [ \&_show_Author, ARGS, GOOD_EXIT, 'Showing Author' ], D => [ \&_show_Details, ARGS, GOOD_EXIT, 'Showing Details' ], O => [ \&_show_out_of_date, NO_ARGS, GOOD_EXIT, 'Showing Out of date' ], l => [ \&_list_all_mods, NO_ARGS, GOOD_EXIT, 'Listing all modules' ], L => [ \&_show_author_mods, ARGS, GOOD_EXIT, 'Showing author mods' ], a => [ \&_create_autobundle, NO_ARGS, GOOD_EXIT, 'Creating autobundle' ], p => [ \&_ping_mirrors, NO_ARGS, GOOD_EXIT, 'Pinging mirrors' ], r => [ \&_recompile, NO_ARGS, GOOD_EXIT, 'Recompiling' ], u => [ \&_upgrade, NO_ARGS, GOOD_EXIT, 'Running `make test`' ], 's' => [ \&_shell, NO_ARGS, GOOD_EXIT, 'Drop into the CPAN.pm shell' ], 'x' => [ \&_guess_namespace, ARGS, GOOD_EXIT, 'Guessing namespaces' ], c => [ \&_default, ARGS, GOOD_EXIT, 'Running `make clean`' ], f => [ \&_default, ARGS, GOOD_EXIT, 'Installing with force' ], i => [ \&_default, ARGS, GOOD_EXIT, 'Running `make install`' ], 'm' => [ \&_default, ARGS, GOOD_EXIT, 'Running `make`' ], t => [ \&_default, ARGS, GOOD_EXIT, 'Running `make test`' ], T => [ \&_default, ARGS, GOOD_EXIT, 'Installing with notest' ], ); %Method_table_index = ( code => 0, takes_args => 1, exit_value => 2, description => 3, ); } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # finally, do some argument processing sub _stupid_interface_hack_for_non_rtfmers { no warnings 'uninitialized'; shift @ARGV if( $ARGV[0] eq 'install' and @ARGV > 1 ) } sub _process_options { my %options; push @ARGV, grep $_, split /\s+/, $ENV{CPAN_OPTS} || ''; # if no arguments, just drop into the shell if( 0 == @ARGV ) { CPAN::shell(); exit 0 } elsif (Getopt::Std::getopts( join( '', @option_order ), \%options )) { \%options; } else { exit 1 } } sub _process_setup_options { my( $class, $options ) = @_; if( $options->{j} ) { $Method_table{j}[ $Method_table_index{code} ]->( $options->{j} ); delete $options->{j}; } elsif ( ! $options->{h} ) { # h "ignores all of the other options and arguments" # this is what CPAN.pm would do otherwise local $CPAN::Be_Silent = 1; CPAN::HandleConfig->load( # be_silent => 1, deprecated write_file => 0, ); } $class->_turn_off_testing if $options->{T}; foreach my $o ( qw(F I w P M) ) { next unless exists $options->{$o}; $Method_table{$o}[ $Method_table_index{code} ]->( $options->{$o} ); delete $options->{$o}; } if( $options->{o} ) { my @pairs = map { [ split /=/, $_, 2 ] } split /,/, $options->{o}; foreach my $pair ( @pairs ) { my( $setting, $value ) = @$pair; $CPAN::Config->{$setting} = $value; # $logger->debug( "Setting [$setting] to [$value]" ); } delete $options->{o}; } my $option_count = grep { $options->{$_} } @option_order; no warnings 'uninitialized'; # don't count options that imply installation foreach my $opt ( qw(f T) ) { # don't count force or notest $option_count -= $options->{$opt}; } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if there are no options, set -i (this line fixes RT ticket 16915) $options->{i}++ unless $option_count; } sub _setup_environment { # should we override or set defaults? If this were a true interactive # session, we'd be in the CPAN shell. # https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/lancaster-consensus.md $ENV{NONINTERACTIVE_TESTING} = 1 unless defined $ENV{NONINTERACTIVE_TESTING}; $ENV{PERL_MM_USE_DEFAULT} = 1 unless defined $ENV{PERL_MM_USE_DEFAULT}; } =item run( ARGS ) Just do it. The C method returns 0 on success and a positive number on failure. See the section on EXIT CODES for details on the values. =cut my $logger; sub run { my( $class, @args ) = @_; local @ARGV = @args; my $return_value = HEY_IT_WORKED; # assume that things will work $logger = $class->_init_logger; $logger->debug( "Using logger from @{[ref $logger]}" ); $class->_hook_into_CPANpm_report; $logger->debug( "Hooked into output" ); $class->_stupid_interface_hack_for_non_rtfmers; $logger->debug( "Patched cargo culting" ); my $options = $class->_process_options; $logger->debug( "Options are @{[Dumper($options)]}" ); $class->_process_setup_options( $options ); $class->_setup_environment( $options ); OPTION: foreach my $option ( @option_order ) { next unless $options->{$option}; my( $sub, $takes_args, $description ) = map { $Method_table{$option}[ $Method_table_index{$_} ] } qw( code takes_args description ); unless( ref $sub eq ref sub {} ) { $return_value = THE_PROGRAMMERS_AN_IDIOT; last OPTION; } $logger->info( "[$option] $description -- ignoring other arguments" ) if( @ARGV && ! $takes_args ); $return_value = $sub->( \ @ARGV, $options ); last; } return $return_value; } my $LEVEL; { package Local::Null::Logger; # hide from PAUSE my @LOGLEVELS = qw(TRACE DEBUG INFO WARN ERROR FATAL); $LEVEL = uc($ENV{CPANSCRIPT_LOGLEVEL} || 'INFO'); my %LL = map { $LOGLEVELS[$_] => $_ } 0..$#LOGLEVELS; unless (defined $LL{$LEVEL}){ warn "Unsupported loglevel '$LEVEL', setting to INFO"; $LEVEL = 'INFO'; } sub new { bless \ my $x, $_[0] } sub AUTOLOAD { my $autoload = our $AUTOLOAD; $autoload =~ s/.*://; return if $LL{uc $autoload} < $LL{$LEVEL}; $CPAN::Frontend->mywarn(">($autoload): $_\n") for split /[\r\n]+/, $_[1]; } sub DESTROY { 1 } } # load a module without searching the default entry for the current # directory sub _safe_load_module { my $name = shift; local @INC = @INC; pop @INC if $INC[-1] eq '.'; eval "require $name; 1"; } sub _init_logger { my $log4perl_loaded = _safe_load_module("Log::Log4perl"); unless( $log4perl_loaded ) { print STDOUT "Loading internal logger. Log::Log4perl recommended for better logging\n"; $logger = Local::Null::Logger->new; return $logger; } Log::Log4perl::init( \ <<"HERE" ); log4perl.rootLogger=$LEVEL, A1 log4perl.appender.A1=Log::Log4perl::Appender::Screen log4perl.appender.A1.layout=PatternLayout log4perl.appender.A1.layout.ConversionPattern=%m%n HERE $logger = Log::Log4perl->get_logger( 'App::Cpan' ); } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # sub _default { my( $args, $options ) = @_; my $switch = ''; # choose the option that we're going to use # we'll deal with 'f' (force) later, so skip it foreach my $option ( @CPAN_OPTIONS ) { next if ( $option eq 'f' or $option eq 'T' ); next unless $options->{$option}; $switch = $option; last; } # 1. with no switches, but arguments, use the default switch (install) # 2. with no switches and no args, start the shell # 3. With a switch but no args, die! These switches need arguments. if( not $switch and @$args ) { $switch = $Default; } elsif( not $switch and not @$args ) { return CPAN::shell() } elsif( $switch and not @$args ) { die "Nothing to $CPAN_METHODS{$switch}!\n"; } # Get and check the method from CPAN::Shell my $method = $CPAN_METHODS{$switch}; die "CPAN.pm cannot $method!\n" unless CPAN::Shell->can( $method ); # call the CPAN::Shell method, with force or notest if specified my $action = do { if( $options->{f} ) { sub { CPAN::Shell->force( $method, @_ ) } } elsif( $options->{T} ) { sub { CPAN::Shell->notest( $method, @_ ) } } else { sub { CPAN::Shell->$method( @_ ) } } }; # How do I handle exit codes for multiple arguments? my @errors = (); $options->{x} or _disable_guessers(); foreach my $arg ( @$args ) { # check the argument and perhaps capture typos my $module = _expand_module( $arg ) or do { $logger->error( "Skipping $arg because I couldn't find a matching namespace." ); next; }; _clear_cpanpm_output(); $action->( $arg ); my $error = _cpanpm_output_indicates_failure(); push @errors, $error if $error; } return do { if( @errors ) { $errors[0] } else { HEY_IT_WORKED } }; } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # =for comment CPAN.pm sends all the good stuff either to STDOUT, or to a temp file if $CPAN::Be_Silent is set. I have to intercept that output so I can find out what happened. =cut BEGIN { my $scalar = ''; sub _hook_into_CPANpm_report { no warnings 'redefine'; *CPAN::Shell::myprint = sub { my($self,$what) = @_; $scalar .= $what if defined $what; $self->print_ornamented($what, $CPAN::Config->{colorize_print}||'bold blue on_white', ); }; *CPAN::Shell::mywarn = sub { my($self,$what) = @_; $scalar .= $what if defined $what; $self->print_ornamented($what, $CPAN::Config->{colorize_warn}||'bold red on_white' ); }; } sub _clear_cpanpm_output { $scalar = '' } sub _get_cpanpm_output { $scalar } # These are lines I don't care about in CPAN.pm output. If I can # filter out the informational noise, I have a better chance to # catch the error signal my @skip_lines = ( qr/^\QWarning \(usually harmless\)/, qr/\bwill not store persistent state\b/, qr(//hint//), qr/^\s+reports\s+/, qr/^Try the command/, qr/^\s+$/, qr/^to find objects/, qr/^\s*Database was generated on/, qr/^Going to read/, qr|^\s+i\s+/|, # the i /Foo::Whatever/ line when it doesn't know ); sub _get_cpanpm_last_line { my $fh; if( $] < 5.008 ) { $fh = IO::Scalar->new( \ $scalar ); } else { eval q{ open $fh, '<', \\ $scalar; }; } my @lines = <$fh>; # This is a bit ugly. Once we examine a line, we have to # examine the line before it and go through all of the same # regexes. I could do something fancy, but this works. REGEXES: { foreach my $regex ( @skip_lines ) { if( $lines[-1] =~ m/$regex/ ) { pop @lines; redo REGEXES; # we have to go through all of them for every line! } } } $logger->debug( "Last interesting line of CPAN.pm output is:\n\t$lines[-1]" ); $lines[-1]; } } BEGIN { my $epic_fail_words = join '|', qw( Error stop(?:ping)? problems force not unsupported fail(?:ed)? Cannot\s+install ); sub _cpanpm_output_indicates_failure { my $last_line = _get_cpanpm_last_line(); my $result = $last_line =~ /\b(?:$epic_fail_words)\b/i; return A_MODULE_FAILED_TO_INSTALL if $last_line =~ /\b(?:Cannot\s+install)\b/i; $result || (); } } sub _cpanpm_output_indicates_success { my $last_line = _get_cpanpm_last_line(); my $result = $last_line =~ /\b(?:\s+-- OK|PASS)\b/; $result || (); } sub _cpanpm_output_is_vague { return FALSE if _cpanpm_output_indicates_failure() || _cpanpm_output_indicates_success(); return TRUE; } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # sub _turn_on_warnings { carp "Warnings are implemented yet"; return HEY_IT_WORKED; } sub _turn_off_testing { $logger->debug( 'Trusting test report history' ); $CPAN::Config->{trust_test_report_history} = 1; return HEY_IT_WORKED; } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # sub _print_help { $logger->info( "Use perldoc to read the documentation" ); my $HAVE_PERLDOC = eval { require Pod::Perldoc; 1; }; if ($HAVE_PERLDOC) { system qq{"$^X" -e "require Pod::Perldoc; Pod::Perldoc->run()" $0}; exit; } else { warn "Please install Pod::Perldoc, maybe try 'cpan -i Pod::Perldoc'\n"; return HEY_IT_WORKED; } } sub _print_version # -v { $logger->info( "$0 script version $VERSION, CPAN.pm version " . CPAN->VERSION ); return HEY_IT_WORKED; } sub _print_details # -V { _print_version(); _check_install_dirs(); $logger->info( '-' x 50 . "\nChecking configured mirrors..." ); foreach my $mirror ( @{ $CPAN::Config->{urllist} } ) { _print_ping_report( $mirror ); } $logger->info( '-' x 50 . "\nChecking for faster mirrors..." ); { require CPAN::Mirrors; if ( $CPAN::Config->{connect_to_internet_ok} ) { $CPAN::Frontend->myprint(qq{Trying to fetch a mirror list from the Internet\n}); eval { CPAN::FTP->localize('MIRRORED.BY',File::Spec->catfile($CPAN::Config->{keep_source_where},'MIRRORED.BY'),3,1) } or $CPAN::Frontend->mywarn(<<'HERE'); We failed to get a copy of the mirror list from the Internet. You will need to provide CPAN mirror URLs yourself. HERE $CPAN::Frontend->myprint("\n"); } my $mirrors = CPAN::Mirrors->new( _mirror_file() ); my @continents = $mirrors->find_best_continents; my @mirrors = $mirrors->get_mirrors_by_continents( $continents[0] ); my @timings = $mirrors->get_mirrors_timings( \@mirrors ); foreach my $timing ( @timings ) { $logger->info( sprintf "%s (%0.2f ms)", $timing->hostname, $timing->rtt ); } } return HEY_IT_WORKED; } sub _check_install_dirs { my $makepl_arg = $CPAN::Config->{makepl_arg}; my $mbuildpl_arg = $CPAN::Config->{mbuildpl_arg}; my @custom_dirs; # PERL_MM_OPT push @custom_dirs, $makepl_arg =~ m/INSTALL_BASE\s*=\s*(\S+)/g, $mbuildpl_arg =~ m/--install_base\s*=\s*(\S+)/g; if( @custom_dirs ) { foreach my $dir ( @custom_dirs ) { _print_inc_dir_report( $dir ); } } # XXX: also need to check makepl_args, etc my @checks = ( [ 'core', [ grep $_, @Config{qw(installprivlib installarchlib)} ] ], [ 'vendor', [ grep $_, @Config{qw(installvendorlib installvendorarch)} ] ], [ 'site', [ grep $_, @Config{qw(installsitelib installsitearch)} ] ], [ 'PERL5LIB', _split_paths( $ENV{PERL5LIB} ) ], [ 'PERLLIB', _split_paths( $ENV{PERLLIB} ) ], ); $logger->info( '-' x 50 . "\nChecking install dirs..." ); foreach my $tuple ( @checks ) { my( $label ) = $tuple->[0]; $logger->info( "Checking $label" ); $logger->info( "\tno directories for $label" ) unless @{ $tuple->[1] }; foreach my $dir ( @{ $tuple->[1] } ) { _print_inc_dir_report( $dir ); } } } sub _split_paths { [ map { _expand_filename( $_ ) } split /$Config{path_sep}/, $_[0] || '' ]; } =pod Stolen from File::Path::Expand =cut sub _expand_filename { my( $path ) = @_; no warnings 'uninitialized'; $logger->debug( "Expanding path $path\n" ); $path =~ s{\A~([^/]+)?}{ _home_of( $1 || $> ) || "~$1" }e; return $path; } sub _home_of { require User::pwent; my( $user ) = @_; my $ent = User::pwent::getpw($user) or return; return $ent->dir; } sub _get_default_inc { require Config; [ @Config::Config{ _vars() }, '.' ]; } sub _vars { qw( installarchlib installprivlib installsitearch installsitelib ); } sub _ping_mirrors { my $urls = $CPAN::Config->{urllist}; require URI; foreach my $url ( @$urls ) { my( $obj ) = URI->new( $url ); next unless _is_pingable_scheme( $obj ); my $host = $obj->host; _print_ping_report( $obj ); } } sub _is_pingable_scheme { my( $uri ) = @_; $uri->scheme eq 'file' } sub _mirror_file { my $file = do { my $file = 'MIRRORED.BY'; my $local_path = File::Spec->catfile( $CPAN::Config->{keep_source_where}, $file ); if( -e $local_path ) { $local_path } else { require CPAN::FTP; CPAN::FTP->localize( $file, $local_path, 3, 1 ); $local_path; } }; } sub _find_good_mirrors { require CPAN::Mirrors; my $mirrors = CPAN::Mirrors->new( _mirror_file() ); my @mirrors = $mirrors->best_mirrors( how_many => 5, verbose => 1, ); foreach my $mirror ( @mirrors ) { next unless eval { $mirror->can( 'http' ) }; _print_ping_report( $mirror->http ); } $CPAN::Config->{urllist} = [ map { $_->http } @mirrors ]; } sub _print_inc_dir_report { my( $dir ) = shift; my $writeable = -w $dir ? '+' : '!!! (not writeable)'; $logger->info( "\t$writeable $dir" ); return -w $dir; } sub _print_ping_report { my( $mirror ) = @_; my $rtt = eval { _get_ping_report( $mirror ) }; my $result = $rtt ? sprintf "+ (%4d ms)", $rtt * 1000 : '!'; $logger->info( sprintf "\t%s %s", $result, $mirror ); } sub _get_ping_report { require URI; my( $mirror ) = @_; my( $url ) = ref $mirror ? $mirror : URI->new( $mirror ); #XXX require Net::Ping; my $ping = Net::Ping->new( 'tcp', 1 ); if( $url->scheme eq 'file' ) { return -e $url->file; } my( $port ) = $url->port; return unless $port; if ( $ping->can('port_number') ) { $ping->port_number($port); } else { $ping->{'port_num'} = $port; } $ping->hires(1) if $ping->can( 'hires' ); my( $alive, $rtt ) = eval{ $ping->ping( $url->host ) }; $alive ? $rtt : undef; } sub _load_local_lib # -I { $logger->debug( "Loading local::lib" ); my $rc = _safe_load_module("local::lib"); unless( $rc ) { $logger->logdie( "Could not load local::lib" ); } local::lib->import; return HEY_IT_WORKED; } sub _use_these_mirrors # -M { $logger->debug( "Setting per session mirrors" ); unless( $_[0] ) { $logger->logdie( "The -M switch requires a comma-separated list of mirrors" ); } $CPAN::Config->{urllist} = [ split /,/, $_[0] ]; $logger->debug( "Mirrors are @{$CPAN::Config->{urllist}}" ); } sub _create_autobundle { $logger->info( "Creating autobundle in $CPAN::Config->{cpan_home}/Bundle" ); CPAN::Shell->autobundle; return HEY_IT_WORKED; } sub _recompile { $logger->info( "Recompiling dynamically-loaded extensions" ); CPAN::Shell->recompile; return HEY_IT_WORKED; } sub _upgrade { $logger->info( "Upgrading all modules" ); CPAN::Shell->upgrade(); return HEY_IT_WORKED; } sub _shell { $logger->info( "Dropping into shell" ); CPAN::shell(); return HEY_IT_WORKED; } sub _load_config # -j { my $argument = shift; my $file = file_name_is_absolute( $argument ) ? $argument : rel2abs( $argument ); croak( "cpan config file [$file] for -j does not exist!\n" ) unless -e $file; # should I clear out any existing config here? $CPAN::Config = {}; delete $INC{'CPAN/Config.pm'}; my $rc = eval "require '$file'"; # CPAN::HandleConfig::require_myconfig_or_config looks for this $INC{'CPAN/MyConfig.pm'} = 'fake out!'; # CPAN::HandleConfig::load looks for this $CPAN::Config_loaded = 'fake out'; croak( "Could not load [$file]: $@\n") unless $rc; return HEY_IT_WORKED; } sub _dump_config # -J { my $args = shift; require Data::Dumper; my $fh = $args->[0] || \*STDOUT; local $Data::Dumper::Sortkeys = 1; my $dd = Data::Dumper->new( [$CPAN::Config], ['$CPAN::Config'] ); print $fh $dd->Dump, "\n1;\n__END__\n"; return HEY_IT_WORKED; } sub _lock_lobotomy # -F { no warnings 'redefine'; *CPAN::_flock = sub { 1 }; *CPAN::checklock = sub { 1 }; return HEY_IT_WORKED; } sub _download { my $args = shift; local $CPAN::DEBUG = 1; my %paths; foreach my $arg ( @$args ) { $logger->info( "Checking $arg" ); my $module = _expand_module( $arg ) or next; my $path = $module->cpan_file; $logger->debug( "Inst file would be $path\n" ); $paths{$module} = _get_file( _make_path( $path ) ); $logger->info( "Downloaded [$arg] to [$paths{$arg}]" ); } return \%paths; } sub _make_path { join "/", qw(authors id), $_[0] } sub _get_file { my $path = shift; my $loaded = _safe_load_module("LWP::Simple"); croak "You need LWP::Simple to use features that fetch files from CPAN\n" unless $loaded; my $file = substr $path, rindex( $path, '/' ) + 1; my $store_path = catfile( cwd(), $file ); $logger->debug( "Store path is $store_path" ); foreach my $site ( @{ $CPAN::Config->{urllist} } ) { my $fetch_path = join "/", $site, $path; $logger->debug( "Trying $fetch_path" ); my $status_code = LWP::Simple::getstore( $fetch_path, $store_path ); last if( 200 <= $status_code and $status_code <= 300 ); $logger->warn( "Could not get [$fetch_path]: Status code $status_code" ); } return $store_path; } sub _gitify { my $args = shift; my $loaded = _safe_load_module("Archive::Extract"); croak "You need Archive::Extract to use features that gitify distributions\n" unless $loaded; my $starting_dir = cwd(); foreach my $arg ( @$args ) { $logger->info( "Checking $arg" ); my $store_paths = _download( [ $arg ] ); $logger->debug( "gitify Store path is $store_paths->{$arg}" ); my $dirname = dirname( $store_paths->{$arg} ); my $ae = Archive::Extract->new( archive => $store_paths->{$arg} ); $ae->extract( to => $dirname ); chdir $ae->extract_path; my $git = $ENV{GIT_COMMAND} || '/usr/local/bin/git'; croak "Could not find $git" unless -e $git; croak "$git is not executable" unless -x $git; # can we do this in Pure Perl? system( $git, 'init' ); system( $git, qw( add . ) ); system( $git, qw( commit -a -m ), 'initial import' ); } chdir $starting_dir; return HEY_IT_WORKED; } sub _show_Changes { my $args = shift; foreach my $arg ( @$args ) { $logger->info( "Checking $arg\n" ); my $module = _expand_module( $arg ) or next; my $out = _get_cpanpm_output(); next unless eval { $module->inst_file }; #next if $module->uptodate; ( my $id = $module->id() ) =~ s/::/\-/; my $url = "http://search.cpan.org/~" . lc( $module->userid ) . "/" . $id . "-" . $module->cpan_version() . "/"; #print "URL: $url\n"; _get_changes_file($url); } return HEY_IT_WORKED; } sub _get_changes_file { croak "Reading Changes files requires LWP::Simple and URI\n" unless _safe_load_module("LWP::Simple") && _safe_load_module("URI"); my $url = shift; my $content = LWP::Simple::get( $url ); $logger->info( "Got $url ..." ) if defined $content; #print $content; my( $change_link ) = $content =~ m|Changes|gi; my $changes_url = URI->new_abs( $change_link, $url ); $logger->debug( "Change link is: $changes_url" ); my $changes = LWP::Simple::get( $changes_url ); print $changes; return HEY_IT_WORKED; } sub _show_Author { my $args = shift; foreach my $arg ( @$args ) { my $module = _expand_module( $arg ) or next; unless( $module ) { $logger->info( "Didn't find a $arg module, so no author!" ); next; } my $author = CPAN::Shell->expand( "Author", $module->userid ); next unless $module->userid; printf "%-25s %-8s %-25s %s\n", $arg, $module->userid, $author->email, $author->name; } return HEY_IT_WORKED; } sub _show_Details { my $args = shift; foreach my $arg ( @$args ) { my $module = _expand_module( $arg ) or next; my $author = CPAN::Shell->expand( "Author", $module->userid ); next unless $module->userid; print "$arg\n", "-" x 73, "\n\t"; print join "\n\t", $module->description ? $module->description : "(no description)", $module->cpan_file ? $module->cpan_file : "(no cpanfile)", $module->inst_file ? $module->inst_file :"(no installation file)" , 'Installed: ' . ($module->inst_version ? $module->inst_version : "not installed"), 'CPAN: ' . $module->cpan_version . ' ' . ($module->uptodate ? "" : "Not ") . "up to date", $author->fullname . " (" . $module->userid . ")", $author->email; print "\n\n"; } return HEY_IT_WORKED; } BEGIN { my $modules; sub _get_all_namespaces { return $modules if $modules; $modules = [ map { $_->id } CPAN::Shell->expand( "Module", "/./" ) ]; } } sub _show_out_of_date { my $modules = _get_all_namespaces(); printf "%-40s %6s %6s\n", "Module Name", "Local", "CPAN"; print "-" x 73, "\n"; foreach my $module ( @$modules ) { next unless $module = _expand_module($module); next unless $module->inst_file; next if $module->uptodate; printf "%-40s %.4f %.4f\n", $module->id, $module->inst_version ? $module->inst_version : '', $module->cpan_version; } return HEY_IT_WORKED; } sub _show_author_mods { my $args = shift; my %hash = map { lc $_, 1 } @$args; my $modules = _get_all_namespaces(); foreach my $module ( @$modules ) { next unless exists $hash{ lc $module->userid }; print $module->id, "\n"; } return HEY_IT_WORKED; } sub _list_all_mods # -l { require File::Find; my $args = shift; my $fh = \*STDOUT; INC: foreach my $inc ( @INC ) { my( $wanted, $reporter ) = _generator(); File::Find::find( { wanted => $wanted }, $inc ); my $count = 0; FILE: foreach my $file ( @{ $reporter->() } ) { my $version = _parse_version_safely( $file ); my $module_name = _path_to_module( $inc, $file ); next FILE unless defined $module_name; print $fh "$module_name\t$version\n"; #last if $count++ > 5; } } return HEY_IT_WORKED; } sub _generator { my @files = (); sub { push @files, File::Spec->canonpath( $File::Find::name ) if m/\A\w+\.pm\z/ }, sub { \@files }, } sub _parse_version_safely # stolen from PAUSE's mldistwatch, but refactored { my( $file ) = @_; local $/ = "\n"; local $_; # don't mess with the $_ in the map calling this return unless open FILE, "<$file"; my $in_pod = 0; my $version; while( ) { chomp; $in_pod = /^=(?!cut)/ ? 1 : /^=cut/ ? 0 : $in_pod; next if $in_pod || /^\s*#/; next unless /([\$*])(([\w\:\']*)\bVERSION)\b.*\=/; my( $sigil, $var ) = ( $1, $2 ); $version = _eval_version( $_, $sigil, $var ); last; } close FILE; return 'undef' unless defined $version; return $version; } sub _eval_version { my( $line, $sigil, $var ) = @_; # split package line to hide from PAUSE my $eval = qq{ package ExtUtils::MakeMaker::_version; local $sigil$var; \$$var=undef; do { $line }; \$$var }; my $version = do { local $^W = 0; no strict; eval( $eval ); }; return $version; } sub _path_to_module { my( $inc, $path ) = @_; return if length $path < length $inc; my $module_path = substr( $path, length $inc ); $module_path =~ s/\.pm\z//; # XXX: this is cheating and doesn't handle everything right my @dirs = grep { ! /\W/ } File::Spec->splitdir( $module_path ); shift @dirs; my $module_name = join "::", @dirs; return $module_name; } sub _expand_module { my( $module ) = @_; my $expanded = CPAN::Shell->expandany( $module ); return $expanded if $expanded; $expanded = CPAN::Shell->expand( "Module", $module ); unless( defined $expanded ) { $logger->error( "Could not expand [$module]. Check the module name." ); my $threshold = ( grep { int } sort { length $a <=> length $b } length($module)/4, 4 )[0]; my $guesses = _guess_at_module_name( $module, $threshold ); if( defined $guesses and @$guesses ) { $logger->info( "Perhaps you meant one of these:" ); foreach my $guess ( @$guesses ) { $logger->info( "\t$guess" ); } } return; } return $expanded; } my $guessers = [ [ qw( Text::Levenshtein::XS distance 7 1 ) ], [ qw( Text::Levenshtein::Damerau::XS xs_edistance 7 1 ) ], [ qw( Text::Levenshtein distance 7 1 ) ], [ qw( Text::Levenshtein::Damerau::PP pp_edistance 7 1 ) ], ]; sub _disable_guessers { $_->[-1] = 0 for @$guessers; } # for -x sub _guess_namespace { my $args = shift; foreach my $arg ( @$args ) { $logger->debug( "Checking $arg" ); my $guesses = _guess_at_module_name( $arg ); foreach my $guess ( @$guesses ) { print $guess, "\n"; } } return HEY_IT_WORKED; } sub _list_all_namespaces { my $modules = _get_all_namespaces(); foreach my $module ( @$modules ) { print $module, "\n"; } } BEGIN { my $distance; my $_threshold; my $can_guess; my $shown_help = 0; sub _guess_at_module_name { my( $target, $threshold ) = @_; unless( defined $distance ) { foreach my $try ( @$guessers ) { $can_guess = eval "require $try->[0]; 1" or next; $try->[-1] or next; # disabled no strict 'refs'; $distance = \&{ join "::", @$try[0,1] }; $threshold ||= $try->[2]; } } $_threshold ||= $threshold; unless( $distance ) { unless( $shown_help ) { my $modules = join ", ", map { $_->[0] } @$guessers; substr $modules, rindex( $modules, ',' ), 1, ', and'; # Should this be colorized? if( $can_guess ) { $logger->info( "I can suggest names if you provide the -x option on invocation." ); } else { $logger->info( "I can suggest names if you install one of $modules" ); $logger->info( "and you provide the -x option on invocation." ); } $shown_help++; } return; } my $modules = _get_all_namespaces(); $logger->info( "Checking " . @$modules . " namespaces for close match suggestions" ); my %guesses; foreach my $guess ( @$modules ) { my $distance = $distance->( $target, $guess ); next if $distance > $_threshold; $guesses{$guess} = $distance; } my @guesses = sort { $guesses{$a} <=> $guesses{$b} } keys %guesses; return [ grep { defined } @guesses[0..9] ]; } } 1; =back =head1 EXIT VALUES The script exits with zero if it thinks that everything worked, or a positive number if it thinks that something failed. Note, however, that in some cases it has to divine a failure by the output of things it does not control. For now, the exit codes are vague: 1 An unknown error 2 The was an external problem 4 There was an internal problem with the script 8 A module failed to install =head1 TO DO * There is initial support for Log4perl if it is available, but I haven't gone through everything to make the NullLogger work out correctly if Log4perl is not installed. * When I capture CPAN.pm output, I need to check for errors and report them to the user. * Warnings switch * Check then exit =head1 BUGS * none noted =head1 SEE ALSO L, L =head1 SOURCE AVAILABILITY This code is in Github in the CPAN.pm repository: https://github.com/andk/cpanpm The source used to be tracked separately in another GitHub repo, but the canonical source is now in the above repo. =head1 CREDITS Japheth Cleaver added the bits to allow a forced install (C<-f>). Jim Brandt suggested and provided the initial implementation for the up-to-date and Changes features. Adam Kennedy pointed out that C causes problems on Windows where this script ends up with a .bat extension David Golden helps integrate this into the C repos. Jim Keenan fixed up various issues with _download =head1 AUTHOR brian d foy, C<< >> =head1 COPYRIGHT Copyright (c) 2001-2021, brian d foy, All Rights Reserved. You may redistribute this under the same terms as Perl itself. =cut # Local Variables: # mode: cperl # indent-tabs-mode: t # cperl-indent-level: 8 # cperl-continued-statement-offset: 8 # End: PK!}l++perl5/CPAN/API/HOWTO.podnu6$=head1 NAME CPAN::API::HOWTO - a recipe book for programming with CPAN.pm =head1 RECIPES All of these recipes assume that you have put "use CPAN" at the top of your program. =head2 What distribution contains a particular module? my $distribution = CPAN::Shell->expand( "Module", "Data::UUID" )->distribution()->pretty_id(); This returns a string of the form "AUTHORID/TARBALL". If you want the full path and filename to this distribution on a CPAN mirror, then it is C<.../authors/id/A/AU/AUTHORID/TARBALL>. =head2 What modules does a particular distribution contain? CPAN::Index->reload(); my @modules = CPAN::Shell->expand( "Distribution", "JHI/Graph-0.83.tar.gz" )->containsmods(); You may also refer to a distribution in the form A/AU/AUTHORID/TARBALL. =head1 SEE ALSO the main CPAN.pm documentation =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L =head1 AUTHOR David Cantrell =cut PK!ܑH*perl5/CPAN/Exception/yaml_process_error.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Exception::yaml_process_error; use strict; use overload '""' => "as_string"; use vars qw( $VERSION ); $VERSION = "5.5"; sub new { my($class,$module,$file,$during,$error) = @_; # my $at = Carp::longmess(""); # XXX find something more beautiful bless { module => $module, file => $file, during => $during, error => $error, # at => $at, }, $class; } sub as_string { my($self) = shift; if ($self->{during}) { if ($self->{file}) { if ($self->{module}) { if ($self->{error}) { return "Alert: While trying to '$self->{during}' YAML file\n". " '$self->{file}'\n". "with '$self->{module}' the following error was encountered:\n". " $self->{error}\n"; } else { return "Alert: While trying to '$self->{during}' YAML file\n". " '$self->{file}'\n". "with '$self->{module}' some unknown error was encountered\n"; } } else { return "Alert: While trying to '$self->{during}' YAML file\n". " '$self->{file}'\n". "some unknown error was encountered\n"; } } else { return "Alert: While trying to '$self->{during}' some YAML file\n". "some unknown error was encountered\n"; } } else { return "Alert: unknown error encountered\n"; } } 1; PK!1..+perl5/CPAN/Exception/RecursiveDependency.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Exception::RecursiveDependency; use strict; use overload '""' => "as_string"; use vars qw( $VERSION ); $VERSION = "5.5001"; { package CPAN::Exception::RecursiveDependency::na; use overload '""' => "as_string"; sub new { bless {}, shift }; sub as_string { "N/A" }; } my $NA = CPAN::Exception::RecursiveDependency::na->new; # a module sees its distribution (no version) # a distribution sees its prereqs (which are module names) (usually with versions) # a bundle sees its module names and/or its distributions (no version) sub new { my($class) = shift; my($deps_arg) = shift; my (@deps,%seen,$loop_starts_with); DCHAIN: for my $dep (@$deps_arg) { push @deps, {name => $dep, display_as => $dep}; if ($seen{$dep}++) { $loop_starts_with = $dep; last DCHAIN; } } my $in_loop = 0; my %mark; DWALK: for my $i (0..$#deps) { my $x = $deps[$i]{name}; $in_loop ||= $loop_starts_with && $x eq $loop_starts_with; my $xo = CPAN::Shell->expandany($x) or next; if ($xo->isa("CPAN::Module")) { my $have = $xo->inst_version || $NA; my($want,$d,$want_type); if ($i>0 and $d = $deps[$i-1]{name}) { my $do = CPAN::Shell->expandany($d); $want = $do->{prereq_pm}{requires}{$x}; if (defined $want) { $want_type = "requires: "; } else { $want = $do->{prereq_pm}{build_requires}{$x}; if (defined $want) { $want_type = "build_requires: "; } else { $want_type = "unknown status"; $want = "???"; } } } else { $want = $xo->cpan_version; $want_type = "want: "; } $deps[$i]{have} = $have; $deps[$i]{want_type} = $want_type; $deps[$i]{want} = $want; $deps[$i]{display_as} = "$x (have: $have; $want_type$want)"; if ((! ref $have || !$have->isa('CPAN::Exception::RecursiveDependency::na')) && CPAN::Version->vge($have, $want)) { # https://rt.cpan.org/Ticket/Display.html?id=115340 undef $loop_starts_with; last DWALK; } } elsif ($xo->isa("CPAN::Distribution")) { my $pretty = $deps[$i]{display_as} = $xo->pretty_id; my $mark_as; if ($in_loop) { $mark_as = CPAN::Distrostatus->new("NO cannot resolve circular dependency"); } else { $mark_as = CPAN::Distrostatus->new("NO one dependency ($loop_starts_with) is a circular dependency"); } $mark{$pretty} = { xo => $xo, mark_as => $mark_as }; } } if ($loop_starts_with) { while (my($k,$v) = each %mark) { my $xo = $v->{xo}; $xo->{make} = $v->{mark_as}; $xo->store_persistent_state; # otherwise I will not reach # all involved parties for # the next session } } bless { deps => \@deps, loop_starts_with => $loop_starts_with }, $class; } sub is_resolvable { ! defined shift->{loop_starts_with}; } sub as_string { my($self) = shift; my $deps = $self->{deps}; my $loop_starts_with = $self->{loop_starts_with}; unless ($loop_starts_with) { return "--not a recursive/circular dependency--"; } my $ret = "\nRecursive dependency detected:\n "; $ret .= join("\n => ", map {$_->{display_as}} @$deps); $ret .= ".\nCannot resolve.\n"; $ret; } 1; PK!T*perl5/CPAN/Exception/yaml_not_installed.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Exception::yaml_not_installed; use strict; use overload '""' => "as_string"; use vars qw( $VERSION ); $VERSION = "5.5"; sub new { my($class,$module,$file,$during) = @_; bless { module => $module, file => $file, during => $during }, $class; } sub as_string { my($self) = shift; "'$self->{module}' not installed, cannot $self->{during} '$self->{file}'\n"; } 1; PK!*^'perl5/CPAN/Exception/blocked_urllist.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Exception::blocked_urllist; use strict; use overload '""' => "as_string"; use vars qw( $VERSION ); $VERSION = "1.001"; sub new { my($class) = @_; bless {}, $class; } sub as_string { my($self) = shift; if ($CPAN::Config->{connect_to_internet_ok}) { return qq{ You have not configured a urllist for CPAN mirrors. Configure it with o conf init urllist }; } else { return qq{ You have not configured a urllist and do not allow connections to the internet to get a list of mirrors. If you wish to get a list of CPAN mirrors to pick from, use this command o conf init connect_to_internet_ok urllist If you do not wish to get a list of mirrors and would prefer to set your urllist manually, use just this command instead o conf init urllist }; } } 1; PK!Hperl5/CPAN/FTP/netrc.pmnu6$package CPAN::FTP::netrc; use strict; $CPAN::FTP::netrc::VERSION = $CPAN::FTP::netrc::VERSION = "1.01"; # package CPAN::FTP::netrc; sub new { my($class) = @_; my $file = File::Spec->catfile($ENV{HOME},".netrc"); my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file); $mode ||= 0; my $protected = 0; my($fh,@machines,$hasdefault); $hasdefault = 0; $fh = FileHandle->new or die "Could not create a filehandle"; if($fh->open($file)) { $protected = ($mode & 077) == 0; local($/) = ""; NETRC: while (<$fh>) { my(@tokens) = split " ", $_; TOKEN: while (@tokens) { my($t) = shift @tokens; if ($t eq "default") { $hasdefault++; last NETRC; } last TOKEN if $t eq "macdef"; if ($t eq "machine") { push @machines, shift @tokens; } } } } else { $file = $hasdefault = $protected = ""; } bless { 'mach' => [@machines], 'netrc' => $file, 'hasdefault' => $hasdefault, 'protected' => $protected, }, $class; } # CPAN::FTP::netrc::hasdefault; sub hasdefault { shift->{'hasdefault'} } sub netrc { shift->{'netrc'} } sub protected { shift->{'protected'} } sub contains { my($self,$mach) = @_; for ( @{$self->{'mach'}} ) { return 1 if $_ eq $mach; } return 0; } 1; PK!((perl5/CPAN/HTTP/Client.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::HTTP::Client; use strict; use vars qw(@ISA); use CPAN::HTTP::Credentials; use HTTP::Tiny 0.005; $CPAN::HTTP::Client::VERSION = $CPAN::HTTP::Client::VERSION = "1.9602"; # CPAN::HTTP::Client is adapted from parts of cpanm by Tatsuhiko Miyagawa # and parts of LWP by Gisle Aas sub new { my $class = shift; my %args = @_; for my $k ( keys %args ) { $args{$k} = '' unless defined $args{$k}; } $args{no_proxy} = [split(",", $args{no_proxy}) ] if $args{no_proxy}; return bless \%args, $class; } # This executes a request with redirection (up to 5) and returns the # response structure generated by HTTP::Tiny # # If authentication fails, it will attempt to get new authentication # information and repeat up to 5 times sub mirror { my($self, $uri, $path) = @_; my $want_proxy = $self->_want_proxy($uri); my $http = HTTP::Tiny->new( verify_SSL => 1, $want_proxy ? (proxy => $self->{proxy}) : () ); my ($response, %headers); my $retries = 0; while ( $retries++ < 5 ) { $response = $http->mirror( $uri, $path, {headers => \%headers} ); if ( $response->{status} eq '401' ) { last unless $self->_get_auth_params( $response, 'non_proxy' ); } elsif ( $response->{status} eq '407' ) { last unless $self->_get_auth_params( $response, 'proxy' ); } else { last; # either success or failure } my %headers = ( $self->_auth_headers( $uri, 'non_proxy' ), ( $want_proxy ? $self->_auth_headers($uri, 'proxy') : () ), ); } return $response; } sub _want_proxy { my ($self, $uri) = @_; return unless $self->{proxy}; my($host) = $uri =~ m|://([^/:]+)|; return ! grep { $host =~ /\Q$_\E$/ } @{ $self->{no_proxy} || [] }; } # Generates the authentication headers for a given mode # C is 'proxy' or 'non_proxy' # C<_${mode}_type> is 'basic' or 'digest' # C<_${mode}_params> will be the challenge parameters from the 401/407 headers sub _auth_headers { my ($self, $uri, $mode) = @_; # Get names for our mode-specific attributes my ($type_key, $param_key) = map {"_" . $mode . $_} qw/_type _params/; # If _prepare_auth has not been called, we can't prepare headers return unless $self->{$type_key}; # Get user credentials for mode my $cred_method = "get_" . ($mode ? "proxy" : "non_proxy") ."_credentials"; my ($user, $pass) = CPAN::HTTP::Credentials->$cred_method; # Generate the header for the mode & type my $header = $mode eq 'proxy' ? 'Proxy-Authorization' : 'Authorization'; my $value_method = "_" . $self->{$type_key} . "_auth"; my $value = $self->$value_method($user, $pass, $self->{$param_key}, $uri); # If we didn't get a value, we didn't have the right modules available return $value ? ( $header, $value ) : (); } # Extract authentication parameters from headers, but clear any prior # credentials if we failed (so we might prompt user for password again) sub _get_auth_params { my ($self, $response, $mode) = @_; my $prefix = $mode eq 'proxy' ? 'Proxy' : 'WWW'; my ($type_key, $param_key) = map {"_" . $mode . $_} qw/_type _params/; if ( ! $response->{success} ) { # auth failed my $method = "clear_${mode}_credentials"; CPAN::HTTP::Credentials->$method; delete $self->{$_} for $type_key, $param_key; } ($self->{$type_key}, $self->{$param_key}) = $self->_get_challenge( $response, "${prefix}-Authenticate"); return $self->{$type_key}; } # Extract challenge type and parameters for a challenge list sub _get_challenge { my ($self, $response, $auth_header) = @_; my $auth_list = $response->{headers}(lc $auth_header); return unless defined $auth_list; $auth_list = [$auth_list] unless ref $auth_list; for my $challenge (@$auth_list) { $challenge =~ tr/,/;/; # "," is used to separate auth-params!! ($challenge) = $self->split_header_words($challenge); my $scheme = shift(@$challenge); shift(@$challenge); # no value $challenge = { @$challenge }; # make rest into a hash unless ($scheme =~ /^(basic|digest)$/) { next; # bad scheme } $scheme = $1; # untainted now return ($scheme, $challenge); } return; } # Generate a basic authentication header value sub _basic_auth { my ($self, $user, $pass) = @_; unless ( $CPAN::META->has_usable('MIME::Base64') ) { $CPAN::Frontend->mywarn( "MIME::Base64 is required for 'Basic' style authentication" ); return; } return "Basic " . MIME::Base64::encode_base64("$user\:$pass", q{}); } # Generate a digest authentication header value sub _digest_auth { my ($self, $user, $pass, $auth_param, $uri) = @_; unless ( $CPAN::META->has_usable('Digest::MD5') ) { $CPAN::Frontend->mywarn( "Digest::MD5 is required for 'Digest' style authentication" ); return; } my $nc = sprintf "%08X", ++$self->{_nonce_count}{$auth_param->{nonce}}; my $cnonce = sprintf "%8x", time; my ($path) = $uri =~ m{^\w+?://[^/]+(/.*)$}; $path = "/" unless defined $path; my $md5 = Digest::MD5->new; my(@digest); $md5->add(join(":", $user, $auth_param->{realm}, $pass)); push(@digest, $md5->hexdigest); $md5->reset; push(@digest, $auth_param->{nonce}); if ($auth_param->{qop}) { push(@digest, $nc, $cnonce, ($auth_param->{qop} =~ m|^auth[,;]auth-int$|) ? 'auth' : $auth_param->{qop}); } $md5->add(join(":", 'GET', $path)); push(@digest, $md5->hexdigest); $md5->reset; $md5->add(join(":", @digest)); my($digest) = $md5->hexdigest; $md5->reset; my %resp = map { $_ => $auth_param->{$_} } qw(realm nonce opaque); @resp{qw(username uri response algorithm)} = ($user, $path, $digest, "MD5"); if (($auth_param->{qop} || "") =~ m|^auth([,;]auth-int)?$|) { @resp{qw(qop cnonce nc)} = ("auth", $cnonce, $nc); } my(@order) = qw(username realm qop algorithm uri nonce nc cnonce response opaque); my @pairs; for (@order) { next unless defined $resp{$_}; push(@pairs, "$_=" . qq("$resp{$_}")); } my $auth_value = "Digest " . join(", ", @pairs); return $auth_value; } # split_header_words adapted from HTTP::Headers::Util sub split_header_words { my ($self, @words) = @_; my @res = $self->_split_header_words(@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($self, @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; } 1; PK!3yI I perl5/CPAN/HTTP/Credentials.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::HTTP::Credentials; use strict; use vars qw($USER $PASSWORD $PROXY_USER $PROXY_PASSWORD); $CPAN::HTTP::Credentials::VERSION = $CPAN::HTTP::Credentials::VERSION = "1.9601"; sub clear_credentials { clear_non_proxy_credentials(); clear_proxy_credentials(); } sub clear_non_proxy_credentials { undef $USER; undef $PASSWORD; } sub clear_proxy_credentials { undef $PROXY_USER; undef $PROXY_PASSWORD; } sub get_proxy_credentials { my $self = shift; if ($PROXY_USER && $PROXY_PASSWORD) { return ($PROXY_USER, $PROXY_PASSWORD); } if ( defined $CPAN::Config->{proxy_user} && $CPAN::Config->{proxy_user} ) { $PROXY_USER = $CPAN::Config->{proxy_user}; $PROXY_PASSWORD = $CPAN::Config->{proxy_pass} || ""; return ($PROXY_USER, $PROXY_PASSWORD); } my $username_prompt = "\nProxy authentication needed! (Note: to permanently configure username and password run o conf proxy_user your_username o conf proxy_pass your_password )\nUsername:"; ($PROXY_USER, $PROXY_PASSWORD) = _get_username_and_password_from_user($username_prompt); return ($PROXY_USER,$PROXY_PASSWORD); } sub get_non_proxy_credentials { my $self = shift; if ($USER && $PASSWORD) { return ($USER, $PASSWORD); } if ( defined $CPAN::Config->{username} ) { $USER = $CPAN::Config->{username}; $PASSWORD = $CPAN::Config->{password} || ""; return ($USER, $PASSWORD); } my $username_prompt = "\nAuthentication needed! (Note: to permanently configure username and password run o conf username your_username o conf password your_password )\nUsername:"; ($USER, $PASSWORD) = _get_username_and_password_from_user($username_prompt); return ($USER,$PASSWORD); } sub _get_username_and_password_from_user { my $username_message = shift; my ($username,$password); ExtUtils::MakeMaker->import(qw(prompt)); $username = prompt($username_message); if ($CPAN::META->has_inst("Term::ReadKey")) { Term::ReadKey::ReadMode("noecho"); } else { $CPAN::Frontend->mywarn( "Warning: Term::ReadKey seems not to be available, your password will be echoed to the terminal!\n" ); } $password = prompt("Password:"); if ($CPAN::META->has_inst("Term::ReadKey")) { Term::ReadKey::ReadMode("restore"); } $CPAN::Frontend->myprint("\n\n"); return ($username,$password); } 1; PK!w)#99"perl5/CPAN/Kwalify/distroprefs.ymlnu6$--- type: map mapping: comment: type: text depends: type: map mapping: configure_requires: &requires_common type: map mapping: =: type: text build_requires: *requires_common requires: *requires_common match: type: map mapping: distribution: type: text module: type: text perl: type: text perlconfig: &matchhash_common type: map mapping: =: type: text env: *matchhash_common install: &args_env_expect type: map mapping: args: type: seq sequence: - type: text commandline: type: text env: type: map mapping: =: type: text expect: type: seq sequence: - type: text eexpect: type: map mapping: mode: type: text enum: - deterministic - anyorder timeout: type: number reuse: type: int talk: type: seq sequence: - type: text make: *args_env_expect pl: *args_env_expect test: *args_env_expect patches: type: seq sequence: - type: text disabled: type: int enum: - 0 - 1 goto: type: text cpanconfig: type: map mapping: =: type: text features: type: seq sequence: - type: text reminder: type: text PK!< !perl5/CPAN/Kwalify/distroprefs.ddnu6$$VAR1 = { "mapping" => { "comment" => { "type" => "text" }, "cpanconfig" => { "mapping" => { "=" => { "type" => "text" } }, "type" => "map" }, "depends" => { "mapping" => { "build_requires" => { "mapping" => { "=" => { "type" => "text" } }, "type" => "map" }, "configure_requires" => {}, "requires" => {} }, "type" => "map" }, "disabled" => { "enum" => [ 0, 1 ], "type" => "int" }, "features" => { "sequence" => [ { "type" => "text" } ], "type" => "seq" }, "goto" => { "type" => "text" }, "install" => { "mapping" => { "args" => { "sequence" => [ { "type" => "text" } ], "type" => "seq" }, "commandline" => { "type" => "text" }, "eexpect" => { "mapping" => { "mode" => { "enum" => [ "deterministic", "anyorder" ], "type" => "text" }, "reuse" => { "type" => "int" }, "talk" => { "sequence" => [ { "type" => "text" } ], "type" => "seq" }, "timeout" => { "type" => "number" } }, "type" => "map" }, "env" => { "mapping" => { "=" => { "type" => "text" } }, "type" => "map" }, "expect" => { "sequence" => [ { "type" => "text" } ], "type" => "seq" } }, "type" => "map" }, "make" => {}, "match" => { "mapping" => { "distribution" => { "type" => "text" }, "env" => { "mapping" => { "=" => { "type" => "text" } }, "type" => "map" }, "module" => { "type" => "text" }, "perl" => { "type" => "text" }, "perlconfig" => {} }, "type" => "map" }, "patches" => { "sequence" => [ { "type" => "text" } ], "type" => "seq" }, "pl" => {}, "reminder" => { "type" => "text" }, "test" => {} }, "type" => "map" }; $VAR1->{"mapping"}{"depends"}{"mapping"}{"configure_requires"} = $VAR1->{"mapping"}{"depends"}{"mapping"}{"build_requires"}; $VAR1->{"mapping"}{"depends"}{"mapping"}{"requires"} = $VAR1->{"mapping"}{"depends"}{"mapping"}{"build_requires"}; $VAR1->{"mapping"}{"make"} = $VAR1->{"mapping"}{"install"}; $VAR1->{"mapping"}{"match"}{"mapping"}{"perlconfig"} = $VAR1->{"mapping"}{"match"}{"mapping"}{"env"}; $VAR1->{"mapping"}{"pl"} = $VAR1->{"mapping"}{"install"}; $VAR1->{"mapping"}{"test"} = $VAR1->{"mapping"}{"install"}; PK!>+perl5/CPAN/LWP/UserAgent.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::LWP::UserAgent; use strict; use vars qw(@ISA $USER $PASSWD $SETUPDONE); use CPAN::HTTP::Credentials; # we delay requiring LWP::UserAgent and setting up inheritance until we need it $CPAN::LWP::UserAgent::VERSION = $CPAN::LWP::UserAgent::VERSION = "1.9601"; sub config { return if $SETUPDONE; if ($CPAN::META->has_usable('LWP::UserAgent')) { require LWP::UserAgent; @ISA = qw(Exporter LWP::UserAgent); ## no critic $SETUPDONE++; } else { $CPAN::Frontend->mywarn(" LWP::UserAgent not available\n"); } } sub get_basic_credentials { my($self, $realm, $uri, $proxy) = @_; if ( $proxy ) { return CPAN::HTTP::Credentials->get_proxy_credentials(); } else { return CPAN::HTTP::Credentials->get_non_proxy_credentials(); } } sub no_proxy { my ( $self, $no_proxy ) = @_; return $self->SUPER::no_proxy( split(',',$no_proxy) ); } # mirror(): Its purpose is to deal with proxy authentication. When we # call SUPER::mirror, we really call the mirror method in # LWP::UserAgent. LWP::UserAgent will then call # $self->get_basic_credentials or some equivalent and this will be # $self->dispatched to our own get_basic_credentials method. # Our own get_basic_credentials sets $USER and $PASSWD, two globals. # 407 stands for HTTP_PROXY_AUTHENTICATION_REQUIRED. Which means # although we have gone through our get_basic_credentials, the proxy # server refuses to connect. This could be a case where the username or # password has changed in the meantime, so I'm trying once again without # $USER and $PASSWD to give the get_basic_credentials routine another # chance to set $USER and $PASSWD. sub mirror { my($self,$url,$aslocal) = @_; my $result = $self->SUPER::mirror($url,$aslocal); if ($result->code == 407) { CPAN::HTTP::Credentials->clear_credentials; $result = $self->SUPER::mirror($url,$aslocal); } $result; } 1; PK!z¤!!perl5/CPAN/Plugin/Specfile.pmnu6$=head1 NAME CPAN::Plugin::Specfile - Proof of concept implementation of a trivial CPAN::Plugin =head1 SYNOPSIS # once in the cpan shell o conf plugin_list push CPAN::Plugin::Specfile # make permanent o conf commit # any time in the cpan shell to write a spec file test Acme::Meta # disable # if it is the last in plugin_list: o conf plugin_list pop # otherwise, determine the index to splice: o conf plugin_list # and then use splice, e.g. to splice position 3: o conf plugin_list splice 3 1 =head1 DESCRIPTION Implemented as a post-test hook, this plugin writes a specfile after every successful test run. The content is also written to the terminal. As a side effect, the timestamps of the written specfiles reflect the linear order of all dependencies. B This code is just a small demo how to use the plugin system of the CPAN shell, not a full fledged spec file writer. Do not expect new features in this plugin. =head2 OPTIONS The target directory to store the spec files in can be set using C

as in o conf plugin_list push CPAN::Plugin::Specfile=dir,/tmp/specfiles-000042 The default directory for this is the C directory in the I directory. =head1 AUTHOR Andreas Koenig , Branislav Zahradnik =cut package CPAN::Plugin::Specfile; our $VERSION = '0.02'; use File::Path; use File::Spec; sub __accessor { my ($class, $key) = @_; no strict 'refs'; *{$class . '::' . $key} = sub { my $self = shift; if (@_) { $self->{$key} = shift; } return $self->{$key}; }; } BEGIN { __PACKAGE__->__accessor($_) for qw(dir dir_default) } sub new { my($class, @rest) = @_; my $self = bless {}, $class; while (my($arg,$val) = splice @rest, 0, 2) { $self->$arg($val); } $self->dir_default(File::Spec->catdir($CPAN::Config->{cpan_home},"plugins",__PACKAGE__)); $self; } sub post_test { my $self = shift; my $distribution_object = shift; my $distribution = $distribution_object->pretty_id; unless ($CPAN::META->has_inst("CPAN::DistnameInfo")){ $CPAN::Frontend->mydie("CPAN::DistnameInfo not installed; cannot continue"); } my $d = CPAN::Shell->expand("Distribution",$distribution) or $CPAN::Frontend->mydie("Unknowns distribution '$distribution'\n"); my $build_dir = $d->{build_dir} or $CPAN::Frontend->mydie("Distribution has not been built yet, cannot proceed"); my %contains = map {($_ => undef)} $d->containsmods; my @m; my $width = 16; my $header = sub { my($header,$value) = @_; push @m, sprintf("%-s:%*s%s\n", $header, $width-length($header), "", $value); }; my $dni = CPAN::DistnameInfo->new($distribution); my $dist = $dni->dist; my $summary = CPAN::Shell->_guess_manpage($d,\%contains,$dist); $header->("Name", "perl-$dist"); my $version = $dni->version; $header->("Version", $version); $header->("Release", "1%{?dist}"); #Summary: Template processing system #Group: Development/Libraries #License: GPL+ or Artistic #URL: http://www.template-toolkit.org/ #Source0: http://search.cpan.org/CPAN/authors/id/A/AB/ABW/Template-Toolkit-%{version}.tar.gz #Patch0: Template-2.22-SREZIC-01.patch #BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) for my $h_tuple ([Summary => $summary], [Group => "Development/Libraries"], [License =>], [URL =>], [BuildRoot => "%{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)"], [Requires => "perl(:MODULE_COMPAT_%(eval \"`%{__perl} -V:version`\"; echo \$version))"], ) { my($h,$v) = @$h_tuple; $v = "unknown" unless defined $v; $header->($h, $v); } $header->("Source0", sprintf( "http://search.cpan.org/CPAN/authors/id/%s/%s/%s", substr($distribution,0,1), substr($distribution,0,2), $distribution )); require POSIX; my @xs = glob "$build_dir/*.xs"; # quick try unless (@xs) { require ExtUtils::Manifest; my $manifest_file = "$build_dir/MANIFEST"; my $manifest = ExtUtils::Manifest::maniread($manifest_file); @xs = grep /\.xs$/, keys %$manifest; } if (! @xs) { $header->('BuildArch', 'noarch'); } for my $k (sort keys %contains) { my $m = CPAN::Shell->expand("Module",$k); my $v = $contains{$k} = $m->cpan_version; my $vspec = $v eq "undef" ? "" : " = $v"; $header->("Provides", "perl($k)$vspec"); } if (my $prereq_pm = $d->{prereq_pm}) { my %req; for my $reqkey (keys %$prereq_pm) { while (my($k,$v) = each %{$prereq_pm->{$reqkey}}) { $req{$k} = $v; } } if (-e "$build_dir/Build.PL" && ! exists $req{"Module::Build"}) { $req{"Module::Build"} = 0; } for my $k (sort keys %req) { next if $k eq "perl"; my $v = $req{$k}; my $vspec = defined $v && length $v && $v > 0 ? " >= $v" : ""; $header->(BuildRequires => "perl($k)$vspec"); next if $k =~ /^(Module::Build)$/; # MB is always only a # BuildRequires; if we # turn it into a # Requires, then we # would have to make it # a BuildRequires # everywhere we depend # on *one* MB built # module. $header->(Requires => "perl($k)$vspec"); } } push @m, "\n%define _use_internal_dependency_generator 0 %define __find_requires %{nil} %define __find_provides %{nil} "; push @m, "\n%description\n%{summary}.\n"; push @m, "\n%prep\n%setup -q -n $dist-%{version}\n"; if (-e "$build_dir/Build.PL") { # see http://www.redhat.com/archives/rpm-list/2002-July/msg00110.html about RPM_BUILD_ROOT vs %{buildroot} push @m, <<'EOF'; %build %{__perl} Build.PL --installdirs=vendor --libdoc installvendorman3dir ./Build %install rm -rf $RPM_BUILD_ROOT ./Build install destdir=$RPM_BUILD_ROOT create_packlist=0 find $RPM_BUILD_ROOT -depth -type d -exec rmdir {} 2>/dev/null \; %{_fixperms} $RPM_BUILD_ROOT/* %check ./Build test EOF } elsif (-e "$build_dir/Makefile.PL") { push @m, <<'EOF'; %build %{__perl} Makefile.PL INSTALLDIRS=vendor make %{?_smp_mflags} %install rm -rf $RPM_BUILD_ROOT make pure_install DESTDIR=$RPM_BUILD_ROOT find $RPM_BUILD_ROOT -type f -name .packlist -exec rm -f {} ';' find $RPM_BUILD_ROOT -depth -type d -exec rmdir {} 2>/dev/null ';' %{_fixperms} $RPM_BUILD_ROOT/* %check make test EOF } else { $CPAN::Frontend->mydie("'$distribution' has neither a Build.PL nor a Makefile.PL\n"); } push @m, "\n%clean\nrm -rf \$RPM_BUILD_ROOT\n"; my $vendorlib = @xs ? "vendorarch" : "vendorlib"; my $date = POSIX::strftime("%a %b %d %Y", gmtime); my @doc = grep { -e "$build_dir/$_" } qw(README Changes); my $exe_stanza = "\n"; if (my $exe_files = $d->_exe_files) { if (@$exe_files) { $exe_stanza = "%{_mandir}/man1/*.1*\n"; for my $e (@$exe_files) { unless (CPAN->has_inst("File::Basename")) { $CPAN::Frontend->mydie("File::Basename not installed, cannot continue"); } my $basename = File::Basename::basename($e); $exe_stanza .= "/usr/bin/$basename\n"; } } } push @m, < - $version-1 - autogenerated by CPAN::Plugin::Specfile() EOF my $ret = join "", @m; $CPAN::Frontend->myprint($ret); my $target_dir = $self->dir || $self->dir_default; File::Path::mkpath($target_dir); my $outfile = File::Spec->catfile($target_dir, "perl-$dist.spec"); open my $specout, ">", $outfile or $CPAN::Frontend->mydie("Could not open >$outfile: $!"); print $specout $ret; $CPAN::Frontend->myprint("Wrote $outfile"); $ret; } 1; PK!z66perl5/CPAN/Debug.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- package CPAN::Debug; use strict; use vars qw($VERSION); $VERSION = "5.5001"; # module is internal to CPAN.pm %CPAN::DEBUG = qw[ CPAN 1 Index 2 InfoObj 4 Author 8 Distribution 16 Bundle 32 Module 64 CacheMgr 128 Complete 256 FTP 512 Shell 1024 Eval 2048 HandleConfig 4096 Tarzip 8192 Version 16384 Queue 32768 FirstTime 65536 ]; $CPAN::DEBUG ||= 0; #-> sub CPAN::Debug::debug ; sub debug { my($self,$arg) = @_; my @caller; my $i = 0; while () { my(@c) = (caller($i))[0 .. ($i ? 3 : 2)]; last unless defined $c[0]; push @caller, \@c; for (0,3) { last if $_ > $#c; $c[$_] =~ s/.*:://; } for (1) { $c[$_] =~ s|.*/||; } last if ++$i>=3; } pop @caller; if ($CPAN::DEBUG{$caller[0][0]} & $CPAN::DEBUG) { if ($arg and ref $arg) { eval { require Data::Dumper }; if ($@) { $CPAN::Frontend->myprint("Debug(\n" . $arg->as_string . ")\n"); } else { $CPAN::Frontend->myprint("Debug(\n" . Data::Dumper::Dumper($arg) . ")\n"); } } else { my $outer = ""; local $" = ","; if (@caller>1) { $outer = ",[@{$caller[1]}]"; } $CPAN::Frontend->myprint("Debug(@{$caller[0]}$outer): $arg\n"); } } } 1; __END__ =head1 NAME CPAN::Debug - internal debugging for CPAN.pm =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!Ʈޒw^w^perl5/CPAN/HandleConfig.pmnu6$package CPAN::HandleConfig; use strict; use vars qw(%can %keys $loading $VERSION); use File::Path (); use File::Spec (); use File::Basename (); use Carp (); =head1 NAME CPAN::HandleConfig - internal configuration handling for CPAN.pm =cut $VERSION = "5.5012"; # see also CPAN::Config::VERSION at end of file %can = ( commit => "Commit changes to disk", defaults => "Reload defaults from disk", help => "Short help about 'o conf' usage", init => "Interactive setting of all options", ); # Q: where is the "How do I add a new config option" HOWTO? # A1: svn diff -r 757:758 # where dagolden added test_report [git e997b71de88f1019a1472fc13cb97b1b7f96610f] # A2: svn diff -r 985:986 # where andk added yaml_module [git 312b6d9b12b1bdec0b6e282d853482145475021f] # A3: 1. add new config option to %keys below # 2. add a Pod description in CPAN::FirstTime in the DESCRIPTION # section; it should include a prompt line; see others for # examples # 3. add a "matcher" section in CPAN::FirstTime::init that includes # a prompt function; see others for examples # 4. add config option to documentation section in CPAN.pm %keys = map { $_ => undef } ( "allow_installing_module_downgrades", "allow_installing_outdated_dists", "applypatch", "auto_commit", "build_cache", "build_dir", "build_dir_reuse", "build_requires_install_policy", "bzip2", "cache_metadata", "check_sigs", "cleanup_after_install", "colorize_debug", "colorize_output", "colorize_print", "colorize_warn", "commandnumber_in_prompt", "commands_quote", "connect_to_internet_ok", "cpan_home", "curl", "dontload_hash", # deprecated after 1.83_68 (rev. 581) "dontload_list", "ftp", "ftp_passive", "ftp_proxy", "ftpstats_size", "ftpstats_period", "getcwd", "gpg", "gzip", "halt_on_failure", "histfile", "histsize", "http_proxy", "inactivity_timeout", "index_expire", "inhibit_startup_message", "keep_source_where", "load_module_verbosity", "lynx", "make", "make_arg", "make_install_arg", "make_install_make_command", "makepl_arg", "mbuild_arg", "mbuild_install_arg", "mbuild_install_build_command", "mbuildpl_arg", "ncftp", "ncftpget", "no_proxy", "pager", "password", "patch", "patches_dir", "perl5lib_verbosity", "plugin_list", "prefer_external_tar", "prefer_installer", "prefs_dir", "prerequisites_policy", "proxy_pass", "proxy_user", "pushy_https", "randomize_urllist", "recommends_policy", "scan_cache", "shell", "show_unparsable_versions", "show_upload_date", "show_zero_versions", "suggests_policy", "tar", "tar_verbosity", "term_is_latin", "term_ornaments", "test_report", "trust_test_report_history", "unzip", "urllist", "urllist_ping_verbose", "urllist_ping_external", "use_prompt_default", "use_sqlite", "username", "version_timeout", "wait_list", "wget", "yaml_load_code", "yaml_module", ); my %prefssupport = map { $_ => 1 } ( "allow_installing_module_downgrades", "allow_installing_outdated_dists", "build_requires_install_policy", "check_sigs", "make", "make_install_make_command", "prefer_installer", "test_report", ); # returns true on successful action sub edit { my($self,@args) = @_; return unless @args; CPAN->debug("self[$self]args[".join(" | ",@args)."]"); my($o,$str,$func,$args,$key_exists); $o = shift @args; if($can{$o}) { my $success = $self->$o(args => \@args); # o conf init => sub init => sub load unless ($success) { die "Panic: could not configure CPAN.pm for args [@args]. Giving up."; } } else { CPAN->debug("o[$o]") if $CPAN::DEBUG; unless (exists $keys{$o}) { $CPAN::Frontend->mywarn("Warning: unknown configuration variable '$o'\n"); } my $changed; # one day I used randomize_urllist for a boolean, so we must # list them explicitly --ak if (0) { } elsif ($o =~ /^(wait_list|urllist|dontload_list|plugin_list)$/) { # # ARRAYS # $func = shift @args; $func ||= ""; CPAN->debug("func[$func]args[@args]") if $CPAN::DEBUG; # Let's avoid eval, it's easier to comprehend without. if ($func eq "push") { push @{$CPAN::Config->{$o}}, @args; $changed = 1; } elsif ($func eq "pop") { pop @{$CPAN::Config->{$o}}; $changed = 1; } elsif ($func eq "shift") { shift @{$CPAN::Config->{$o}}; $changed = 1; } elsif ($func eq "unshift") { unshift @{$CPAN::Config->{$o}}, @args; $changed = 1; } elsif ($func eq "splice") { my $offset = shift @args || 0; my $length = shift @args || 0; splice @{$CPAN::Config->{$o}}, $offset, $length, @args; # may warn $changed = 1; } elsif ($func) { $CPAN::Config->{$o} = [$func, @args]; $changed = 1; } else { $self->prettyprint($o); } if ($changed) { if ($o eq "urllist") { # reset the cached values undef $CPAN::FTP::Thesite; undef $CPAN::FTP::Themethod; $CPAN::Index::LAST_TIME = 0; } elsif ($o eq "dontload_list") { # empty it, it will be built up again $CPAN::META->{dontload_hash} = {}; } } } elsif ($o =~ /_hash$/) { # # HASHES # if (@args==1 && $args[0] eq "") { @args = (); } elsif (@args % 2) { push @args, ""; } $CPAN::Config->{$o} = { @args }; $changed = 1; } else { # # SCALARS # if (defined $args[0]) { $CPAN::CONFIG_DIRTY = 1; $CPAN::Config->{$o} = $args[0]; $changed = 1; } $self->prettyprint($o) if exists $keys{$o} or defined $CPAN::Config->{$o}; } if ($changed) { if ($CPAN::Config->{auto_commit}) { $self->commit; } else { $CPAN::CONFIG_DIRTY = 1; $CPAN::Frontend->myprint("Please use 'o conf commit' to ". "make the config permanent!\n\n"); } } } } sub prettyprint { my($self,$k) = @_; my $v = $CPAN::Config->{$k}; if (ref $v) { my(@report); if (ref $v eq "ARRAY") { @report = map {"\t$_ \[$v->[$_]]\n"} 0..$#$v; } else { @report = map { sprintf "\t%-18s => %s\n", "[$_]", defined $v->{$_} ? "[$v->{$_}]" : "undef" } sort keys %$v; } $CPAN::Frontend->myprint( join( "", sprintf( " %-18s\n", $k ), @report ) ); } elsif (defined $v) { $CPAN::Frontend->myprint(sprintf " %-18s [%s]\n", $k, $v); } else { $CPAN::Frontend->myprint(sprintf " %-18s undef\n", $k); } } # generally, this should be called without arguments so that the currently # loaded config file is where changes are committed. sub commit { my($self,@args) = @_; CPAN->debug("args[@args]") if $CPAN::DEBUG; if ($CPAN::RUN_DEGRADED) { $CPAN::Frontend->mydie( "'o conf commit' disabled in ". "degraded mode. Maybe try\n". " !undef \$CPAN::RUN_DEGRADED\n" ); } my ($configpm, $must_reload); # XXX does anything do this? can it be simplified? -- dagolden, 2011-01-19 if (@args) { if ($args[0] eq "args") { # we have not signed that contract } else { $configpm = $args[0]; } } # use provided name or the current config or create a new MyConfig $configpm ||= require_myconfig_or_config() || make_new_config(); # commit to MyConfig if we can't write to Config if ( ! -w $configpm && $configpm =~ m{CPAN/Config\.pm} ) { my $myconfig = _new_config_name(); $CPAN::Frontend->mywarn( "Your $configpm file\n". "is not writable. I will attempt to write your configuration to\n" . "$myconfig instead.\n\n" ); $configpm = make_new_config(); $must_reload++; # so it gets loaded as $INC{'CPAN/MyConfig.pm'} } # XXX why not just "-w $configpm"? -- dagolden, 2011-01-19 my($mode); if (-f $configpm) { $mode = (stat $configpm)[2]; if ($mode && ! -w _) { _die_cant_write_config($configpm); } } $self->_write_config_file($configpm); require_myconfig_or_config() if $must_reload; #$mode = 0444 | ( $mode & 0111 ? 0111 : 0 ); #chmod $mode, $configpm; ###why was that so? $self->defaults; $CPAN::Frontend->myprint("commit: wrote '$configpm'\n"); $CPAN::CONFIG_DIRTY = 0; 1; } sub _write_config_file { my ($self, $configpm) = @_; my $msg; $msg = <new; rename $configpm, "$configpm~" if -f $configpm; open $fh, ">$configpm" or $CPAN::Frontend->mydie("Couldn't open >$configpm: $!"); $fh->print(qq[$msg\$CPAN::Config = \{\n]); foreach (sort keys %$CPAN::Config) { unless (exists $keys{$_}) { # do not drop them: forward compatibility! $CPAN::Frontend->mywarn("Unknown config variable '$_'\n"); next; } $fh->print( " '$_' => ", $self->neatvalue($CPAN::Config->{$_}), ",\n" ); } $fh->print("};\n1;\n__END__\n"); close $fh; return; } # stolen from MakeMaker; not taking the original because it is buggy; # bugreport will have to say: keys of hashes remain unquoted and can # produce syntax errors sub neatvalue { my($self, $v) = @_; return "undef" unless defined $v; my($t) = ref $v; unless ($t) { $v =~ s/\\/\\\\/g; return "q[$v]"; } if ($t eq 'ARRAY') { my(@m, @neat); push @m, "["; foreach my $elem (@$v) { push @neat, "q[$elem]"; } push @m, join ", ", @neat; push @m, "]"; return join "", @m; } return "$v" unless $t eq 'HASH'; my @m; foreach my $key (sort keys %$v) { my $val = $v->{$key}; push(@m,"q[$key]=>".$self->neatvalue($val)) ; } return "{ ".join(', ',@m)." }"; } sub defaults { my($self) = @_; if ($CPAN::RUN_DEGRADED) { $CPAN::Frontend->mydie( "'o conf defaults' disabled in ". "degraded mode. Maybe try\n". " !undef \$CPAN::RUN_DEGRADED\n" ); } my $done; for my $config (qw(CPAN/MyConfig.pm CPAN/Config.pm)) { if ($INC{$config}) { CPAN->debug("INC{'$config'}[$INC{$config}]") if $CPAN::DEBUG; CPAN::Shell->_reload_this($config,{reloforce => 1}); $CPAN::Frontend->myprint("'$INC{$config}' reread\n"); last; } } $CPAN::CONFIG_DIRTY = 0; 1; } =head2 C<< CLASS->safe_quote ITEM >> Quotes an item to become safe against spaces in shell interpolation. An item is enclosed in double quotes if: - the item contains spaces in the middle - the item does not start with a quote This happens to avoid shell interpolation problems when whitespace is present in directory names. This method uses C to determine the correct quote. If C is a space, no quoting will take place. if it starts and ends with the same quote character: leave it as it is if it contains no whitespace: leave it as it is if it contains whitespace, then if it contains quotes: better leave it as it is else: quote it with the correct quote type for the box we're on =cut { # Instead of patching the guess, set commands_quote # to the right value my ($quotes,$use_quote) = $^O eq 'MSWin32' ? ('"', '"') : (q{"'}, "'") ; sub safe_quote { my ($self, $command) = @_; # Set up quote/default quote my $quote = $CPAN::Config->{commands_quote} || $quotes; if ($quote ne ' ' and defined($command ) and $command =~ /\s/ and $command !~ /[$quote]/) { return qq<$use_quote$command$use_quote> } return $command; } } sub init { my($self,@args) = @_; CPAN->debug("self[$self]args[".join(",",@args)."]"); $self->load(do_init => 1, @args); 1; } # Loads CPAN::MyConfig or fall-back to CPAN::Config. Will not reload a file # if already loaded. Returns the path to the file %INC or else the empty string # # Note -- if CPAN::Config were loaded and CPAN::MyConfig subsequently # created, calling this again will leave *both* in %INC sub require_myconfig_or_config () { if ( $INC{"CPAN/MyConfig.pm"} || _try_loading("CPAN::MyConfig", cpan_home())) { return $INC{"CPAN/MyConfig.pm"}; } elsif ( $INC{"CPAN/Config.pm"} || _try_loading("CPAN::Config") ) { return $INC{"CPAN/Config.pm"}; } else { return q{}; } } # Load a module, but ignore "can't locate..." errors # Optionally take a list of directories to add to @INC for the load sub _try_loading { my ($module, @dirs) = @_; (my $file = $module) =~ s{::}{/}g; $file .= ".pm"; local @INC = @INC; for my $dir ( @dirs ) { if ( -f File::Spec->catfile($dir, $file) ) { unshift @INC, $dir; last; } } eval { require $file }; my $err_myconfig = $@; if ($err_myconfig and $err_myconfig !~ m#locate \Q$file\E#) { die "Error while requiring ${module}:\n$err_myconfig"; } return $INC{$file}; } # prioritized list of possible places for finding "CPAN/MyConfig.pm" sub cpan_home_dir_candidates { my @dirs; my $old_v = $CPAN::Config->{load_module_verbosity}; $CPAN::Config->{load_module_verbosity} = q[none]; if ($CPAN::META->has_usable('File::HomeDir')) { if ($^O ne 'darwin') { push @dirs, File::HomeDir->my_data; # my_data is ~/Library/Application Support on darwin, # which causes issues in the toolchain. } push @dirs, File::HomeDir->my_home; } # Windows might not have HOME, so check it first push @dirs, $ENV{HOME} if $ENV{HOME}; # Windows might have these instead push( @dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') ) if $ENV{HOMEDRIVE} && $ENV{HOMEPATH}; push @dirs, $ENV{USERPROFILE} if $ENV{USERPROFILE}; $CPAN::Config->{load_module_verbosity} = $old_v; my $dotcpan = $^O eq 'VMS' ? '_cpan' : '.cpan'; @dirs = map { File::Spec->catdir($_, $dotcpan) } grep { defined } @dirs; return wantarray ? @dirs : $dirs[0]; } sub load { my($self, %args) = @_; $CPAN::Be_Silent+=0; # protect against 'used only once' $CPAN::Be_Silent++ if $args{be_silent}; # do not use; planned to be removed in 2011 my $do_init = delete $args{do_init} || 0; my $make_myconfig = delete $args{make_myconfig}; $loading = 0 unless defined $loading; my $configpm = require_myconfig_or_config; my @miss = $self->missing_config_data; CPAN->debug("do_init[$do_init]loading[$loading]miss[@miss]") if $CPAN::DEBUG; return unless $do_init || @miss; if (@miss==1 and $miss[0] eq "pushy_https" && !$do_init) { $CPAN::Frontend->myprint(<<'END'); Starting with version 2.29 of the cpan shell, a new download mechanism is the default which exclusively uses cpan.org as the host to download from. The configuration variable pushy_https can be used to (de)select the new mechanism. Please read more about it and make your choice between the old and the new mechanism by running o conf init pushy_https Once you have done that and stored the config variable this dialog will disappear. END return; } # I'm not how we'd ever wind up in a recursive loop, but I'm leaving # this here for safety's sake -- dagolden, 2011-01-19 return if $loading; local $loading = ($loading||0) + 1; # Warn if we have a config file, but things were found missing if ($configpm && @miss && !$do_init) { if ($make_myconfig || ( ! -w $configpm && $configpm =~ m{CPAN/Config\.pm})) { $configpm = make_new_config(); $CPAN::Frontend->myprint(<> END } else { $CPAN::Frontend->myprint(<> END } } require CPAN::FirstTime; return CPAN::FirstTime::init($configpm || make_new_config(), %args); } # Creates a new, empty config file at the preferred location # Any existing will be renamed with a ".bak" suffix if possible # If the file cannot be created, an exception is thrown sub make_new_config { my $configpm = _new_config_name(); my $configpmdir = File::Basename::dirname( $configpm ); File::Path::mkpath($configpmdir) unless -d $configpmdir; if ( -w $configpmdir ) { #_#_# following code dumped core on me with 5.003_11, a.k. if( -f $configpm ) { my $configpm_bak = "$configpm.bak"; unlink $configpm_bak if -f $configpm_bak; if( rename $configpm, $configpm_bak ) { $CPAN::Frontend->mywarn(<new; if ($fh->open(">$configpm")) { $fh->print("1;\n"); return $configpm; } } _die_cant_write_config($configpm); } sub _die_cant_write_config { my ($configpm) = @_; $CPAN::Frontend->mydie(<<"END"); WARNING: CPAN.pm is unable to write a configuration file. You must be able to create and write to '$configpm'. Aborting configuration. END } # From candidate directories, we would like (in descending preference order): # * the one that contains a MyConfig file # * one that exists (even without MyConfig) # * the first one on the list sub cpan_home { my @dirs = cpan_home_dir_candidates(); for my $d (@dirs) { return $d if -f "$d/CPAN/MyConfig.pm"; } for my $d (@dirs) { return $d if -d $d; } return $dirs[0]; } sub _new_config_name { return File::Spec->catfile(cpan_home(), 'CPAN', 'MyConfig.pm'); } # returns mandatory but missing entries in the Config sub missing_config_data { my(@miss); for ( "auto_commit", "build_cache", "build_dir", "cache_metadata", "cpan_home", "ftp_proxy", #"gzip", "http_proxy", "index_expire", #"inhibit_startup_message", "keep_source_where", #"make", "make_arg", "make_install_arg", "makepl_arg", "mbuild_arg", "mbuild_install_arg", ($^O eq "MSWin32" ? "" : "mbuild_install_build_command"), "mbuildpl_arg", "no_proxy", #"pager", "prerequisites_policy", "pushy_https", "scan_cache", #"tar", #"unzip", "urllist", ) { next unless exists $keys{$_}; push @miss, $_ unless defined $CPAN::Config->{$_}; } return @miss; } sub help { $CPAN::Frontend->myprint(q[ Known options: commit commit session changes to disk defaults reload default config values from disk help this help init enter a dialog to set all or a set of parameters Edit key values as in the following (the "o" is a literal letter o): o conf build_cache 15 o conf build_dir "/foo/bar" o conf urllist shift o conf urllist unshift ftp://ftp.foo.bar/ o conf inhibit_startup_message 1 ]); 1; #don't reprint CPAN::Config } sub cpl { my($word,$line,$pos) = @_; $word ||= ""; CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG; my(@words) = split " ", substr($line,0,$pos+1); if ( defined($words[2]) and $words[2] =~ /list$/ and ( @words == 3 || @words == 4 && length($word) ) ) { return grep /^\Q$word\E/, qw(splice shift unshift pop push); } elsif (defined($words[2]) and $words[2] eq "init" and ( @words == 3 || @words >= 4 && length($word) )) { return sort grep /^\Q$word\E/, keys %keys; } elsif (@words >= 4) { return (); } my %seen; my(@o_conf) = sort grep { !$seen{$_}++ } keys %can, keys %$CPAN::Config, keys %keys; return grep /^\Q$word\E/, @o_conf; } sub prefs_lookup { my($self,$distro,$what) = @_; if ($prefssupport{$what}) { return $CPAN::Config->{$what} unless $distro and $distro->prefs and $distro->prefs->{cpanconfig} and defined $distro->prefs->{cpanconfig}{$what}; return $distro->prefs->{cpanconfig}{$what}; } else { $CPAN::Frontend->mywarn("Warning: $what not yet officially ". "supported for distroprefs, doing a normal lookup\n"); return $CPAN::Config->{$what}; } } { package CPAN::Config; ####::###### #hide from indexer # note: J. Nick Koston wrote me that they are using # CPAN::Config->commit although undocumented. I suggested # CPAN::Shell->o("conf","commit") even when ugly it is at least # documented # that's why I added the CPAN::Config class with autoload and # deprecated warning use strict; use vars qw($AUTOLOAD $VERSION); $VERSION = "5.5012"; # formerly CPAN::HandleConfig was known as CPAN::Config sub AUTOLOAD { ## no critic my $class = shift; # e.g. in dh-make-perl: CPAN::Config my($l) = $AUTOLOAD; $CPAN::Frontend->mywarn("Dispatching deprecated method '$l' to CPAN::HandleConfig\n"); $l =~ s/.*:://; CPAN::HandleConfig->$l(@_); } } 1; __END__ =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut # Local Variables: # mode: cperl # cperl-indent-level: 4 # End: # vim: ts=4 sts=4 sw=4: PK!n3y..perl5/CPAN/Version.pmnu6$package CPAN::Version; use strict; use vars qw($VERSION); $VERSION = "5.5003"; # CPAN::Version::vcmp courtesy Jost Krieger sub vcmp { my($self,$l,$r) = @_; local($^W) = 0; CPAN->debug("l[$l] r[$r]") if $CPAN::DEBUG; # treat undef as zero $l = 0 if $l eq 'undef'; $r = 0 if $r eq 'undef'; return 0 if $l eq $r; # short circuit for quicker success for ($l,$r) { s/_//g; } CPAN->debug("l[$l] r[$r]") if $CPAN::DEBUG; for ($l,$r) { next unless tr/.// > 1 || /^v/; s/^v?/v/; 1 while s/\.0+(\d)/.$1/; # remove leading zeroes per group } CPAN->debug("l[$l] r[$r]") if $CPAN::DEBUG; if ($l=~/^v/ <=> $r=~/^v/) { for ($l,$r) { next if /^v/; $_ = $self->float2vv($_); } } CPAN->debug("l[$l] r[$r]") if $CPAN::DEBUG; my $lvstring = "v0"; my $rvstring = "v0"; if ($] >= 5.006 && $l =~ /^v/ && $r =~ /^v/) { $lvstring = $self->vstring($l); $rvstring = $self->vstring($r); CPAN->debug(sprintf "lv[%vd] rv[%vd]", $lvstring, $rvstring) if $CPAN::DEBUG; } return ( ($l ne "undef") <=> ($r ne "undef") || $lvstring cmp $rvstring || $l <=> $r || $l cmp $r ); } sub vgt { my($self,$l,$r) = @_; $self->vcmp($l,$r) > 0; } sub vlt { my($self,$l,$r) = @_; $self->vcmp($l,$r) < 0; } sub vge { my($self,$l,$r) = @_; $self->vcmp($l,$r) >= 0; } sub vle { my($self,$l,$r) = @_; $self->vcmp($l,$r) <= 0; } sub vstring { my($self,$n) = @_; $n =~ s/^v// or die "CPAN::Version::vstring() called with invalid arg [$n]"; pack "U*", split /\./, $n; } # vv => visible vstring sub float2vv { my($self,$n) = @_; my($rev) = int($n); $rev ||= 0; my($mantissa) = $n =~ /\.(\d{1,12})/; # limit to 12 digits to limit # architecture influence $mantissa ||= 0; $mantissa .= "0" while length($mantissa)%3; my $ret = "v" . $rev; while ($mantissa) { $mantissa =~ s/(\d{1,3})// or die "Panic: length>0 but not a digit? mantissa[$mantissa]"; $ret .= ".".int($1); } # warn "n[$n]ret[$ret]"; $ret =~ s/(\.0)+/.0/; # v1.0.0 => v1.0 $ret; } sub readable { my($self,$n) = @_; $n =~ /^([\w\-\+\.]+)/; return $1 if defined $1 && length($1)>0; # if the first user reaches version v43, he will be treated as "+". # We'll have to decide about a new rule here then, depending on what # will be the prevailing versioning behavior then. if ($] < 5.006) { # or whenever v-strings were introduced # we get them wrong anyway, whatever we do, because 5.005 will # have already interpreted 0.2.4 to be "0.24". So even if he # indexer sends us something like "v0.2.4" we compare wrongly. # And if they say v1.2, then the old perl takes it as "v12" if (defined $CPAN::Frontend) { $CPAN::Frontend->mywarn("Suspicious version string seen [$n]\n"); } else { warn("Suspicious version string seen [$n]\n"); } return $n; } my $better = sprintf "v%vd", $n; CPAN->debug("n[$n] better[$better]") if $CPAN::DEBUG; return $better; } 1; __END__ =head1 NAME CPAN::Version - utility functions to compare CPAN versions =head1 SYNOPSIS use CPAN::Version; CPAN::Version->vgt("1.1","1.1.1"); # 1 bc. 1.1 > 1.001001 CPAN::Version->vlt("1.1","1.1"); # 0 bc. 1.1 not < 1.1 CPAN::Version->vcmp("1.1","1.1.1"); # 1 bc. first is larger CPAN::Version->vcmp("1.1.1","1.1"); # -1 bc. first is smaller CPAN::Version->readable(v1.2.3); # "v1.2.3" CPAN::Version->vstring("v1.2.3"); # v1.2.3 CPAN::Version->float2vv(1.002003); # "v1.2.3" =head1 DESCRIPTION This module mediates between some version that perl sees in a package and the version that is published by the CPAN indexer. It's only written as a helper module for both CPAN.pm and CPANPLUS.pm. As it stands it predates version.pm but has the same goal: make version strings visible and comparable. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut # Local Variables: # mode: cperl # cperl-indent-level: 4 # End: PK!Booperl5/CPAN/Admin.pmnu6$package CPAN::Admin; use base CPAN; use CPAN; # old base.pm did not load CPAN on previous line use strict; use vars qw(@EXPORT $VERSION); use constant PAUSE_IP => "pause.perl.org"; @EXPORT = qw(shell); $VERSION = "5.501"; push @CPAN::Complete::COMMANDS, qw(register modsearch); $CPAN::Shell::COLOR_REGISTERED = 1; sub shell { CPAN::shell($_[0]||"admin's cpan> ",$_[1]); } sub CPAN::Shell::register { my($self,$mod,@rest) = @_; unless ($mod) { print "register called without argument\n"; return; } if ($CPAN::META->has_inst("URI::Escape")) { require URI::Escape; } else { print "register requires URI::Escape installed, otherwise it cannot work\n"; return; } print "Got request for mod[$mod]\n"; if (@rest) { my $modline = join " ", $mod, @rest; print "Sending to PAUSE [$modline]\n"; my $emodline = URI::Escape::uri_escape($modline, '^\w '); $emodline =~ s/ /+/g; my $url = sprintf("https://%s/pause/authenquery?pause99_add_mod_modid=". "%s;SUBMIT_pause99_add_mod_hint=hint", PAUSE_IP, $emodline, ); print "url[$url]\n\n"; print ">>>>Trying to open a netscape window<<<<\n"; sleep 1; system("netscape","-remote","openURL($url)"); return; } my $m = CPAN::Shell->expand("Module",$mod); unless (ref $m) { print "Could not determine the object for $mod\n"; return; } my $id = $m->id; print "Found module id[$id] in database\n"; if (exists $m->{RO} && $m->{RO}{chapterid}) { print "$id is already registered\n"; return; } my(@namespace) = split /::/, $id; my $rootns = $namespace[0]; # Tk, XML and Apache need special treatment if ($rootns=~/^(Bundle)\b/) { print "Bundles are not yet ready for registering\n"; return; } # make a good suggestion for the chapter my(@simile) = CPAN::Shell->expand("Module","/^$rootns(:|\$)/"); print "Found within this namespace ", join(", ", map { $_->id } @simile), "\n"; my(%seench); for my $ch (map { exists $_->{RO} ? $_->{RO}{chapterid} : ""} @simile) { next unless $ch; $seench{$ch}=undef; } my(@seench) = sort grep {length($_)} keys %seench; my $reco_ch = ""; if (@seench>1) { print "Found rootnamespace[$rootns] in the chapters [", join(", ", @seench), "]\n"; $reco_ch = $seench[0]; print "Picking $reco_ch\n"; } elsif (@seench==1) { print "Found rootnamespace[$rootns] in the chapter[$seench[0]]\n"; $reco_ch = $seench[0]; } else { print "The new rootnamespace[$rootns] needs to be introduced. Oh well.\n"; } # Look closer at the dist my $d = CPAN::Shell->expand("Distribution", $m->cpan_file); printf "Module comes with dist[%s]\n", $d->id; for my $contm ($d->containsmods) { if ($CPAN::META->exists("CPAN::Module",$contm)) { my $contm_obj = CPAN::Shell->expand("Module",$contm) or next; my $is_reg = exists $contm_obj->{RO} && $contm_obj->{RO}{description}; printf(" in same dist: %s%s\n", $contm, $is_reg ? " already in modulelist" : "", ); } } # get it so that m is better and we can inspect for XS CPAN::Shell->get($id); CPAN::Shell->m($id); CPAN::Shell->d($d->id); my $has_xs = 0; { my($mani,@mani); local $/ = "\n"; open $mani, "$d->{build_dir}/MANIFEST" and @mani = <$mani>; my @xs = grep /\.xs\b/, @mani; if (@xs) { print "Found XS files: @xs"; $has_xs=1; } } my $emodid = URI::Escape::uri_escape($id, '\W'); my $ech = $reco_ch; $ech =~ s/ /+/g; my $description = $m->{MANPAGE} || ""; $description =~ s/[A-Z]//; # POD $description =~ s/^\Q$id\E//; # usually this line starts with the modid $description =~ s/^[ \-]+//; # leading spaces and dashes substr($description,44) = "" if length($description)>44; $description = ucfirst($description); my $edescription = URI::Escape::uri_escape($description, '^\w '); $edescription =~ s/ /+/g; my $url = sprintf("https://%s/pause/authenquery?pause99_add_mod_modid=". "%s;pause99_add_mod_chapterid=%s;pause99_add_mod_statd=%s;". "pause99_add_mod_stats=%s;pause99_add_mod_statl=%s;". "pause99_add_mod_stati=%s;pause99_add_mod_description=%s;". "pause99_add_mod_userid=%s;SUBMIT_pause99_add_mod_preview=preview", PAUSE_IP, $emodid, $ech, "R", "d", $has_xs ? "c" : "p", "O", $edescription, $m->{RO}{CPAN_USERID}, ); print "$url\n\n"; print ">>>>Trying to open a netscape window<<<<\n"; system("netscape","-remote","openURL($url)"); } sub CPAN::Shell::modsearch { my($self,@line) = @_; unless (@line) { print "modsearch called without argument\n"; return; } my $request = join " ", @line; print "Got request[$request]\n"; my $erequest = URI::Escape::uri_escape($request, '^\w '); $erequest =~ s/ /+/g; my $url = sprintf("http://www.xray.mpe.mpg.de/cgi-bin/w3glimpse/modules?query=%s". "&errors=0&case=on&maxfiles=100&maxlines=30", $erequest, ); print "$url\n\n"; print ">>>>Trying to open a netscape window<<<<\n"; system("netscape","-remote","openURL('$url')"); } 1; __END__ =head1 NAME CPAN::Admin - A CPAN Shell for CPAN admins =head1 SYNOPSIS perl -MCPAN::Admin -e shell =head1 STATUS Note: this module is currently not maintained. If you need it and fix it for your needs, please submit patches. =head1 DESCRIPTION CPAN::Admin is a subclass of CPAN that adds the commands C and C to the CPAN shell. C calls C on the named module, assembles a couple of informations (description, language), and calls Netscape with the -remote argument so that a form is filled with all the assembled informations and the registration can be performed with a single click. If the command line has more than one argument, register does not run a C, instead it interprets the rest of the line as DSLI status, description, and userid and sends them to netscape such that the form is again mostly filled and can be edited or confirmed with a single click. CPAN::Admin never performs the submission click for you, it is only intended to fill in the form on PAUSE and leave the confirmation to you. C simply passes the arguments to the search engine for the modules@perl.org mailing list at L where all registration requests are stored. It does so in the same way as register, namely with the C command. An experimental feature has also been added, namely to color already registered modules in listings. If you have L installed, the u, r, and m commands will show already registered modules in green. =head1 PREREQUISITES L, a browser available in the path, the browser must understand the -remote switch (as far as I know, this is only available on UNIX); coloring of registered modules is only available if L is installed. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!$d d perl5/CPAN/Kwalify.pmnu6$=head1 NAME CPAN::Kwalify - Interface between CPAN.pm and Kwalify.pm =head1 SYNOPSIS use CPAN::Kwalify; validate($schema_name, $data, $file, $doc); =head1 DESCRIPTION =over =item _validate($schema_name, $data, $file, $doc) $schema_name is the name of a supported schema. Currently only C is supported. $data is the data to be validated. $file is the absolute path to the file the data are coming from. $doc is the index of the document within $doc that is to be validated. The last two arguments are only there for better error reporting. Relies on being called from within CPAN.pm. Dies if something fails. Does not return anything useful. =item yaml($schema_name) Returns the YAML text of that schema. Dies if something fails. =back =head1 AUTHOR Andreas Koenig C<< >> =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 use strict; package CPAN::Kwalify; use vars qw($VERSION $VAR1); $VERSION = "5.50"; use File::Spec (); my %vcache = (); my $schema_loaded = {}; sub _validate { my($schema_name,$data,$abs,$y) = @_; my $yaml_module = CPAN->_yaml_module; if ( $CPAN::META->has_inst($yaml_module) && $CPAN::META->has_inst("Kwalify") ) { my $load = UNIVERSAL::can($yaml_module,"Load"); unless ($schema_loaded->{$schema_name}) { eval { my $schema_yaml = yaml($schema_name); $schema_loaded->{$schema_name} = $load->($schema_yaml); }; if ($@) { # we know that YAML.pm 0.62 cannot parse the schema, # so we try a fallback my $content = do { my $path = __FILE__; $path =~ s/\.pm$//; $path = File::Spec->catfile($path, "$schema_name.dd"); local *FH; open FH, $path or die "Could not open '$path': $!"; local $/; ; }; $VAR1 = undef; eval $content; if (my $err = $@) { die "parsing of '$schema_name.dd' failed: $err"; } $schema_loaded->{$schema_name} = $VAR1; } } } if (my $schema = $schema_loaded->{$schema_name}) { my $mtime = (stat $abs)[9]; for my $k (keys %{$vcache{$abs}}) { delete $vcache{$abs}{$k} unless $k eq $mtime; } return if $vcache{$abs}{$mtime}{$y}++; eval { Kwalify::validate($schema, $data) }; if (my $err = $@) { my $info = {}; yaml($schema_name, info => $info); die "validation of distropref '$abs'[$y] against schema '$info->{path}' failed: $err"; } } } sub _clear_cache { %vcache = (); } sub yaml { my($schema_name, %opt) = @_; my $content = do { my $path = __FILE__; $path =~ s/\.pm$//; $path = File::Spec->catfile($path, "$schema_name.yml"); if ($opt{info}) { $opt{info}{path} = $path; } local *FH; open FH, $path or die "Could not open '$path': $!"; local $/; ; }; return $content; } 1; # Local Variables: # mode: cperl # cperl-indent-level: 4 # End: PK!ך9LLperl5/CPAN/URL.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::URL; use overload '""' => "as_string", fallback => 1; # accessors: TEXT(the url string), FROM(DEF=>defaultlist,USER=>urllist), # planned are things like age or quality use vars qw( $VERSION ); $VERSION = "5.5"; sub new { my($class,%args) = @_; bless { %args }, $class; } sub as_string { my($self) = @_; $self->text; } sub text { my($self,$set) = @_; if (defined $set) { $self->{TEXT} = $set; } $self->{TEXT}; } 1; PK!Чperl5/CPAN/InfoObj.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::InfoObj; use strict; use CPAN::Debug; @CPAN::InfoObj::ISA = qw(CPAN::Debug); use Cwd qw(chdir); use vars qw( $VERSION ); $VERSION = "5.5"; sub ro { my $self = shift; exists $self->{RO} and return $self->{RO}; } #-> sub CPAN::InfoObj::cpan_userid sub cpan_userid { my $self = shift; my $ro = $self->ro; if ($ro) { return $ro->{CPAN_USERID} || "N/A"; } else { $self->debug("ID[$self->{ID}]"); # N/A for bundles found locally return "N/A"; } } sub id { shift->{ID}; } #-> sub CPAN::InfoObj::new ; sub new { my $this = bless {}, shift; %$this = @_; $this } # The set method may only be used by code that reads index data or # otherwise "objective" data from the outside world. All session # related material may do anything else with instance variables but # must not touch the hash under the RO attribute. The reason is that # the RO hash gets written to Metadata file and is thus persistent. #-> sub CPAN::InfoObj::safe_chdir ; sub safe_chdir { my($self,$todir) = @_; # we die if we cannot chdir and we are debuggable Carp::confess("safe_chdir called without todir argument") unless defined $todir and length $todir; if (chdir $todir) { $self->debug(sprintf "changed directory to %s", CPAN::anycwd()) if $CPAN::DEBUG; } else { if (-e $todir) { unless (-x $todir) { unless (chmod 0755, $todir) { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mywarn("I have neither the -x permission nor the ". "permission to change the permission; cannot ". "chdir to '$todir'\n"); $CPAN::Frontend->mysleep(5); $CPAN::Frontend->mydie(qq{Could not chdir from cwd[$cwd] }. qq{to todir[$todir]: $!}); } } } else { $CPAN::Frontend->mydie("Directory '$todir' has gone. Cannot continue.\n"); } if (chdir $todir) { $self->debug(sprintf "changed directory to %s", CPAN::anycwd()) if $CPAN::DEBUG; } else { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mydie(qq{Could not chdir from cwd[$cwd] }. qq{to todir[$todir] (a chmod has been issued): $!}); } } } #-> sub CPAN::InfoObj::set ; sub set { my($self,%att) = @_; my $class = ref $self; # This must be ||=, not ||, because only if we write an empty # reference, only then the set method will write into the readonly # area. But for Distributions that spring into existence, maybe # because of a typo, we do not like it that they are written into # the readonly area and made permanent (at least for a while) and # that is why we do not "allow" other places to call ->set. unless ($self->id) { CPAN->debug("Bug? Empty ID, rejecting"); return; } my $ro = $self->{RO} = $CPAN::META->{readonly}{$class}{$self->id} ||= {}; while (my($k,$v) = each %att) { $ro->{$k} = $v; } } #-> sub CPAN::InfoObj::as_glimpse ; sub as_glimpse { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; my $id = $self->can("pretty_id") ? $self->pretty_id : $self->{ID}; push @m, sprintf "%-15s %s\n", $class, $id; join "", @m; } #-> sub CPAN::InfoObj::as_string ; sub as_string { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; push @m, $class, " id = $self->{ID}\n"; my $ro; unless ($ro = $self->ro) { if (substr($self->{ID},-1,1) eq ".") { # directory $ro = +{}; } else { $CPAN::Frontend->mywarn("Unknown object $self->{ID}\n"); $CPAN::Frontend->mysleep(5); return; } } for (sort keys %$ro) { # next if m/^(ID|RO)$/; my $extra = ""; if ($_ eq "CPAN_USERID") { $extra .= " ("; $extra .= $self->fullname; my $email; # old perls! if ($email = $CPAN::META->instance("CPAN::Author", $self->cpan_userid )->email) { $extra .= " <$email>"; } else { $extra .= " "; } $extra .= ")"; } elsif ($_ eq "FULLNAME") { # potential UTF-8 conversion push @m, sprintf " %-12s %s\n", $_, $self->fullname; next; } next unless defined $ro->{$_}; push @m, sprintf " %-12s %s%s\n", $_, $ro->{$_}, $extra; } KEY: for (sort keys %$self) { next if m/^(ID|RO)$/; unless (defined $self->{$_}) { delete $self->{$_}; next KEY; } if (ref($self->{$_}) eq "ARRAY") { push @m, sprintf " %-12s %s\n", $_, "@{$self->{$_}}"; } elsif (ref($self->{$_}) eq "HASH") { my $value; if (/^CONTAINSMODS$/) { $value = join(" ",sort keys %{$self->{$_}}); } elsif (/^prereq_pm$/) { my @value; my $v = $self->{$_}; for my $x (sort keys %$v) { my @svalue; for my $y (sort keys %{$v->{$x}}) { push @svalue, "$y=>$v->{$x}{$y}"; } push @value, "$x\:" . join ",", @svalue if @svalue; } $value = join ";", @value; } else { $value = $self->{$_}; } push @m, sprintf( " %-12s %s\n", $_, $value, ); } else { push @m, sprintf " %-12s %s\n", $_, $self->{$_}; } } join "", @m, "\n"; } #-> sub CPAN::InfoObj::fullname ; sub fullname { my($self) = @_; $CPAN::META->instance("CPAN::Author",$self->cpan_userid)->fullname; } #-> sub CPAN::InfoObj::dump ; sub dump { my($self, $what) = @_; unless ($CPAN::META->has_inst("Data::Dumper")) { $CPAN::Frontend->mydie("dump command requires Data::Dumper installed"); } local $Data::Dumper::Sortkeys; $Data::Dumper::Sortkeys = 1; my $out = Data::Dumper::Dumper($what ? eval $what : $self); if (length $out > 100000) { my $fh_pager = FileHandle->new; local($SIG{PIPE}) = "IGNORE"; my $pager = $CPAN::Config->{'pager'} || "cat"; $fh_pager->open("|$pager") or die "Could not open pager $pager\: $!"; $fh_pager->print($out); close $fh_pager; } else { $CPAN::Frontend->myprint($out); } } 1; PK!7Sperl5/CPAN/Author.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Author; use strict; use CPAN::InfoObj; @CPAN::Author::ISA = qw(CPAN::InfoObj); use vars qw( $VERSION ); $VERSION = "5.5002"; package CPAN::Author; use strict; #-> sub CPAN::Author::force sub force { my $self = shift; $self->{force}++; } #-> sub CPAN::Author::force sub unforce { my $self = shift; delete $self->{force}; } #-> sub CPAN::Author::id sub id { my $self = shift; my $id = $self->{ID}; $CPAN::Frontend->mydie("Illegal author id[$id]") unless $id =~ /^[A-Z]/; $id; } #-> sub CPAN::Author::as_glimpse ; sub as_glimpse { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; push @m, sprintf(qq{%-15s %s ("%s" <%s>)\n}, $class, $self->{ID}, $self->fullname, $self->email); join "", @m; } #-> sub CPAN::Author::fullname ; sub fullname { shift->ro->{FULLNAME}; } *name = \&fullname; #-> sub CPAN::Author::email ; sub email { shift->ro->{EMAIL}; } #-> sub CPAN::Author::ls ; sub ls { my $self = shift; my $glob = shift || ""; my $silent = shift || 0; my $id = $self->id; # adapted from CPAN::Distribution::verifyCHECKSUM ; my(@csf); # chksumfile @csf = $self->id =~ /(.)(.)(.*)/; $csf[1] = join "", @csf[0,1]; $csf[2] = join "", @csf[1,2]; # ("A","AN","ANDK") my(@dl); @dl = $self->dir_listing([$csf[0],"CHECKSUMS"], 0, 1); unless (grep {$_->[2] eq $csf[1]} @dl) { $CPAN::Frontend->myprint("Directory $csf[1]/ does not exist\n") unless $silent ; return; } @dl = $self->dir_listing([@csf[0,1],"CHECKSUMS"], 0, 1); unless (grep {$_->[2] eq $csf[2]} @dl) { $CPAN::Frontend->myprint("Directory $id/ does not exist\n") unless $silent; return; } @dl = $self->dir_listing([@csf,"CHECKSUMS"], 1, 1); if ($glob) { if ($CPAN::META->has_inst("Text::Glob")) { $glob =~ s|/$|/*|; my $rglob = Text::Glob::glob_to_regex($glob); CPAN->debug("glob[$glob]rglob[$rglob]dl[@dl]") if $CPAN::DEBUG; my @tmpdl = grep { $_->[2] =~ /$rglob/ } @dl; if (1==@tmpdl && $tmpdl[0][0]==0) { $rglob = Text::Glob::glob_to_regex("$glob/*"); @dl = grep { $_->[2] =~ /$rglob/ } @dl; } else { @dl = @tmpdl; } CPAN->debug("rglob[$rglob]dl[@dl]") if $CPAN::DEBUG; } else { $CPAN::Frontend->mydie("Text::Glob not installed, cannot proceed"); } } unless ($silent >= 2) { $CPAN::Frontend->myprint ( join "", map { sprintf ( "%8d %10s %s/%s%s\n", $_->[0], $_->[1], $id, $_->[2], 0==$_->[0]?"/":"", ) } sort { $a->[2] cmp $b->[2] } @dl ); } @dl; } # returns an array of arrays, the latter contain (size,mtime,filename) #-> sub CPAN::Author::dir_listing ; sub dir_listing { my $self = shift; my $chksumfile = shift; my $recursive = shift; my $may_ftp = shift; my $lc_want = File::Spec->catfile($CPAN::Config->{keep_source_where}, "authors", "id", @$chksumfile); my $fh; CPAN->debug("chksumfile[@$chksumfile]recursive[$recursive]may_ftp[$may_ftp]") if $CPAN::DEBUG; # Purge and refetch old (pre-PGP) CHECKSUMS; they are a security # hazard. (Without GPG installed they are not that much better, # though.) $fh = FileHandle->new; if (open($fh, $lc_want)) { my $line = <$fh>; close $fh; unlink($lc_want) unless $line =~ /PGP/; } local($") = "/"; # connect "force" argument with "index_expire". my $force = $self->{force}; if (my @stat = stat $lc_want) { $force ||= $stat[9] + $CPAN::Config->{index_expire}*86400 <= time; } my $lc_file; if ($may_ftp) { $lc_file = eval { CPAN::FTP->localize ( "authors/id/@$chksumfile", $lc_want, $force, ); }; unless ($lc_file) { $CPAN::Frontend->myprint("Trying $lc_want.gz\n"); $chksumfile->[-1] .= ".gz"; $lc_file = eval { CPAN::FTP->localize ("authors/id/@$chksumfile", "$lc_want.gz", 1, ); }; if ($lc_file) { $lc_file =~ s{\.gz(?!\n)\Z}{}; #}; eval{CPAN::Tarzip->new("$lc_file.gz")->gunzip($lc_file)}; } else { return; } } } else { $lc_file = $lc_want; # we *could* second-guess and if the user has a file: URL, # then we could look there. But on the other hand, if they do # have a file: URL, why did they choose to set # $CPAN::Config->{show_upload_date} to false? } # adapted from CPAN::Distribution::CHECKSUM_check_file ; $fh = FileHandle->new; my($cksum); if (open $fh, $lc_file) { local($/); my $eval = <$fh>; $eval =~ s/\015?\012/\n/g; close $fh; my($compmt) = Safe->new(); $cksum = $compmt->reval($eval); if ($@) { rename $lc_file, "$lc_file.bad"; Carp::confess($@) if $@; } } elsif ($may_ftp) { Carp::carp ("Could not open '$lc_file' for reading."); } else { # Maybe should warn: "You may want to set show_upload_date to a true value" return; } my(@result,$f); for $f (sort keys %$cksum) { if (exists $cksum->{$f}{isdir}) { if ($recursive) { my(@dir) = @$chksumfile; pop @dir; push @dir, $f, "CHECKSUMS"; push @result, [ 0, "-", $f ]; push @result, map { [$_->[0], $_->[1], "$f/$_->[2]"] } $self->dir_listing(\@dir,1,$may_ftp); } else { push @result, [ 0, "-", $f ]; } } else { push @result, [ ($cksum->{$f}{"size"}||0), $cksum->{$f}{"mtime"}||"---", $f ]; } } @result; } #-> sub CPAN::Author::reports sub reports { $CPAN::Frontend->mywarn("reports on authors not implemented. Please file a bugreport if you need this.\n"); } 1; PK!2]perl5/CPAN/Nox.pmnu6$package CPAN::Nox; use strict; use vars qw($VERSION @EXPORT); BEGIN{ $CPAN::Suppress_readline=1 unless defined $CPAN::term; } use Exporter (); @CPAN::ISA = ('Exporter'); use CPAN; $VERSION = "5.5001"; $CPAN::META->has_inst('Digest::MD5','no'); $CPAN::META->has_inst('LWP','no'); $CPAN::META->has_inst('Compress::Zlib','no'); @EXPORT = @CPAN::EXPORT; *AUTOLOAD = \&CPAN::AUTOLOAD; 1; __END__ =head1 NAME CPAN::Nox - Wrapper around CPAN.pm without using any XS module =head1 SYNOPSIS Interactive mode: perl -MCPAN::Nox -e shell; =head1 DESCRIPTION This package has the same functionality as CPAN.pm, but tries to prevent the usage of compiled extensions during its own execution. Its primary purpose is a rescue in case you upgraded perl and broke binary compatibility somehow. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L =cut PK!M :..perl5/CPAN/Distroprefs.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: use 5.006; use strict; package CPAN::Distroprefs; use vars qw($VERSION); $VERSION = '6.0001'; package CPAN::Distroprefs::Result; use File::Spec; sub new { bless $_[1] || {} => $_[0] } sub abs { File::Spec->catfile($_[0]->dir, $_[0]->file) } sub __cloner { my ($class, $name, $newclass) = @_; $newclass = 'CPAN::Distroprefs::Result::' . $newclass; no strict 'refs'; *{$class . '::' . $name} = sub { $newclass->new({ %{ $_[0] }, %{ $_[1] }, }); }; } BEGIN { __PACKAGE__->__cloner(as_warning => 'Warning') } BEGIN { __PACKAGE__->__cloner(as_fatal => 'Fatal') } BEGIN { __PACKAGE__->__cloner(as_success => 'Success') } sub __accessor { my ($class, $key) = @_; no strict 'refs'; *{$class . '::' . $key} = sub { $_[0]->{$key} }; } BEGIN { __PACKAGE__->__accessor($_) for qw(type file ext dir) } sub is_warning { 0 } sub is_fatal { 0 } sub is_success { 0 } package CPAN::Distroprefs::Result::Error; use vars qw(@ISA); BEGIN { @ISA = 'CPAN::Distroprefs::Result' } ## no critic BEGIN { __PACKAGE__->__accessor($_) for qw(msg) } sub as_string { my ($self) = @_; if ($self->msg) { return sprintf $self->fmt_reason, $self->file, $self->msg; } else { return sprintf $self->fmt_unknown, $self->file; } } package CPAN::Distroprefs::Result::Warning; use vars qw(@ISA); BEGIN { @ISA = 'CPAN::Distroprefs::Result::Error' } ## no critic sub is_warning { 1 } sub fmt_reason { "Error reading distroprefs file %s, skipping: %s" } sub fmt_unknown { "Unknown error reading distroprefs file %s, skipping." } package CPAN::Distroprefs::Result::Fatal; use vars qw(@ISA); BEGIN { @ISA = 'CPAN::Distroprefs::Result::Error' } ## no critic sub is_fatal { 1 } sub fmt_reason { "Error reading distroprefs file %s: %s" } sub fmt_unknown { "Unknown error reading distroprefs file %s." } package CPAN::Distroprefs::Result::Success; use vars qw(@ISA); BEGIN { @ISA = 'CPAN::Distroprefs::Result' } ## no critic BEGIN { __PACKAGE__->__accessor($_) for qw(prefs extension) } sub is_success { 1 } package CPAN::Distroprefs::Iterator; sub new { bless $_[1] => $_[0] } sub next { $_[0]->() } package CPAN::Distroprefs; use Carp (); use DirHandle; sub _load_method { my ($self, $loader, $result) = @_; return '_load_yaml' if $loader eq 'CPAN' or $loader =~ /^YAML(::|$)/; return '_load_' . $result->ext; } sub _load_yaml { my ($self, $loader, $result) = @_; my $data = eval { $loader eq 'CPAN' ? $loader->_yaml_loadfile($result->abs) : [ $loader->can('LoadFile')->($result->abs) ] }; if (my $err = $@) { die $result->as_warning({ msg => $err, }); } elsif (!$data) { die $result->as_warning; } else { return @$data; } } sub _load_dd { my ($self, $loader, $result) = @_; my @data; { package CPAN::Eval; # this caused a die in CPAN.pm, and I am leaving it 'fatal', though I'm # not sure why we wouldn't just skip the file as we do for all other # errors. -- hdp my $abs = $result->abs; open FH, "<$abs" or die $result->as_fatal(msg => "$!"); local $/; my $eval = ; close FH; no strict; eval $eval; if (my $err = $@) { die $result->as_warning({ msg => $err }); } my $i = 1; while (${"VAR$i"}) { push @data, ${"VAR$i"}; $i++; } } return @data; } sub _load_st { my ($self, $loader, $result) = @_; # eval because Storable is never forward compatible my @data = eval { @{scalar $loader->can('retrieve')->($result->abs) } }; if (my $err = $@) { die $result->as_warning({ msg => $err }); } return @data; } sub _build_file_list { if (@_ > 3) { die "_build_file_list should be called with 3 arguments, was called with more. First argument is '$_[0]'."; } my ($dir, $dir1, $ext_re) = @_; my @list; my $dh; unless (opendir($dh, $dir)) { $CPAN::Frontend->mywarn("ignoring prefs directory '$dir': $!"); return @list; } while (my $fn = readdir $dh) { next if $fn eq '.' || $fn eq '..'; if (-d "$dir/$fn") { next if $fn =~ /^[._]/; # prune .svn, .git, .hg, _darcs and what the user wants to hide push @list, _build_file_list("$dir/$fn", "$dir1$fn/", $ext_re); } else { if ($fn =~ $ext_re) { push @list, "$dir1$fn"; } } } return @list; } sub find { my ($self, $dir, $ext_map) = @_; return CPAN::Distroprefs::Iterator->new(sub { return }) unless %$ext_map; my $possible_ext = join "|", map { quotemeta } keys %$ext_map; my $ext_re = qr/\.($possible_ext)$/; my @files = _build_file_list($dir, '', $ext_re); @files = sort @files if @files; # label the block so that we can use redo in the middle return CPAN::Distroprefs::Iterator->new(sub { LOOP: { my $fn = shift @files; return unless defined $fn; my ($ext) = $fn =~ $ext_re; my $loader = $ext_map->{$ext}; my $result = CPAN::Distroprefs::Result->new({ file => $fn, ext => $ext, dir => $dir }); # copied from CPAN.pm; is this ever actually possible? redo unless -f $result->abs; my $load_method = $self->_load_method($loader, $result); my @prefs = eval { $self->$load_method($loader, $result) }; if (my $err = $@) { if (ref($err) && eval { $err->isa('CPAN::Distroprefs::Result') }) { return $err; } # rethrow any exceptions that we did not generate die $err; } elsif (!@prefs) { # the loader should have handled this, but just in case: return $result->as_warning; } return $result->as_success({ prefs => [ map { CPAN::Distroprefs::Pref->new({ data => $_ }) } @prefs ], }); } }); } package CPAN::Distroprefs::Pref; use Carp (); sub new { bless $_[1] => $_[0] } sub data { shift->{data} } sub has_any_match { $_[0]->data->{match} ? 1 : 0 } sub has_match { my $match = $_[0]->data->{match} || return 0; exists $match->{$_[1]} || exists $match->{"not_$_[1]"} } sub has_valid_subkeys { grep { exists $_[0]->data->{match}{$_} } map { $_, "not_$_" } $_[0]->match_attributes } sub _pattern { my $re = shift; my $p = eval sprintf 'qr{%s}', $re; if ($@) { $@ =~ s/\n$//; die "Error in Distroprefs pattern qr{$re}\n$@"; } return $p; } sub _match_scalar { my ($match, $data) = @_; my $qr = _pattern($match); return $data =~ /$qr/; } sub _match_hash { my ($match, $data) = @_; for my $mkey (keys %$match) { (my $dkey = $mkey) =~ s/^not_//; my $val = defined $data->{$dkey} ? $data->{$dkey} : ''; if (_match_scalar($match->{$mkey}, $val)) { return 0 if $mkey =~ /^not_/; } else { return 0 if $mkey !~ /^not_/; } } return 1; } sub _match { my ($self, $key, $data, $matcher) = @_; my $m = $self->data->{match}; if (exists $m->{$key}) { return 0 unless $matcher->($m->{$key}, $data); } if (exists $m->{"not_$key"}) { return 0 if $matcher->($m->{"not_$key"}, $data); } return 1; } sub _scalar_match { my ($self, $key, $data) = @_; return $self->_match($key, $data, \&_match_scalar); } sub _hash_match { my ($self, $key, $data) = @_; return $self->_match($key, $data, \&_match_hash); } # do not take the order of C because "module" is by far the # slowest sub match_attributes { qw(env distribution perl perlconfig module) } sub match_module { my ($self, $modules) = @_; return $self->_match("module", $modules, sub { my($match, $data) = @_; my $qr = _pattern($match); for my $module (@$data) { return 1 if $module =~ /$qr/; } return 0; }); } sub match_distribution { shift->_scalar_match(distribution => @_) } sub match_perl { shift->_scalar_match(perl => @_) } sub match_perlconfig { shift->_hash_match(perlconfig => @_) } sub match_env { shift->_hash_match(env => @_) } sub matches { my ($self, $arg) = @_; my $default_match = 0; for my $key (grep { $self->has_match($_) } $self->match_attributes) { unless (exists $arg->{$key}) { Carp::croak "Can't match pref: missing argument key $key"; } $default_match = 1; my $val = $arg->{$key}; # make it possible to avoid computing things until we have to if (ref($val) eq 'CODE') { $val = $val->() } my $meth = "match_$key"; return 0 unless $self->$meth($val); } return $default_match; } 1; __END__ =head1 NAME CPAN::Distroprefs -- read and match distroprefs =head1 SYNOPSIS use CPAN::Distroprefs; my %info = (... distribution/environment info ...); my $finder = CPAN::Distroprefs->find($prefs_dir, \%ext_map); while (my $result = $finder->next) { die $result->as_string if $result->is_fatal; warn($result->as_string), next if $result->is_warning; for my $pref (@{ $result->prefs }) { if ($pref->matches(\%info)) { return $pref; } } } =head1 DESCRIPTION This module encapsulates reading L and matching them against CPAN distributions. =head1 INTERFACE my $finder = CPAN::Distroprefs->find($dir, \%ext_map); while (my $result = $finder->next) { ... } Build an iterator which finds distroprefs files in the tree below the given directory. Within the tree directories matching C are pruned. C<%ext_map> is a hashref whose keys are file extensions and whose values are modules used to load matching files: { 'yml' => 'YAML::Syck', 'dd' => 'Data::Dumper', ... } Each time C<< $finder->next >> is called, the iterator returns one of two possible values: =over =item * a CPAN::Distroprefs::Result object =item * C, indicating that no prefs files remain to be found =back =head1 RESULTS L|/INTERFACE> returns CPAN::Distroprefs::Result objects to indicate success or failure when reading a prefs file. =head2 Common All results share some common attributes: =head3 type C, C, or C =head3 file the file from which these prefs were read, or to which this error refers (relative filename) =head3 ext the file's extension, which determines how to load it =head3 dir the directory the file was read from =head3 abs the absolute path to the file =head2 Errors Error results (warning and fatal) contain: =head3 msg the error message (usually either C<$!> or a YAML error) =head2 Successes Success results contain: =head3 prefs an arrayref of CPAN::Distroprefs::Pref objects =head1 PREFS CPAN::Distroprefs::Pref objects represent individual distroprefs documents. They are constructed automatically as part of C results from C. =head3 data the pref information as a hashref, suitable for e.g. passing to Kwalify =head3 match_attributes returns a list of the valid match attributes (see the Distroprefs section in L) currently: C =head3 has_any_match true if this pref has a 'match' attribute at all =head3 has_valid_subkeys true if this pref has a 'match' attribute and at least one valid match attribute =head3 matches if ($pref->matches(\%arg)) { ... } true if this pref matches the passed-in hashref, which must have a value for each of the C (above) =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!UVVperl5/CPAN/Index.pmnu6$package CPAN::Index; use strict; use vars qw($LAST_TIME $DATE_OF_02 $DATE_OF_03 $HAVE_REANIMATED $VERSION); $VERSION = "2.29"; @CPAN::Index::ISA = qw(CPAN::Debug); $LAST_TIME ||= 0; $DATE_OF_03 ||= 0; # use constant PROTOCOL => "2.0"; # commented out to avoid warning on upgrade from 1.57 sub PROTOCOL { 2.0 } #-> sub CPAN::Index::force_reload ; sub force_reload { my($class) = @_; $CPAN::Index::LAST_TIME = 0; $class->reload(1); } my @indexbundle = ( { reader => "rd_authindex", dir => "authors", remotefile => '01mailrc.txt.gz', shortlocalfile => '01mailrc.gz', }, { reader => "rd_modpacks", dir => "modules", remotefile => '02packages.details.txt.gz', shortlocalfile => '02packag.gz', }, { reader => "rd_modlist", dir => "modules", remotefile => '03modlist.data.gz', shortlocalfile => '03mlist.gz', }, ); #-> sub CPAN::Index::reload ; sub reload { my($self,$force) = @_; my $time = time; # XXX check if a newer one is available. (We currently read it # from time to time) for ($CPAN::Config->{index_expire}) { $_ = 0.001 unless $_ && $_ > 0.001; } unless (1 || $CPAN::Have_warned->{readmetadatacache}++) { # debug here when CPAN doesn't seem to read the Metadata require Carp; Carp::cluck("META-PROTOCOL[$CPAN::META->{PROTOCOL}]"); } unless ($CPAN::META->{PROTOCOL}) { $self->read_metadata_cache; $CPAN::META->{PROTOCOL} ||= "1.0"; } if ( $CPAN::META->{PROTOCOL} < PROTOCOL ) { # warn "Setting last_time to 0"; $LAST_TIME = 0; # No warning necessary } if ($LAST_TIME + $CPAN::Config->{index_expire}*86400 > $time and ! $force) { # called too often # CPAN->debug("LAST_TIME[$LAST_TIME]index_expire[$CPAN::Config->{index_expire}]time[$time]"); } elsif (0) { # IFF we are developing, it helps to wipe out the memory # between reloads, otherwise it is not what a user expects. undef $CPAN::META; # Neue Gruendlichkeit since v1.52(r1.274) $CPAN::META = CPAN->new; } else { my($debug,$t2); local $LAST_TIME = $time; local $CPAN::META->{PROTOCOL} = PROTOCOL; my $needshort = $^O eq "dos"; INX: for my $indexbundle (@indexbundle) { my $reader = $indexbundle->{reader}; my $localfile = $needshort ? $indexbundle->{shortlocalfile} : $indexbundle->{remotefile}; my $localpath = File::Spec->catfile($indexbundle->{dir}, $localfile); my $remote = join "/", $indexbundle->{dir}, $indexbundle->{remotefile}; my $localized = $self->reload_x($remote, $localpath, $force); $self->$reader($localized); # may die but we let the shell catch it if ($CPAN::DEBUG){ $t2 = time; $debug = "timing reading 01[".($t2 - $time)."]"; $time = $t2; } return if $CPAN::Signal; # this is sometimes lengthy } $self->write_metadata_cache; if ($CPAN::DEBUG){ $t2 = time; $debug .= "03[".($t2 - $time)."]"; $time = $t2; } CPAN->debug($debug) if $CPAN::DEBUG; } if ($CPAN::Config->{build_dir_reuse}) { $self->reanimate_build_dir; } if (CPAN::_sqlite_running()) { $CPAN::SQLite->reload(time => $time, force => $force) if not $LAST_TIME; } $LAST_TIME = $time; $CPAN::META->{PROTOCOL} = PROTOCOL; } #-> sub CPAN::Index::reanimate_build_dir ; sub reanimate_build_dir { my($self) = @_; unless ($CPAN::META->has_inst($CPAN::Config->{yaml_module}||"YAML")) { return; } return if $HAVE_REANIMATED++; my $d = $CPAN::Config->{build_dir}; my $dh = DirHandle->new; opendir $dh, $d or return; # does not exist my $dirent; my $i = 0; my $painted = 0; my $restored = 0; my $start = CPAN::FTP::_mytime(); my @candidates = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [ $_, -M File::Spec->catfile($d,$_) ] } grep {/(.+)\.yml$/ && -d File::Spec->catfile($d,$1)} readdir $dh; if ( @candidates ) { $CPAN::Frontend->myprint (sprintf("Reading %d yaml file%s from %s/\n", scalar @candidates, @candidates==1 ? "" : "s", $CPAN::Config->{build_dir} )); DISTRO: for $i (0..$#candidates) { my $dirent = $candidates[$i]; my $y = eval {CPAN->_yaml_loadfile(File::Spec->catfile($d,$dirent), {loadblessed => 1})}; if ($@) { warn "Error while parsing file '$dirent'; error: '$@'"; next DISTRO; } my $c = $y->[0]; if ($c && $c->{perl} && $c->{distribution} && CPAN->_perl_fingerprint($c->{perl})) { my $key = $c->{distribution}{ID}; for my $k (keys %{$c->{distribution}}) { if ($c->{distribution}{$k} && ref $c->{distribution}{$k} && UNIVERSAL::isa($c->{distribution}{$k},"CPAN::Distrostatus")) { $c->{distribution}{$k}{COMMANDID} = $i - @candidates; } } #we tried to restore only if element already #exists; but then we do not work with metadata #turned off. my $do = $CPAN::META->{readwrite}{'CPAN::Distribution'}{$key} = $c->{distribution}; for my $skipper (qw( badtestcnt configure_requires_later configure_requires_later_for force_update later later_for notest should_report sponsored_mods prefs negative_prefs_cache )) { delete $do->{$skipper}; } if ($do->can("tested_ok_but_not_installed")) { if ($do->tested_ok_but_not_installed) { $CPAN::META->is_tested($do->{build_dir},$do->{make_test}{TIME}); } else { next DISTRO; } } $restored++; } $i++; while (($painted/76) < ($i/@candidates)) { $CPAN::Frontend->myprint("."); $painted++; } } } else { $CPAN::Frontend->myprint("Build_dir empty, nothing to restore\n"); } my $took = CPAN::FTP::_mytime() - $start; $CPAN::Frontend->myprint(sprintf( "DONE\nRestored the state of %s (in %.4f secs)\n", $restored || "none", $took, )); } #-> sub CPAN::Index::reload_x ; sub reload_x { my($cl,$wanted,$localname,$force) = @_; $force |= 2; # means we're dealing with an index here CPAN::HandleConfig->load; # we should guarantee loading wherever # we rely on Config XXX $localname ||= $wanted; my $abs_wanted = File::Spec->catfile($CPAN::Config->{'keep_source_where'}, $localname); if ( -f $abs_wanted && -M $abs_wanted < $CPAN::Config->{'index_expire'} && !($force & 1) ) { my $s = $CPAN::Config->{'index_expire'} == 1 ? "" : "s"; $cl->debug(qq{$abs_wanted younger than $CPAN::Config->{'index_expire'} }. qq{day$s. I\'ll use that.}); return $abs_wanted; } else { $force |= 1; # means we're quite serious about it. } return CPAN::FTP->localize($wanted,$abs_wanted,$force); } #-> sub CPAN::Index::rd_authindex ; sub rd_authindex { my($cl, $index_target) = @_; return unless defined $index_target; return if CPAN::_sqlite_running(); my @lines; $CPAN::Frontend->myprint("Reading '$index_target'\n"); local(*FH); tie *FH, 'CPAN::Tarzip', $index_target; local($/) = "\n"; local($_); push @lines, split /\012/ while ; my $i = 0; my $painted = 0; foreach (@lines) { my($userid,$fullname,$email) = m/alias\s+(\S+)\s+\"([^\"\<]*)\s+\<(.*)\>\"/; $fullname ||= $email; if ($userid && $fullname && $email) { my $userobj = $CPAN::META->instance('CPAN::Author',$userid); $userobj->set('FULLNAME' => $fullname, 'EMAIL' => $email); } else { CPAN->debug(sprintf "line[%s]", $_) if $CPAN::DEBUG; } $i++; while (($painted/76) < ($i/@lines)) { $CPAN::Frontend->myprint("."); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); } sub userid { my($self,$dist) = @_; $dist = $self->{'id'} unless defined $dist; my($ret) = $dist =~ m|(?:\w/\w\w/)?([^/]+)/|; $ret; } #-> sub CPAN::Index::rd_modpacks ; sub rd_modpacks { my($self, $index_target) = @_; return unless defined $index_target; return if CPAN::_sqlite_running(); $CPAN::Frontend->myprint("Reading '$index_target'\n"); my $fh = CPAN::Tarzip->TIEHANDLE($index_target); local $_; CPAN->debug(sprintf "start[%d]", time) if $CPAN::DEBUG; my $slurp = ""; my $chunk; while (my $bytes = $fh->READ(\$chunk,8192)) { $slurp.=$chunk; } my @lines = split /\012/, $slurp; CPAN->debug(sprintf "end[%d]", time) if $CPAN::DEBUG; undef $fh; # read header my($line_count,$last_updated); while (@lines) { my $shift = shift(@lines); last if $shift =~ /^\s*$/; $shift =~ /^Line-Count:\s+(\d+)/ and $line_count = $1; $shift =~ /^Last-Updated:\s+(.+)/ and $last_updated = $1; } CPAN->debug("line_count[$line_count]last_updated[$last_updated]") if $CPAN::DEBUG; my $errors = 0; if (not defined $line_count) { $CPAN::Frontend->mywarn(qq{Warning: Your $index_target does not contain a Line-Count header. Please check the validity of the index file by comparing it to more than one CPAN mirror. I'll continue but problems seem likely to happen.\a }); $errors++; $CPAN::Frontend->mysleep(5); } elsif ($line_count != scalar @lines) { $CPAN::Frontend->mywarn(sprintf qq{Warning: Your %s contains a Line-Count header of %d but I see %d lines there. Please check the validity of the index file by comparing it to more than one CPAN mirror. I'll continue but problems seem likely to happen.\a\n}, $index_target, $line_count, scalar(@lines)); } if (not defined $last_updated) { $CPAN::Frontend->mywarn(qq{Warning: Your $index_target does not contain a Last-Updated header. Please check the validity of the index file by comparing it to more than one CPAN mirror. I'll continue but problems seem likely to happen.\a }); $errors++; $CPAN::Frontend->mysleep(5); } else { $CPAN::Frontend ->myprint(sprintf qq{ Database was generated on %s\n}, $last_updated); $DATE_OF_02 = $last_updated; my $age = time; if ($CPAN::META->has_inst('HTTP::Date')) { require HTTP::Date; $age -= HTTP::Date::str2time($last_updated); } else { $CPAN::Frontend->mywarn(" HTTP::Date not available\n"); require Time::Local; my(@d) = $last_updated =~ / (\d+) (\w+) (\d+) (\d+):(\d+):(\d+) /; $d[1] = index("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", $d[1])/4; $age -= $d[1]>=0 ? Time::Local::timegm(@d[5,4,3,0,1,2]) : 0; } $age /= 3600*24; if ($age > 30) { $CPAN::Frontend ->mywarn(sprintf qq{Warning: This index file is %d days old. Please check the host you chose as your CPAN mirror for staleness. I'll continue but problems seem likely to happen.\a\n}, $age); } elsif ($age < -1) { $CPAN::Frontend ->mywarn(sprintf qq{Warning: Your system date is %d days behind this index file! System time: %s Timestamp index file: %s Please fix your system time, problems with the make command expected.\n}, -$age, scalar gmtime, $DATE_OF_02, ); } } # A necessity since we have metadata_cache: delete what isn't # there anymore my $secondtime = $CPAN::META->exists("CPAN::Module","CPAN"); CPAN->debug("secondtime[$secondtime]") if $CPAN::DEBUG; my(%exists); my $i = 0; my $painted = 0; LINE: foreach (@lines) { # before 1.56 we split into 3 and discarded the rest. From # 1.57 we assign remaining text to $comment thus allowing to # influence isa_perl my($mod,$version,$dist,$comment) = split " ", $_, 4; unless ($mod && defined $version && $dist) { require Dumpvalue; my $dv = Dumpvalue->new(tick => '"'); $CPAN::Frontend->mywarn(sprintf "Could not split line[%s]\n", $dv->stringify($_)); if ($errors++ >= 5){ $CPAN::Frontend->mydie("Giving up parsing your $index_target, too many errors"); } next LINE; } my($bundle,$id,$userid); if ($mod eq 'CPAN' && ! ( CPAN::Queue->exists('Bundle::CPAN') || CPAN::Queue->exists('CPAN') ) ) { local($^W)= 0; if ($version > $CPAN::VERSION) { $CPAN::Frontend->mywarn(qq{ New CPAN.pm version (v$version) available. [Currently running version is v$CPAN::VERSION] You might want to try install CPAN reload cpan to both upgrade CPAN.pm and run the new version without leaving the current session. }); #}); $CPAN::Frontend->mysleep(2); $CPAN::Frontend->myprint(qq{\n}); } last if $CPAN::Signal; } elsif ($mod =~ /^Bundle::(.*)/) { $bundle = $1; } if ($bundle) { $id = $CPAN::META->instance('CPAN::Bundle',$mod); # Let's make it a module too, because bundles have so much # in common with modules. # Changed in 1.57_63: seems like memory bloat now without # any value, so commented out # $CPAN::META->instance('CPAN::Module',$mod); } else { # instantiate a module object $id = $CPAN::META->instance('CPAN::Module',$mod); } # Although CPAN prohibits same name with different version the # indexer may have changed the version for the same distro # since the last time ("Force Reindexing" feature) if ($id->cpan_file ne $dist || $id->cpan_version ne $version ) { $userid = $id->userid || $self->userid($dist); $id->set( 'CPAN_USERID' => $userid, 'CPAN_VERSION' => $version, 'CPAN_FILE' => $dist, ); } # instantiate a distribution object if ($CPAN::META->exists('CPAN::Distribution',$dist)) { # we do not need CONTAINSMODS unless we do something with # this dist, so we better produce it on demand. ## my $obj = $CPAN::META->instance( ## 'CPAN::Distribution' => $dist ## ); ## $obj->{CONTAINSMODS}{$mod} = undef; # experimental } else { $CPAN::META->instance( 'CPAN::Distribution' => $dist )->set( 'CPAN_USERID' => $userid, 'CPAN_COMMENT' => $comment, ); } if ($secondtime) { for my $name ($mod,$dist) { # $self->debug("exists name[$name]") if $CPAN::DEBUG; $exists{$name} = undef; } } $i++; while (($painted/76) < ($i/@lines)) { $CPAN::Frontend->myprint("."); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); if ($secondtime) { for my $class (qw(CPAN::Module CPAN::Bundle CPAN::Distribution)) { for my $o ($CPAN::META->all_objects($class)) { next if exists $exists{$o->{ID}}; $CPAN::META->delete($class,$o->{ID}); # CPAN->debug("deleting ID[$o->{ID}] in class[$class]") # if $CPAN::DEBUG; } } } } #-> sub CPAN::Index::rd_modlist ; sub rd_modlist { my($cl,$index_target) = @_; return unless defined $index_target; return if CPAN::_sqlite_running(); $CPAN::Frontend->myprint("Reading '$index_target'\n"); my $fh = CPAN::Tarzip->TIEHANDLE($index_target); local $_; my $slurp = ""; my $chunk; while (my $bytes = $fh->READ(\$chunk,8192)) { $slurp.=$chunk; } my @eval2 = split /\012/, $slurp; while (@eval2) { my $shift = shift(@eval2); if ($shift =~ /^Date:\s+(.*)/) { if ($DATE_OF_03 eq $1) { $CPAN::Frontend->myprint("Unchanged.\n"); return; } ($DATE_OF_03) = $1; } last if $shift =~ /^\s*$/; } push @eval2, q{CPAN::Modulelist->data;}; local($^W) = 0; my($compmt) = Safe->new("CPAN::Safe1"); my($eval2) = join("\n", @eval2); CPAN->debug(sprintf "length of eval2[%d]", length $eval2) if $CPAN::DEBUG; my $ret = $compmt->reval($eval2); Carp::confess($@) if $@; return if $CPAN::Signal; my $i = 0; my $until = keys(%$ret); my $painted = 0; CPAN->debug(sprintf "until[%d]", $until) if $CPAN::DEBUG; for (sort keys %$ret) { my $obj = $CPAN::META->instance("CPAN::Module",$_); delete $ret->{$_}{modid}; # not needed here, maybe elsewhere $obj->set(%{$ret->{$_}}); $i++; while (($painted/76) < ($i/$until)) { $CPAN::Frontend->myprint("."); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); } #-> sub CPAN::Index::write_metadata_cache ; sub write_metadata_cache { my($self) = @_; return unless $CPAN::Config->{'cache_metadata'}; return if CPAN::_sqlite_running(); return unless $CPAN::META->has_usable("Storable"); my $cache; foreach my $k (qw(CPAN::Bundle CPAN::Author CPAN::Module CPAN::Distribution)) { $cache->{$k} = $CPAN::META->{readonly}{$k}; # unsafe meta access, ok } my $metadata_file = File::Spec->catfile($CPAN::Config->{cpan_home},"Metadata"); $cache->{last_time} = $LAST_TIME; $cache->{DATE_OF_02} = $DATE_OF_02; $cache->{PROTOCOL} = PROTOCOL; $CPAN::Frontend->myprint("Writing $metadata_file\n"); eval { Storable::nstore($cache, $metadata_file) }; $CPAN::Frontend->mywarn($@) if $@; # ?? missing "\n" after $@ in mywarn ?? } #-> sub CPAN::Index::read_metadata_cache ; sub read_metadata_cache { my($self) = @_; return unless $CPAN::Config->{'cache_metadata'}; return if CPAN::_sqlite_running(); return unless $CPAN::META->has_usable("Storable"); my $metadata_file = File::Spec->catfile($CPAN::Config->{cpan_home},"Metadata"); return unless -r $metadata_file and -f $metadata_file; $CPAN::Frontend->myprint("Reading '$metadata_file'\n"); my $cache; eval { $cache = Storable::retrieve($metadata_file) }; $CPAN::Frontend->mywarn($@) if $@; # ?? missing "\n" after $@ in mywarn ?? if (!$cache || !UNIVERSAL::isa($cache, 'HASH')) { $LAST_TIME = 0; return; } if (exists $cache->{PROTOCOL}) { if (PROTOCOL > $cache->{PROTOCOL}) { $CPAN::Frontend->mywarn(sprintf("Ignoring Metadata cache written ". "with protocol v%s, requiring v%s\n", $cache->{PROTOCOL}, PROTOCOL) ); return; } } else { $CPAN::Frontend->mywarn("Ignoring Metadata cache written ". "with protocol v1.0\n"); return; } my $clcnt = 0; my $idcnt = 0; while(my($class,$v) = each %$cache) { next unless $class =~ /^CPAN::/; $CPAN::META->{readonly}{$class} = $v; # unsafe meta access, ok while (my($id,$ro) = each %$v) { $CPAN::META->{readwrite}{$class}{$id} ||= $class->new(ID=>$id, RO=>$ro); $idcnt++; } $clcnt++; } unless ($clcnt) { # sanity check $CPAN::Frontend->myprint("Warning: Found no data in $metadata_file\n"); return; } if ($idcnt < 1000) { $CPAN::Frontend->myprint("Warning: Found only $idcnt objects ". "in $metadata_file\n"); return; } $CPAN::META->{PROTOCOL} ||= $cache->{PROTOCOL}; # reading does not up or downgrade, but it # does initialize to some protocol $LAST_TIME = $cache->{last_time}; $DATE_OF_02 = $cache->{DATE_OF_02}; $CPAN::Frontend->myprint(" Database was generated on $DATE_OF_02\n") if defined $DATE_OF_02; # An old cache may not contain DATE_OF_02 return; } 1; PK!4A''perl5/CPAN/Bundle.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Bundle; use strict; use CPAN::Module; @CPAN::Bundle::ISA = qw(CPAN::Module); use vars qw( $VERSION ); $VERSION = "5.5005"; sub look { my $self = shift; $CPAN::Frontend->myprint($self->as_string); } #-> CPAN::Bundle::undelay sub undelay { my $self = shift; delete $self->{later}; for my $c ( $self->contains ) { my $obj = CPAN::Shell->expandany($c) or next; if ($obj->id eq $self->id){ my $id = $obj->id; $CPAN::Frontend->mywarn("$id seems to contain itself, skipping\n"); next; } $obj->undelay; } } # mark as dirty/clean #-> sub CPAN::Bundle::color_cmd_tmps ; sub color_cmd_tmps { my($self) = shift; my($depth) = shift || 0; my($color) = shift || 0; my($ancestors) = shift || []; # a module needs to recurse to its cpan_file, a distribution needs # to recurse into its prereq_pms, a bundle needs to recurse into its modules return if exists $self->{incommandcolor} && $color==1 && $self->{incommandcolor}==$color; if ($depth>=$CPAN::MAX_RECURSION) { my $e = CPAN::Exception::RecursiveDependency->new($ancestors); if ($e->is_resolvable) { return $self->{incommandcolor}=2; } else { die $e; } } # warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1; for my $c ( $self->contains ) { my $obj = CPAN::Shell->expandany($c) or next; CPAN->debug("c[$c]obj[$obj]") if $CPAN::DEBUG; $obj->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]); } # never reached code? #if ($color==0) { #delete $self->{badtestcnt}; #} $self->{incommandcolor} = $color; } #-> sub CPAN::Bundle::as_string ; sub as_string { my($self) = @_; $self->contains; # following line must be "=", not "||=" because we have a moving target $self->{INST_VERSION} = $self->inst_version; return $self->SUPER::as_string; } #-> sub CPAN::Bundle::contains ; sub contains { my($self) = @_; my($inst_file) = $self->inst_file || ""; my($id) = $self->id; $self->debug("inst_file[$inst_file]id[$id]") if $CPAN::DEBUG; if ($inst_file && CPAN::Version->vlt($self->inst_version,$self->cpan_version)) { undef $inst_file; } unless ($inst_file) { # Try to get at it in the cpan directory $self->debug("no inst_file") if $CPAN::DEBUG; my $cpan_file; $CPAN::Frontend->mydie("I don't know a bundle with ID '$id'\n") unless $cpan_file = $self->cpan_file; if ($cpan_file eq "N/A") { $CPAN::Frontend->mywarn("Bundle '$id' not found on disk and not on CPAN. Maybe stale symlink? Maybe removed during session?\n"); return; } my $dist = $CPAN::META->instance('CPAN::Distribution', $self->cpan_file); $self->debug("before get id[$dist->{ID}]") if $CPAN::DEBUG; $dist->get; $self->debug("after get id[$dist->{ID}]") if $CPAN::DEBUG; my($todir) = $CPAN::Config->{'cpan_home'}; my(@me,$from,$to,$me); @me = split /::/, $self->id; $me[-1] .= ".pm"; $me = File::Spec->catfile(@me); my $build_dir; unless ($build_dir = $dist->{build_dir}) { $CPAN::Frontend->mywarn("Warning: cannot determine bundle content without a build_dir.\n"); return; } $from = $self->find_bundle_file($build_dir,join('/',@me)); $to = File::Spec->catfile($todir,$me); File::Path::mkpath(File::Basename::dirname($to)); File::Copy::copy($from, $to) or Carp::confess("Couldn't copy $from to $to: $!"); $inst_file = $to; } my @result; my $fh = FileHandle->new; local $/ = "\n"; open($fh,$inst_file) or die "Could not open '$inst_file': $!"; my $in_cont = 0; $self->debug("inst_file[$inst_file]") if $CPAN::DEBUG; while (<$fh>) { $in_cont = m/^=(?!head1\s+(?i-xsm:CONTENTS))/ ? 0 : m/^=head1\s+(?i-xsm:CONTENTS)/ ? 1 : $in_cont; next unless $in_cont; next if /^=/; s/\#.*//; next if /^\s+$/; chomp; push @result, (split " ", $_, 2)[0]; } close $fh; delete $self->{STATUS}; $self->{CONTAINS} = \@result; $self->debug("CONTAINS[@result]") if $CPAN::DEBUG; unless (@result) { $CPAN::Frontend->mywarn(qq{ The bundle file "$inst_file" may be a broken bundlefile. It seems not to contain any bundle definition. Please check the file and if it is bogus, please delete it. Sorry for the inconvenience. }); } @result; } #-> sub CPAN::Bundle::find_bundle_file # $where is in local format, $what is in unix format sub find_bundle_file { my($self,$where,$what) = @_; $self->debug("where[$where]what[$what]") if $CPAN::DEBUG; ### The following two lines let CPAN.pm become Bundle/CPAN.pm :-( ### my $bu = File::Spec->catfile($where,$what); ### return $bu if -f $bu; my $manifest = File::Spec->catfile($where,"MANIFEST"); unless (-f $manifest) { require ExtUtils::Manifest; my $cwd = CPAN::anycwd(); $self->safe_chdir($where); ExtUtils::Manifest::mkmanifest(); $self->safe_chdir($cwd); } my $fh = FileHandle->new($manifest) or Carp::croak("Couldn't open $manifest: $!"); local($/) = "\n"; my $bundle_filename = $what; $bundle_filename =~ s|Bundle.*/||; my $bundle_unixpath; while (<$fh>) { next if /^\s*\#/; my($file) = /(\S+)/; if ($file =~ m|\Q$what\E$|) { $bundle_unixpath = $file; # return File::Spec->catfile($where,$bundle_unixpath); # bad last; } # retry if she managed to have no Bundle directory $bundle_unixpath = $file if $file =~ m|\Q$bundle_filename\E$|; } return File::Spec->catfile($where, split /\//, $bundle_unixpath) if $bundle_unixpath; Carp::croak("Couldn't find a Bundle file in $where"); } # needs to work quite differently from Module::inst_file because of # cpan_home/Bundle/ directory and the possibility that we have # shadowing effect. As it makes no sense to take the first in @INC for # Bundles, we parse them all for $VERSION and take the newest. #-> sub CPAN::Bundle::inst_file ; sub inst_file { my($self) = @_; my($inst_file); my(@me); @me = split /::/, $self->id; $me[-1] .= ".pm"; my($incdir,$bestv); foreach $incdir ($CPAN::Config->{'cpan_home'},@INC) { my $parsefile = File::Spec->catfile($incdir, @me); CPAN->debug("parsefile[$parsefile]") if $CPAN::DEBUG; next unless -f $parsefile; my $have = eval { MM->parse_version($parsefile); }; if ($@) { $CPAN::Frontend->mywarn("Error while parsing version number in file '$parsefile'\n"); } if (!$bestv || CPAN::Version->vgt($have,$bestv)) { $self->{INST_FILE} = $parsefile; $self->{INST_VERSION} = $bestv = $have; } } $self->{INST_FILE}; } #-> sub CPAN::Bundle::inst_version ; sub inst_version { my($self) = @_; $self->inst_file; # finds INST_VERSION as side effect $self->{INST_VERSION}; } #-> sub CPAN::Bundle::rematein ; sub rematein { my($self,$meth) = @_; $self->debug("self[$self] meth[$meth]") if $CPAN::DEBUG; my($id) = $self->id; Carp::croak( "Can't $meth $id, don't have an associated bundle file. :-(\n" ) unless $self->inst_file || $self->cpan_file; my($s,%fail); for $s ($self->contains) { my($type) = $s =~ m|/| ? 'CPAN::Distribution' : $s =~ m|^Bundle::| ? 'CPAN::Bundle' : 'CPAN::Module'; if ($type eq 'CPAN::Distribution') { $CPAN::Frontend->mywarn(qq{ The Bundle }.$self->id.qq{ contains explicitly a file '$s'. Going to $meth that. }); $CPAN::Frontend->mysleep(5); } # possibly noisy action: $self->debug("type[$type] s[$s]") if $CPAN::DEBUG; my $obj = $CPAN::META->instance($type,$s); $obj->{reqtype} = $self->{reqtype}; $obj->{viabundle} ||= { id => $id, reqtype => $self->{reqtype}, optional => !$self->{mandatory}}; # $obj->$meth(); # XXX should optional be based on whether bundle was optional? -- xdg, 2012-04-01 # A: Sure, what could demand otherwise? --andk, 2013-11-25 CPAN::Queue->queue_item(qmod => $obj->id, reqtype => $self->{reqtype}, optional => !$self->{mandatory}); } } # If a bundle contains another that contains an xs_file we have here, # we just don't bother I suppose #-> sub CPAN::Bundle::xs_file sub xs_file { return 0; } #-> sub CPAN::Bundle::force ; sub fforce { shift->rematein('fforce',@_); } #-> sub CPAN::Bundle::force ; sub force { shift->rematein('force',@_); } #-> sub CPAN::Bundle::notest ; sub notest { shift->rematein('notest',@_); } #-> sub CPAN::Bundle::get ; sub get { shift->rematein('get',@_); } #-> sub CPAN::Bundle::make ; sub make { shift->rematein('make',@_); } #-> sub CPAN::Bundle::test ; sub test { my $self = shift; # $self->{badtestcnt} ||= 0; $self->rematein('test',@_); } #-> sub CPAN::Bundle::install ; sub install { my $self = shift; $self->rematein('install',@_); } #-> sub CPAN::Bundle::clean ; sub clean { shift->rematein('clean',@_); } #-> sub CPAN::Bundle::uptodate ; sub uptodate { my($self) = @_; return 0 unless $self->SUPER::uptodate; # we must have the current Bundle def my $c; foreach $c ($self->contains) { my $obj = CPAN::Shell->expandany($c); return 0 unless $obj->uptodate; } return 1; } #-> sub CPAN::Bundle::readme ; sub readme { my($self) = @_; my($file) = $self->cpan_file or $CPAN::Frontend->myprint(qq{ No File found for bundle } . $self->id . qq{\n}), return; $self->debug("self[$self] file[$file]") if $CPAN::DEBUG; $CPAN::META->instance('CPAN::Distribution',$file)->readme; } 1; PK!Y3AAperl5/CPAN/Tarzip.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- package CPAN::Tarzip; use strict; use vars qw($VERSION @ISA $BUGHUNTING); use CPAN::Debug; use File::Basename qw(basename); $VERSION = "5.5013"; # module is internal to CPAN.pm @ISA = qw(CPAN::Debug); ## no critic $BUGHUNTING ||= 0; # released code must have turned off # it's ok if file doesn't exist, it just matters if it is .gz or .bz2 sub new { my($class,$file) = @_; $CPAN::Frontend->mydie("CPAN::Tarzip->new called without arg") unless defined $file; my $me = { FILE => $file }; if ($file =~ /\.(bz2|gz|zip|tbz|tgz)$/i) { $me->{ISCOMPRESSED} = 1; } else { $me->{ISCOMPRESSED} = 0; } if (0) { } elsif ($file =~ /\.(?:bz2|tbz)$/i) { unless ($me->{UNGZIPPRG} = $CPAN::Config->{bzip2}) { my $bzip2 = _my_which("bzip2"); if ($bzip2) { $me->{UNGZIPPRG} = $bzip2; } else { $CPAN::Frontend->mydie(qq{ CPAN.pm needs the external program bzip2 in order to handle '$file'. Please install it now and run 'o conf init bzip2' from the CPAN shell prompt to register it as external program. }); } } } else { $me->{UNGZIPPRG} = _my_which("gzip"); } $me->{TARPRG} = _my_which("tar") || _my_which("gtar"); bless $me, $class; } sub _zlib_ok () { $CPAN::META->has_inst("Compress::Zlib") or return; Compress::Zlib->can('gzopen'); } sub _my_which { my($what) = @_; if ($CPAN::Config->{$what}) { return $CPAN::Config->{$what}; } if ($CPAN::META->has_inst("File::Which")) { return File::Which::which($what); } my @cand = MM->maybe_command($what); return $cand[0] if @cand; require File::Spec; my $component; PATH_COMPONENT: foreach $component (File::Spec->path()) { next unless defined($component) && $component; my($abs) = File::Spec->catfile($component,$what); if (MM->maybe_command($abs)) { return $abs; } } return; } sub gzip { my($self,$read) = @_; my $write = $self->{FILE}; if (_zlib_ok) { my($buffer,$fhw); $fhw = FileHandle->new($read) or $CPAN::Frontend->mydie("Could not open $read: $!"); my $cwd = `pwd`; my $gz = Compress::Zlib::gzopen($write, "wb") or $CPAN::Frontend->mydie("Cannot gzopen $write: $! (pwd is $cwd)\n"); binmode($fhw); $gz->gzwrite($buffer) while read($fhw,$buffer,4096) > 0 ; $gz->gzclose() ; $fhw->close; return 1; } else { my $command = CPAN::HandleConfig->safe_quote($self->{UNGZIPPRG}); system(qq{$command -c "$read" > "$write"})==0; } } sub gunzip { my($self,$write) = @_; my $read = $self->{FILE}; if (_zlib_ok) { my($buffer,$fhw); $fhw = FileHandle->new(">$write") or $CPAN::Frontend->mydie("Could not open >$write: $!"); my $gz = Compress::Zlib::gzopen($read, "rb") or $CPAN::Frontend->mydie("Cannot gzopen $read: $!\n"); binmode($fhw); $fhw->print($buffer) while $gz->gzread($buffer) > 0 ; $CPAN::Frontend->mydie("Error reading from $read: $!\n") if $gz->gzerror != Compress::Zlib::Z_STREAM_END(); $gz->gzclose() ; $fhw->close; return 1; } else { my $command = CPAN::HandleConfig->safe_quote($self->{UNGZIPPRG}); system(qq{$command -d -c "$read" > "$write"})==0; } } sub gtest { my($self) = @_; return $self->{GTEST} if exists $self->{GTEST}; defined $self->{FILE} or $CPAN::Frontend->mydie("gtest called but no FILE specified"); my $read = $self->{FILE}; my $success; if ($read=~/\.(?:bz2|tbz)$/ && $CPAN::META->has_inst("Compress::Bzip2")) { my($buffer,$len); $len = 0; my $gz = Compress::Bzip2::bzopen($read, "rb") or $CPAN::Frontend->mydie(sprintf("Cannot bzopen %s: %s\n", $read, $Compress::Bzip2::bzerrno)); while ($gz->bzread($buffer) > 0 ) { $len += length($buffer); $buffer = ""; } my $err = $gz->bzerror; $success = ! $err || $err == Compress::Bzip2::BZ_STREAM_END(); if ($len == -s $read) { $success = 0; CPAN->debug("hit an uncompressed file") if $CPAN::DEBUG; } $gz->gzclose(); CPAN->debug("err[$err]success[$success]") if $CPAN::DEBUG; } elsif ( $read=~/\.(?:gz|tgz)$/ && _zlib_ok ) { # After I had reread the documentation in zlib.h, I discovered that # uncompressed files do not lead to an gzerror (anymore?). my($buffer,$len); $len = 0; my $gz = Compress::Zlib::gzopen($read, "rb") or $CPAN::Frontend->mydie(sprintf("Cannot gzopen %s: %s\n", $read, $Compress::Zlib::gzerrno)); while ($gz->gzread($buffer) > 0 ) { $len += length($buffer); $buffer = ""; } my $err = $gz->gzerror; $success = ! $err || $err == Compress::Zlib::Z_STREAM_END(); if ($len == -s $read) { $success = 0; CPAN->debug("hit an uncompressed file") if $CPAN::DEBUG; } $gz->gzclose(); CPAN->debug("err[$err]success[$success]") if $CPAN::DEBUG; } elsif (!$self->{ISCOMPRESSED}) { $success = 0; } else { my $command = CPAN::HandleConfig->safe_quote($self->{UNGZIPPRG}); $success = 0==system(qq{$command -qdt "$read"}); } return $self->{GTEST} = $success; } sub TIEHANDLE { my($class,$file) = @_; my $ret; $class->debug("file[$file]"); my $self = $class->new($file); if (0) { } elsif (!$self->gtest) { my $fh = FileHandle->new($file) or $CPAN::Frontend->mydie("Could not open file[$file]: $!"); binmode $fh; $self->{FH} = $fh; $class->debug("via uncompressed FH"); } elsif ($file =~ /\.(?:bz2|tbz)$/ && $CPAN::META->has_inst("Compress::Bzip2")) { my $gz = Compress::Bzip2::bzopen($file,"rb") or $CPAN::Frontend->mydie("Could not bzopen $file"); $self->{GZ} = $gz; $class->debug("via Compress::Bzip2"); } elsif ($file =~/\.(?:gz|tgz)$/ && _zlib_ok) { my $gz = Compress::Zlib::gzopen($file,"rb") or $CPAN::Frontend->mydie("Could not gzopen $file"); $self->{GZ} = $gz; $class->debug("via Compress::Zlib"); } else { my $gzip = CPAN::HandleConfig->safe_quote($self->{UNGZIPPRG}); my $pipe = "$gzip -d -c $file |"; my $fh = FileHandle->new($pipe) or $CPAN::Frontend->mydie("Could not pipe[$pipe]: $!"); binmode $fh; $self->{FH} = $fh; $class->debug("via external $gzip"); } $self; } sub READLINE { my($self) = @_; if (exists $self->{GZ}) { my $gz = $self->{GZ}; my($line,$bytesread); $bytesread = $gz->gzreadline($line); return undef if $bytesread <= 0; return $line; } else { my $fh = $self->{FH}; return scalar <$fh>; } } sub READ { my($self,$ref,$length,$offset) = @_; $CPAN::Frontend->mydie("read with offset not implemented") if defined $offset; if (exists $self->{GZ}) { my $gz = $self->{GZ}; my $byteread = $gz->gzread($$ref,$length);# 30eaf79e8b446ef52464b5422da328a8 return $byteread; } else { my $fh = $self->{FH}; return read($fh,$$ref,$length); } } sub DESTROY { my($self) = @_; if (exists $self->{GZ}) { my $gz = $self->{GZ}; $gz->gzclose() if defined $gz; # hard to say if it is allowed # to be undef ever. AK, 2000-09 } else { my $fh = $self->{FH}; $fh->close if defined $fh; } undef $self; } sub untar { my($self) = @_; my $file = $self->{FILE}; my($prefer) = 0; my $exttar = $self->{TARPRG} || ""; $exttar = "" if $exttar =~ /^\s+$/; # user refuses to use it my $extgzip = $self->{UNGZIPPRG} || ""; $extgzip = "" if $extgzip =~ /^\s+$/; # user refuses to use it if (0) { # makes changing order easier } elsif ($BUGHUNTING) { $prefer=2; } elsif ($CPAN::Config->{prefer_external_tar}) { $prefer = 1; } elsif ( $CPAN::META->has_usable("Archive::Tar") && _zlib_ok ) { my $prefer_external_tar = $CPAN::Config->{prefer_external_tar}; unless (defined $prefer_external_tar) { if ($^O =~ /(MSWin32|solaris)/) { $prefer_external_tar = 0; } else { $prefer_external_tar = 1; } } $prefer = $prefer_external_tar ? 1 : 2; } elsif ($exttar && $extgzip) { # no modules and not bz2 $prefer = 1; # but solaris binary tar is a problem if ($^O eq 'solaris' && qx($exttar --version 2>/dev/null) !~ /gnu/i) { $CPAN::Frontend->mywarn(<< 'END_WARN'); WARNING: Many CPAN distributions were archived with GNU tar and some of them may be incompatible with Solaris tar. We respectfully suggest you configure CPAN to use a GNU tar instead ("o conf init tar") or install a recent Archive::Tar instead; END_WARN } } else { my $foundtar = $exttar ? "'$exttar'" : "nothing"; my $foundzip = $extgzip ? "'$extgzip'" : $foundtar ? "nothing" : "also nothing"; my $foundAT; if ($CPAN::META->has_usable("Archive::Tar")) { $foundAT = sprintf "'%s'", "Archive::Tar::"->VERSION; } else { $foundAT = "nothing"; } my $foundCZ; if (_zlib_ok) { $foundCZ = sprintf "'%s'", "Compress::Zlib::"->VERSION; } elsif ($foundAT) { $foundCZ = "nothing"; } else { $foundCZ = "also nothing"; } $CPAN::Frontend->mydie(qq{ CPAN.pm needs either the external programs tar and gzip -or- both modules Archive::Tar and Compress::Zlib installed. For tar I found $foundtar, for gzip $foundzip. For Archive::Tar I found $foundAT, for Compress::Zlib $foundCZ; Can't continue cutting file '$file'. }); } my $tar_verb = "v"; if (defined $CPAN::Config->{tar_verbosity}) { $tar_verb = $CPAN::Config->{tar_verbosity} eq "none" ? "" : $CPAN::Config->{tar_verbosity}; } if ($prefer==1) { # 1 => external gzip+tar my($system); my $is_compressed = $self->gtest(); my $tarcommand = CPAN::HandleConfig->safe_quote($exttar); if ($is_compressed) { my $command = CPAN::HandleConfig->safe_quote($extgzip); $system = qq{$command -d -c }. qq{< "$file" | $tarcommand x${tar_verb}f -}; } else { $system = qq{$tarcommand x${tar_verb}f "$file"}; } if (system($system) != 0) { # people find the most curious tar binaries that cannot handle # pipes if ($is_compressed) { (my $ungzf = $file) =~ s/\.gz(?!\n)\Z//; $ungzf = basename $ungzf; my $ct = CPAN::Tarzip->new($file); if ($ct->gunzip($ungzf)) { $CPAN::Frontend->myprint(qq{Uncompressed $file successfully\n}); } else { $CPAN::Frontend->mydie(qq{Couldn\'t uncompress $file\n}); } $file = $ungzf; } $system = qq{$tarcommand x${tar_verb}f "$file"}; $CPAN::Frontend->myprint(qq{Using Tar:$system:\n}); my $ret = system($system); if ($ret==0) { $CPAN::Frontend->myprint(qq{Untarred $file successfully\n}); } else { if ($? == -1) { $CPAN::Frontend->mydie(sprintf qq{Couldn\'t untar %s: '%s'\n}, $file, $!); } elsif ($? & 127) { $CPAN::Frontend->mydie(sprintf qq{Couldn\'t untar %s: child died with signal %d, %s coredump\n}, $file, ($? & 127), ($? & 128) ? 'with' : 'without'); } else { $CPAN::Frontend->mydie(sprintf qq{Couldn\'t untar %s: child exited with value %d\n}, $file, $? >> 8); } } return 1; } else { return 1; } } elsif ($prefer==2) { # 2 => modules unless ($CPAN::META->has_usable("Archive::Tar")) { $CPAN::Frontend->mydie("Archive::Tar not installed, please install it to continue"); } # Make sure AT does not use uid/gid/permissions in the archive # This leaves it to the user's umask instead local $Archive::Tar::CHMOD = 1; local $Archive::Tar::SAME_PERMISSIONS = 0; # Make sure AT leaves current user as owner local $Archive::Tar::CHOWN = 0; my $tar = Archive::Tar->new($file,1); my $af; # archive file my @af; if ($BUGHUNTING) { # RCS 1.337 had this code, it turned out unacceptable slow but # it revealed a bug in Archive::Tar. Code is only here to hunt # the bug again. It should never be enabled in published code. # GDGraph3d-0.53 was an interesting case according to Larry # Virden. warn(">>>Bughunting code enabled<<< " x 20); for $af ($tar->list_files) { if ($af =~ m!^(/|\.\./)!) { $CPAN::Frontend->mydie("ALERT: Archive contains ". "illegal member [$af]"); } $CPAN::Frontend->myprint("$af\n"); $tar->extract($af); # slow but effective for finding the bug return if $CPAN::Signal; } } else { for $af ($tar->list_files) { if ($af =~ m!^(/|\.\./)!) { $CPAN::Frontend->mydie("ALERT: Archive contains ". "illegal member [$af]"); } if ($tar_verb eq "v" || $tar_verb eq "vv") { $CPAN::Frontend->myprint("$af\n"); } push @af, $af; return if $CPAN::Signal; } $tar->extract(@af) or $CPAN::Frontend->mydie("Could not untar with Archive::Tar."); } Mac::BuildTools::convert_files([$tar->list_files], 1) if ($^O eq 'MacOS'); return 1; } } sub unzip { my($self) = @_; my $file = $self->{FILE}; if ($CPAN::META->has_inst("Archive::Zip")) { # blueprint of the code from Archive::Zip::Tree::extractTree(); my $zip = Archive::Zip->new(); my $status; $status = $zip->read($file); $CPAN::Frontend->mydie("Read of file[$file] failed\n") if $status != Archive::Zip::AZ_OK(); $CPAN::META->debug("Successfully read file[$file]") if $CPAN::DEBUG; my @members = $zip->members(); for my $member ( @members ) { my $af = $member->fileName(); if ($af =~ m!^(/|\.\./)!) { $CPAN::Frontend->mydie("ALERT: Archive contains ". "illegal member [$af]"); } $status = $member->extractToFileNamed( $af ); $CPAN::META->debug("af[$af]status[$status]") if $CPAN::DEBUG; $CPAN::Frontend->mydie("Extracting of file[$af] from zipfile[$file] failed\n") if $status != Archive::Zip::AZ_OK(); return if $CPAN::Signal; } return 1; } elsif ( my $unzip = $CPAN::Config->{unzip} ) { my @system = ($unzip, $file); return system(@system) == 0; } else { $CPAN::Frontend->mydie(<<"END"); Can't unzip '$file': You have not configured an 'unzip' program and do not have Archive::Zip installed. Please either install Archive::Zip or else configure 'unzip' by running the command 'o conf init unzip' from the CPAN shell prompt. END } } 1; __END__ =head1 NAME CPAN::Tarzip - internal handling of tar archives for CPAN.pm =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK!Lperl5/CPAN/Distribution.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Distribution; use strict; use Cwd qw(chdir); use CPAN::Distroprefs; use CPAN::InfoObj; use File::Path (); use POSIX ":sys_wait_h"; @CPAN::Distribution::ISA = qw(CPAN::InfoObj); use vars qw($VERSION); $VERSION = "2.34"; my $run_allow_installing_within_test = 1; # boolean; either in test or in install, there is no third option # no prepare, because prepare is not a command on the shell command line # TODO: clear instance cache on reload my %instance; for my $method (qw(get make test install)) { no strict 'refs'; for my $prefix (qw(pre post)) { my $hookname = sprintf "%s_%s", $prefix, $method; *$hookname = sub { my($self) = @_; for my $plugin (@{$CPAN::Config->{plugin_list}}) { my($plugin_proper,$args) = split /=/, $plugin, 2; $args = "" unless defined $args; if ($CPAN::META->has_inst($plugin_proper)){ my @args = split /,/, $args; $instance{$plugin} ||= $plugin_proper->new(@args); if ($instance{$plugin}->can($hookname)) { $instance{$plugin}->$hookname($self); } } else { $CPAN::Frontend->mydie("Plugin '$plugin_proper' not found for hook '$hookname'"); } } }; } } # Accessors sub cpan_comment { my $self = shift; my $ro = $self->ro or return; $ro->{CPAN_COMMENT} } #-> CPAN::Distribution::undelay sub undelay { my $self = shift; for my $delayer ( "configure_requires_later", "configure_requires_later_for", "later", "later_for", ) { delete $self->{$delayer}; } } #-> CPAN::Distribution::is_dot_dist sub is_dot_dist { my($self) = @_; return substr($self->id,-1,1) eq "."; } # add the A/AN/ stuff #-> CPAN::Distribution::normalize sub normalize { my($self,$s) = @_; $s = $self->id unless defined $s; if (substr($s,-1,1) eq ".") { # using a global because we are sometimes called as static method if (!$CPAN::META->{LOCK} && !$CPAN::Have_warned->{"$s is unlocked"}++ ) { $CPAN::Frontend->mywarn("You are visiting the local directory '$s' without lock, take care that concurrent processes do not do likewise.\n"); $CPAN::Frontend->mysleep(1); } if ($s eq ".") { $s = "$CPAN::iCwd/."; } elsif (File::Spec->file_name_is_absolute($s)) { } elsif (File::Spec->can("rel2abs")) { $s = File::Spec->rel2abs($s); } else { $CPAN::Frontend->mydie("Your File::Spec is too old, please upgrade File::Spec"); } CPAN->debug("s[$s]") if $CPAN::DEBUG; unless ($CPAN::META->exists("CPAN::Distribution", $s)) { for ($CPAN::META->instance("CPAN::Distribution", $s)) { $_->{build_dir} = $s; $_->{archived} = "local_directory"; $_->{unwrapped} = CPAN::Distrostatus->new("YES -- local_directory"); } } } elsif ( $s =~ tr|/|| == 1 or $s !~ m|[A-Z]/[A-Z-0-9]{2}/[A-Z-0-9]{2,}/| ) { return $s if $s =~ m:^N/A|^Contact Author: ; $s =~ s|^(.)(.)([^/]*/)(.+)$|$1/$1$2/$1$2$3$4|; CPAN->debug("s[$s]") if $CPAN::DEBUG; } $s; } #-> sub CPAN::Distribution::author ; sub author { my($self) = @_; my($authorid); if (substr($self->id,-1,1) eq ".") { $authorid = "LOCAL"; } else { ($authorid) = $self->pretty_id =~ /^([\w\-]+)/; } CPAN::Shell->expand("Author",$authorid); } # tries to get the yaml from CPAN instead of the distro itself: # EXPERIMENTAL, UNDOCUMENTED AND UNTESTED, for Tels sub fast_yaml { my($self) = @_; my $meta = $self->pretty_id; $meta =~ s/\.(tar.gz|tgz|zip|tar.bz2)/.meta/; my(@ls) = CPAN::Shell->globls($meta); my $norm = $self->normalize($meta); my($local_file); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,$norm) ); $self->debug("Doing localize") if $CPAN::DEBUG; unless ($local_file = CPAN::FTP->localize("authors/id/$norm", $local_wanted)) { $CPAN::Frontend->mydie("Giving up on downloading yaml file '$local_wanted'\n"); } my $yaml = CPAN->_yaml_loadfile($local_file)->[0]; } #-> sub CPAN::Distribution::cpan_userid sub cpan_userid { my $self = shift; if ($self->{ID} =~ m{[A-Z]/[A-Z\-]{2}/([A-Z\-]+)/}) { return $1; } return $self->SUPER::cpan_userid; } #-> sub CPAN::Distribution::pretty_id sub pretty_id { my $self = shift; my $id = $self->id; return $id unless $id =~ m|^./../|; substr($id,5); } #-> sub CPAN::Distribution::base_id sub base_id { my $self = shift; my $id = $self->pretty_id(); my $base_id = File::Basename::basename($id); $base_id =~ s{\.(?:tar\.(bz2|gz|Z)|t(?:gz|bz)|zip)$}{}i; return $base_id; } #-> sub CPAN::Distribution::tested_ok_but_not_installed sub tested_ok_but_not_installed { my $self = shift; return ( $self->{make_test} && $self->{build_dir} && (UNIVERSAL::can($self->{make_test},"failed") ? ! $self->{make_test}->failed : $self->{make_test} =~ /^YES/ ) && ( !$self->{install} || $self->{install}->failed ) ); } # mark as dirty/clean for the sake of recursion detection. $color=1 # means "in use", $color=0 means "not in use anymore". $color=2 means # we have determined prereqs now and thus insist on passing this # through (at least) once again. #-> sub CPAN::Distribution::color_cmd_tmps ; sub color_cmd_tmps { my($self) = shift; my($depth) = shift || 0; my($color) = shift || 0; my($ancestors) = shift || []; # a distribution needs to recurse into its prereq_pms $self->debug("color_cmd_tmps[$depth,$color,@$ancestors]") if $CPAN::DEBUG; return if exists $self->{incommandcolor} && $color==1 && $self->{incommandcolor}==$color; $CPAN::MAX_RECURSION||=0; # silence 'once' warnings if ($depth>=$CPAN::MAX_RECURSION) { my $e = CPAN::Exception::RecursiveDependency->new($ancestors); if ($e->is_resolvable) { return $self->{incommandcolor}=2; } else { die $e; } } # warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1; my $prereq_pm = $self->prereq_pm; if (defined $prereq_pm) { # XXX also optional_req & optional_breq? -- xdg, 2012-04-01 # A: no, optional deps may recurse -- ak, 2014-05-07 PREREQ: for my $pre (sort( keys %{$prereq_pm->{requires}||{}}, keys %{$prereq_pm->{build_requires}||{}}, )) { next PREREQ if $pre eq "perl"; my $premo; unless ($premo = CPAN::Shell->expand("Module",$pre)) { $CPAN::Frontend->mywarn("prerequisite module[$pre] not known\n"); $CPAN::Frontend->mysleep(0.2); next PREREQ; } $premo->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]); } } if ($color==0) { delete $self->{sponsored_mods}; # as we are at the end of a command, we'll give up this # reminder of a broken test. Other commands may test this guy # again. Maybe 'badtestcnt' should be renamed to # 'make_test_failed_within_command'? delete $self->{badtestcnt}; } $self->{incommandcolor} = $color; } #-> sub CPAN::Distribution::as_string ; sub as_string { my $self = shift; $self->containsmods; $self->upload_date; $self->SUPER::as_string(@_); } #-> sub CPAN::Distribution::containsmods ; sub containsmods { my $self = shift; return sort keys %{$self->{CONTAINSMODS}} if exists $self->{CONTAINSMODS}; my $dist_id = $self->{ID}; for my $mod ($CPAN::META->all_objects("CPAN::Module")) { my $mod_file = $mod->cpan_file or next; my $mod_id = $mod->{ID} or next; # warn "mod_file[$mod_file] dist_id[$dist_id] mod_id[$mod_id]"; # sleep 1; if ($CPAN::Signal) { delete $self->{CONTAINSMODS}; return; } $self->{CONTAINSMODS}{$mod_id} = undef if $mod_file eq $dist_id; } sort keys %{$self->{CONTAINSMODS}||={}}; } #-> sub CPAN::Distribution::upload_date ; sub upload_date { my $self = shift; return $self->{UPLOAD_DATE} if exists $self->{UPLOAD_DATE}; my(@local_wanted) = split(/\//,$self->id); my $filename = pop @local_wanted; push @local_wanted, "CHECKSUMS"; my $author = CPAN::Shell->expand("Author",$self->cpan_userid); return unless $author; my @dl = $author->dir_listing(\@local_wanted,0,$CPAN::Config->{show_upload_date}); return unless @dl; my($dirent) = grep { $_->[2] eq $filename } @dl; # warn sprintf "dirent[%s]id[%s]", $dirent, $self->id; return unless $dirent->[1]; return $self->{UPLOAD_DATE} = $dirent->[1]; } #-> sub CPAN::Distribution::uptodate ; sub uptodate { my($self) = @_; my $c; foreach $c ($self->containsmods) { my $obj = CPAN::Shell->expandany($c); unless ($obj->uptodate) { my $id = $self->pretty_id; $self->debug("$id not uptodate due to $c") if $CPAN::DEBUG; return 0; } } return 1; } #-> sub CPAN::Distribution::called_for ; sub called_for { my($self,$id) = @_; $self->{CALLED_FOR} = $id if defined $id; return $self->{CALLED_FOR}; } #-> sub CPAN::Distribution::shortcut_get ; # return values: undef means don't shortcut; 0 means shortcut as fail; # and 1 means shortcut as success sub shortcut_get { my ($self) = @_; if (exists $self->{cleanup_after_install_done}) { if ($self->{force_update}) { delete $self->{cleanup_after_install_done}; } else { my $id = $self->{CALLED_FOR} || $self->pretty_id; return $self->success( "Has already been *installed and cleaned up in the staging area* within this session, will not work on it again; if you really want to start over, try something like `force get $id`" ); } } if (my $why = $self->check_disabled) { $self->{unwrapped} = CPAN::Distrostatus->new("NO $why"); # XXX why is this goodbye() instead of just print/warn? # Alternatively, should other print/warns here be goodbye()? # -- xdg, 2012-04-05 return $self->goodbye("[disabled] -- NA $why"); } $self->debug("checking already unwrapped[$self->{ID}]") if $CPAN::DEBUG; if (exists $self->{build_dir} && -d $self->{build_dir}) { # this deserves print, not warn: return $self->success("Has already been unwrapped into directory ". "$self->{build_dir}" ); } # XXX I'm not sure this should be here because it's not really # a test for whether get should continue or return; this is # a side effect -- xdg, 2012-04-05 $self->debug("checking missing build_dir[$self->{ID}]") if $CPAN::DEBUG; if (exists $self->{build_dir} && ! -d $self->{build_dir}){ # we have lost it. $self->fforce(""); # no method to reset all phases but not set force (dodge) return undef; # no shortcut } # although we talk about 'force' we shall not test on # force directly. New model of force tries to refrain from # direct checking of force. $self->debug("checking unwrapping error[$self->{ID}]") if $CPAN::DEBUG; if ( exists $self->{unwrapped} and ( UNIVERSAL::can($self->{unwrapped},"failed") ? $self->{unwrapped}->failed : $self->{unwrapped} =~ /^NO/ ) ) { return $self->goodbye("Unwrapping had some problem, won't try again without force"); } return undef; # no shortcut } #-> sub CPAN::Distribution::get ; sub get { my($self) = @_; $self->pre_get(); $self->debug("checking goto id[$self->{ID}]") if $CPAN::DEBUG; if (my $goto = $self->prefs->{goto}) { $self->post_get(); return $self->goto($goto); } if ( defined( my $sc = $self->shortcut_get) ) { $self->post_get(); return $sc; } local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : ""; # local $ENV{PERL_USE_UNSAFE_INC} = exists $ENV{PERL_USE_UNSAFE_INC} ? $ENV{PERL_USE_UNSAFE_INC} : 1; # get $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls my $sub_wd = CPAN::anycwd(); # for cleaning up as good as possible my($local_file); # XXX I don't think this check needs to be here, as it # is already checked in shortcut_get() -- xdg, 2012-04-05 unless ($self->{build_dir} && -d $self->{build_dir}) { $self->get_file_onto_local_disk; if ($CPAN::Signal){ $self->post_get(); return; } $self->check_integrity; if ($CPAN::Signal){ $self->post_get(); return; } (my $packagedir,$local_file) = $self->run_preps_on_packagedir; # XXX why is this check here? -- xdg, 2012-04-08 if (exists $self->{writemakefile} && ref $self->{writemakefile} && $self->{writemakefile}->can("failed") && $self->{writemakefile}->failed) { # $self->post_get(); return; } $packagedir ||= $self->{build_dir}; $self->{build_dir} = $packagedir; } # XXX should this move up to after run_preps_on_packagedir? # Otherwise, failing writemakefile can return without # a $CPAN::Signal check -- xdg, 2012-04-05 if ($CPAN::Signal) { $self->safe_chdir($sub_wd); $self->post_get(); return; } unless ($self->patch){ $self->post_get(); return; } $self->store_persistent_state; $self->post_get(); return 1; # success } #-> CPAN::Distribution::get_file_onto_local_disk sub get_file_onto_local_disk { my($self) = @_; return if $self->is_dot_dist; my($local_file); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,$self->id) ); $self->debug("Doing localize") if $CPAN::DEBUG; unless ($local_file = CPAN::FTP->localize("authors/id/$self->{ID}", $local_wanted)) { my $note = ""; if ($CPAN::Index::DATE_OF_02) { $note = "Note: Current database in memory was generated ". "on $CPAN::Index::DATE_OF_02\n"; } $CPAN::Frontend->mydie("Giving up on '$local_wanted'\n$note"); } $self->debug("local_wanted[$local_wanted]local_file[$local_file]") if $CPAN::DEBUG; $self->{localfile} = $local_file; } #-> CPAN::Distribution::check_integrity sub check_integrity { my($self) = @_; return if $self->is_dot_dist; if ($CPAN::META->has_inst("Digest::SHA")) { $self->debug("Digest::SHA is installed, verifying"); $self->verifyCHECKSUM; } else { $self->debug("Digest::SHA is NOT installed"); } } #-> CPAN::Distribution::run_preps_on_packagedir sub run_preps_on_packagedir { my($self) = @_; return if $self->is_dot_dist; $CPAN::META->{cachemgr} ||= CPAN::CacheMgr->new(); # unsafe meta access, ok my $builddir = $CPAN::META->{cachemgr}->dir; # unsafe meta access, ok $self->safe_chdir($builddir); $self->debug("Removing tmp-$$") if $CPAN::DEBUG; File::Path::rmtree("tmp-$$"); unless (mkdir "tmp-$$", 0755) { $CPAN::Frontend->unrecoverable_error(<safe_chdir("tmp-$$"); # # Unpack the goods # my $local_file = $self->{localfile}; my $ct = eval{CPAN::Tarzip->new($local_file)}; unless ($ct) { $self->{unwrapped} = CPAN::Distrostatus->new("NO"); delete $self->{build_dir}; return; } if ($local_file =~ /(\.tar\.(bz2|gz|Z)|\.tgz)(?!\n)\Z/i) { $self->{was_uncompressed}++ unless eval{$ct->gtest()}; $self->untar_me($ct); } elsif ( $local_file =~ /\.zip(?!\n)\Z/i ) { $self->unzip_me($ct); } else { $self->{was_uncompressed}++ unless $ct->gtest(); $local_file = $self->handle_singlefile($local_file); } # we are still in the tmp directory! # Let's check if the package has its own directory. my $dh = DirHandle->new(File::Spec->curdir) or Carp::croak("Couldn't opendir .: $!"); my @readdir = grep $_ !~ /^\.\.?(?!\n)\Z/s, $dh->read; ### MAC?? if (grep { $_ eq "pax_global_header" } @readdir) { $CPAN::Frontend->mywarn("Your (un)tar seems to have extracted a file named 'pax_global_header' from the tarball '$local_file'. This is almost certainly an error. Please upgrade your tar. I'll ignore this file for now. See also http://rt.cpan.org/Ticket/Display.html?id=38932\n"); $CPAN::Frontend->mysleep(5); @readdir = grep { $_ ne "pax_global_header" } @readdir; } $dh->close; my $tdir_base; my $from_dir; my @dirents; if (@readdir == 1 && -d $readdir[0]) { $tdir_base = $readdir[0]; $from_dir = File::Spec->catdir(File::Spec->curdir,$readdir[0]); my($mode) = (stat $from_dir)[2]; chmod $mode | 00755, $from_dir; # JONATHAN/Math-Calculus-TaylorSeries-0.1.tar.gz has 0644 my $dh2; unless ($dh2 = DirHandle->new($from_dir)) { my $why = sprintf ( "Couldn't opendir '%s', mode '%o': %s", $from_dir, $mode, $!, ); $CPAN::Frontend->mywarn("$why\n"); $self->{writemakefile} = CPAN::Distrostatus->new("NO -- $why"); return; } @dirents = grep $_ !~ /^\.\.?(?!\n)\Z/s, $dh2->read; ### MAC?? } else { my $userid = $self->cpan_userid; CPAN->debug("userid[$userid]"); if (!$userid or $userid eq "N/A") { $userid = "anon"; } $tdir_base = $userid; $from_dir = File::Spec->curdir; @dirents = @readdir; } my $packagedir; my $eexist = ($CPAN::META->has_usable("Errno") && defined &Errno::EEXIST) ? &Errno::EEXIST : undef; for(my $suffix = 0; ; $suffix++) { $packagedir = File::Spec->catdir($builddir, "$tdir_base-$suffix"); my $parent = $builddir; mkdir($packagedir, 0777) and last; if((defined($eexist) && $! != $eexist) || $suffix == 999) { $CPAN::Frontend->mydie("Cannot create directory $packagedir: $!\n"); } } my $f; for $f (@dirents) { # is already without "." and ".." my $from = File::Spec->catfile($from_dir,$f); my($mode) = (stat $from)[2]; chmod $mode | 00755, $from if -d $from; # OTTO/Pod-Trial-LinkImg-0.005.tgz my $to = File::Spec->catfile($packagedir,$f); unless (File::Copy::move($from,$to)) { my $err = $!; $from = File::Spec->rel2abs($from); $CPAN::Frontend->mydie( "Couldn't move $from to $to: $err; #82295? ". "CPAN::VERSION=$CPAN::VERSION; ". "File::Copy::VERSION=$File::Copy::VERSION; ". "$from " . (-e $from ? "exists; " : "does not exist; "). "$to " . (-e $to ? "exists; " : "does not exist; "). "cwd=" . CPAN::anycwd() . ";" ); } } $self->{build_dir} = $packagedir; $self->safe_chdir($builddir); File::Path::rmtree("tmp-$$"); $self->safe_chdir($packagedir); $self->_signature_business(); $self->safe_chdir($builddir); return($packagedir,$local_file); } #-> sub CPAN::Distribution::pick_meta_file ; sub pick_meta_file { my($self, $filter) = @_; $filter = '.' unless defined $filter; my $build_dir; unless ($build_dir = $self->{build_dir}) { # maybe permission on build_dir was missing $CPAN::Frontend->mywarn("Warning: cannot determine META.yml without a build_dir.\n"); return; } my $has_cm = $CPAN::META->has_usable("CPAN::Meta"); my $has_pcm = $CPAN::META->has_usable("Parse::CPAN::Meta"); my @choices; push @choices, 'MYMETA.json' if $has_cm; push @choices, 'MYMETA.yml' if $has_cm || $has_pcm; push @choices, 'META.json' if $has_cm; push @choices, 'META.yml' if $has_cm || $has_pcm; for my $file ( grep { /$filter/ } @choices ) { my $path = File::Spec->catfile( $build_dir, $file ); return $path if -f $path } return; } #-> sub CPAN::Distribution::parse_meta_yml ; sub parse_meta_yml { my($self, $yaml) = @_; $self->debug(sprintf("parse_meta_yml[%s]",$yaml||'undef')) if $CPAN::DEBUG; my $build_dir = $self->{build_dir} or die "PANIC: cannot parse yaml without a build_dir"; $yaml ||= File::Spec->catfile($build_dir,"META.yml"); $self->debug("meta[$yaml]") if $CPAN::DEBUG; return unless -f $yaml; my $early_yaml; eval { $CPAN::META->has_inst("Parse::CPAN::Meta") or die; die "Parse::CPAN::Meta yaml too old" unless $Parse::CPAN::Meta::VERSION >= "1.40"; # P::C::M returns last document in scalar context $early_yaml = Parse::CPAN::Meta::LoadFile($yaml); }; unless ($early_yaml) { eval { $early_yaml = CPAN->_yaml_loadfile($yaml)->[0]; }; } $self->debug(sprintf("yaml[%s]", $early_yaml || 'UNDEF')) if $CPAN::DEBUG; $self->debug($early_yaml) if $CPAN::DEBUG && $early_yaml; if (!ref $early_yaml or ref $early_yaml ne "HASH"){ # fix rt.cpan.org #95271 $CPAN::Frontend->mywarn("The content of '$yaml' is not a HASH reference. Cannot use it.\n"); return {}; } return $early_yaml || undef; } #-> sub CPAN::Distribution::satisfy_requires ; # return values: 1 means requirements are satisfied; # and 0 means not satisfied (and maybe queued) sub satisfy_requires { my ($self) = @_; $self->debug("Entering satisfy_requires") if $CPAN::DEBUG; if (my @prereq = $self->unsat_prereq("later")) { if ($CPAN::DEBUG){ require Data::Dumper; my $prereq = Data::Dumper->new(\@prereq)->Terse(1)->Indent(0)->Dump; $self->debug("unsatisfied[$prereq]"); } if ($prereq[0][0] eq "perl") { my $need = "requires perl '$prereq[0][1]'"; my $id = $self->pretty_id; $CPAN::Frontend->mywarn("$id $need; you have only $]; giving up\n"); $self->{make} = CPAN::Distrostatus->new("NO $need"); $self->store_persistent_state; die "[prereq] -- NOT OK\n"; } else { my $follow = eval { $self->follow_prereqs("later",@prereq); }; if (0) { } elsif ($follow) { return; # we need deps } elsif ($@ && ref $@ && $@->isa("CPAN::Exception::RecursiveDependency")) { $CPAN::Frontend->mywarn($@); die "[depend] -- NOT OK\n"; } } } return 1; } #-> sub CPAN::Distribution::satisfy_configure_requires ; # return values: 1 means configure_require is satisfied; # and 0 means not satisfied (and maybe queued) sub satisfy_configure_requires { my($self) = @_; $self->debug("Entering satisfy_configure_requires") if $CPAN::DEBUG; my $enable_configure_requires = 1; if (!$enable_configure_requires) { return 1; # if we return 1 here, everything is as before we introduced # configure_requires that means, things with # configure_requires simply fail, all others succeed } my @prereq = $self->unsat_prereq("configure_requires_later"); $self->debug(sprintf "configure_requires[%s]", join(",",map {join "/",@$_} @prereq)) if $CPAN::DEBUG; return 1 unless @prereq; $self->debug(\@prereq) if $CPAN::DEBUG; if ($self->{configure_requires_later}) { for my $k (sort keys %{$self->{configure_requires_later_for}||{}}) { if ($self->{configure_requires_later_for}{$k}>1) { my $type = ""; for my $p (@prereq) { if ($p->[0] eq $k) { $type = $p->[1]; } } $type = " $type" if $type; $CPAN::Frontend->mywarn("Warning: unmanageable(?) prerequisite $k$type"); sleep 1; } } } if ($prereq[0][0] eq "perl") { my $need = "requires perl '$prereq[0][1]'"; my $id = $self->pretty_id; $CPAN::Frontend->mywarn("$id $need; you have only $]; giving up\n"); $self->{make} = CPAN::Distrostatus->new("NO $need"); $self->store_persistent_state; return $self->goodbye("[prereq] -- NOT OK"); } else { my $follow = eval { $self->follow_prereqs("configure_requires_later", @prereq); }; if (0) { } elsif ($follow) { return; # we need deps } elsif ($@ && ref $@ && $@->isa("CPAN::Exception::RecursiveDependency")) { $CPAN::Frontend->mywarn($@); return $self->goodbye("[depend] -- NOT OK"); } else { return $self->goodbye("[configure_requires] -- NOT OK"); } } die "never reached"; } #-> sub CPAN::Distribution::choose_MM_or_MB ; sub choose_MM_or_MB { my($self) = @_; $self->satisfy_configure_requires() or return; my $local_file = $self->{localfile}; my($mpl) = File::Spec->catfile($self->{build_dir},"Makefile.PL"); my($mpl_exists) = -f $mpl; unless ($mpl_exists) { # NFS has been reported to have racing problems after the # renaming of a directory in some environments. # This trick helps. $CPAN::Frontend->mysleep(1); my $mpldh = DirHandle->new($self->{build_dir}) or Carp::croak("Couldn't opendir $self->{build_dir}: $!"); $mpl_exists = grep /^Makefile\.PL$/, $mpldh->read; $mpldh->close; } my $prefer_installer = "eumm"; # eumm|mb if (-f File::Spec->catfile($self->{build_dir},"Build.PL")) { if ($mpl_exists) { # they *can* choose if ($CPAN::META->has_inst("Module::Build")) { $prefer_installer = CPAN::HandleConfig->prefs_lookup( $self, q{prefer_installer} ); # M::B <= 0.35 left a DATA handle open that # causes problems upgrading M::B on Windows close *Module::Build::Version::DATA if fileno *Module::Build::Version::DATA; } } else { $prefer_installer = "mb"; } } if (lc($prefer_installer) eq "rand") { $prefer_installer = rand()<.5 ? "eumm" : "mb"; } if (lc($prefer_installer) eq "mb") { $self->{modulebuild} = 1; } elsif ($self->{archived} eq "patch") { # not an edge case, nothing to install for sure my $why = "A patch file cannot be installed"; $CPAN::Frontend->mywarn("Refusing to handle this file: $why\n"); $self->{writemakefile} = CPAN::Distrostatus->new("NO $why"); } elsif (! $mpl_exists) { $self->_edge_cases($mpl,$local_file); } if ($self->{build_dir} && $CPAN::Config->{build_dir_reuse} ) { $self->store_persistent_state; } return $self; } # see also reanimate_build_dir #-> CPAN::Distribution::store_persistent_state sub store_persistent_state { my($self) = @_; my $dir = $self->{build_dir}; unless (defined $dir && length $dir) { my $id = $self->id; $CPAN::Frontend->mywarnonce("build_dir of $id is not known, ". "will not store persistent state\n"); return; } # self-build-dir my $sbd = Cwd::realpath( File::Spec->catdir($dir, File::Spec->updir ()) ); # config-build-dir my $cbd = Cwd::realpath( # the catdir is a workaround for bug https://rt.cpan.org/Ticket/Display.html?id=101283 File::Spec->catdir($CPAN::Config->{build_dir}, File::Spec->curdir()) ); unless ($sbd eq $cbd) { $CPAN::Frontend->mywarnonce("Directory '$dir' not below $CPAN::Config->{build_dir}, ". "will not store persistent state\n"); return; } my $file = sprintf "%s.yml", $dir; my $yaml_module = CPAN::_yaml_module(); if ($CPAN::META->has_inst($yaml_module)) { CPAN->_yaml_dumpfile( $file, { time => time, perl => CPAN::_perl_fingerprint(), distribution => $self, } ); } else { $CPAN::Frontend->myprintonce("'$yaml_module' not installed, ". "will not store persistent state\n"); } } #-> CPAN::Distribution::try_download sub try_download { my($self,$patch) = @_; my $norm = $self->normalize($patch); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,$norm), ); $self->debug("Doing localize") if $CPAN::DEBUG; return CPAN::FTP->localize("authors/id/$norm", $local_wanted); } { my $stdpatchargs = ""; #-> CPAN::Distribution::patch sub patch { my($self) = @_; $self->debug("checking patches id[$self->{ID}]") if $CPAN::DEBUG; my $patches = $self->prefs->{patches}; $patches ||= ""; $self->debug("patches[$patches]") if $CPAN::DEBUG; if ($patches) { return unless @$patches; $self->safe_chdir($self->{build_dir}); CPAN->debug("patches[$patches]") if $CPAN::DEBUG; my $patchbin = $CPAN::Config->{patch}; unless ($patchbin && length $patchbin) { $CPAN::Frontend->mydie("No external patch command configured\n\n". "Please run 'o conf init /patch/'\n\n"); } unless (MM->maybe_command($patchbin)) { $CPAN::Frontend->mydie("No external patch command available\n\n". "Please run 'o conf init /patch/'\n\n"); } $patchbin = CPAN::HandleConfig->safe_quote($patchbin); local $ENV{PATCH_GET} = 0; # formerly known as -g0 unless ($stdpatchargs) { my $system = "$patchbin --version |"; local *FH; open FH, $system or die "Could not fork '$system': $!"; local $/ = "\n"; my $pversion; PARSEVERSION: while () { if (/^patch\s+([\d\.]+)/) { $pversion = $1; last PARSEVERSION; } } if ($pversion) { $stdpatchargs = "-N --fuzz=3"; } else { $stdpatchargs = "-N"; } } my $countedpatches = @$patches == 1 ? "1 patch" : (scalar @$patches . " patches"); $CPAN::Frontend->myprint("Applying $countedpatches:\n"); my $patches_dir = $CPAN::Config->{patches_dir}; for my $patch (@$patches) { if ($patches_dir && !File::Spec->file_name_is_absolute($patch)) { my $f = File::Spec->catfile($patches_dir, $patch); $patch = $f if -f $f; } unless (-f $patch) { CPAN->debug("not on disk: patch[$patch]") if $CPAN::DEBUG; if (my $trydl = $self->try_download($patch)) { $patch = $trydl; } else { my $fail = "Could not find patch '$patch'"; $CPAN::Frontend->mywarn("$fail; cannot continue\n"); $self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail"); delete $self->{build_dir}; return; } } $CPAN::Frontend->myprint(" $patch\n"); my $readfh = CPAN::Tarzip->TIEHANDLE($patch); my $pcommand; my($ppp,$pfiles) = $self->_patch_p_parameter($readfh); if ($ppp eq "applypatch") { $pcommand = "$CPAN::Config->{applypatch} -verbose"; } else { my $thispatchargs = join " ", $stdpatchargs, $ppp; $pcommand = "$patchbin $thispatchargs"; require Config; # usually loaded from CPAN.pm if ($Config::Config{osname} eq "solaris") { # native solaris patch cannot patch readonly files for my $file (@{$pfiles||[]}) { my @stat = stat $file or next; chmod $stat[2] | 0600, $file; # may fail } } } $readfh = CPAN::Tarzip->TIEHANDLE($patch); # open again my $writefh = FileHandle->new; $CPAN::Frontend->myprint(" $pcommand\n"); unless (open $writefh, "|$pcommand") { my $fail = "Could not fork '$pcommand'"; $CPAN::Frontend->mywarn("$fail; cannot continue\n"); $self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail"); delete $self->{build_dir}; return; } binmode($writefh); while (my $x = $readfh->READLINE) { print $writefh $x; } unless (close $writefh) { my $fail = "Could not apply patch '$patch'"; $CPAN::Frontend->mywarn("$fail; cannot continue\n"); $self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail"); delete $self->{build_dir}; return; } } $self->{patched}++; } return 1; } } # may return # - "applypatch" # - ("-p0"|"-p1", $files) sub _patch_p_parameter { my($self,$fh) = @_; my $cnt_files = 0; my $cnt_p0files = 0; my @files; local($_); while ($_ = $fh->READLINE) { if ( $CPAN::Config->{applypatch} && /\#\#\#\# ApplyPatch data follows \#\#\#\#/ ) { return "applypatch" } next unless /^[\*\+]{3}\s(\S+)/; my $file = $1; push @files, $file; $cnt_files++; $cnt_p0files++ if -f $file; CPAN->debug("file[$file]cnt_files[$cnt_files]cnt_p0files[$cnt_p0files]") if $CPAN::DEBUG; } return "-p1" unless $cnt_files; my $opt_p = $cnt_files==$cnt_p0files ? "-p0" : "-p1"; return ($opt_p, \@files); } #-> sub CPAN::Distribution::_edge_cases # with "configure" or "Makefile" or single file scripts sub _edge_cases { my($self,$mpl,$local_file) = @_; $self->debug(sprintf("makefilepl[%s]anycwd[%s]", $mpl, CPAN::anycwd(), )) if $CPAN::DEBUG; my $build_dir = $self->{build_dir}; my($configure) = File::Spec->catfile($build_dir,"Configure"); if (-f $configure) { # do we have anything to do? $self->{configure} = $configure; } elsif (-f File::Spec->catfile($build_dir,"Makefile")) { $CPAN::Frontend->mywarn(qq{ Package comes with a Makefile and without a Makefile.PL. We\'ll try to build it with that Makefile then. }); $self->{writemakefile} = CPAN::Distrostatus->new("YES"); $CPAN::Frontend->mysleep(2); } else { my $cf = $self->called_for || "unknown"; if ($cf =~ m|/|) { $cf =~ s|.*/||; $cf =~ s|\W.*||; } $cf =~ s|[/\\:]||g; # risk of filesystem damage $cf = "unknown" unless length($cf); if (my $crud = $self->_contains_crud($build_dir)) { my $why = qq{Package contains $crud; not recognized as a perl package, giving up}; $CPAN::Frontend->mywarn("$why\n"); $self->{writemakefile} = CPAN::Distrostatus->new(qq{NO -- $why}); return; } $CPAN::Frontend->mywarn(qq{Package seems to come without Makefile.PL. (The test -f "$mpl" returned false.) Writing one on our own (setting NAME to $cf)\a\n}); $self->{had_no_makefile_pl}++; $CPAN::Frontend->mysleep(3); # Writing our own Makefile.PL my $exefile_stanza = ""; if ($self->{archived} eq "maybe_pl") { $exefile_stanza = $self->_exefile_stanza($build_dir,$local_file); } my $fh = FileHandle->new; $fh->open(">$mpl") or Carp::croak("Could not open >$mpl: $!"); $fh->print( qq{# This Makefile.PL has been autogenerated by the module CPAN.pm # because there was no Makefile.PL supplied. # Autogenerated on: }.scalar localtime().qq{ use ExtUtils::MakeMaker; WriteMakefile( NAME => q[$cf],$exefile_stanza ); }); $fh->close; } } #-> CPAN;:Distribution::_contains_crud sub _contains_crud { my($self,$dir) = @_; my(@dirs, $dh, @files); opendir $dh, $dir or return; my $dirent; for $dirent (readdir $dh) { next if $dirent =~ /^\.\.?$/; my $path = File::Spec->catdir($dir,$dirent); if (-d $path) { push @dirs, $dirent; } elsif (-f $path) { push @files, $dirent; } } if (@dirs && @files) { return "both files[@files] and directories[@dirs]"; } elsif (@files > 2) { return "several files[@files] but no Makefile.PL or Build.PL"; } return; } #-> CPAN;:Distribution::_exefile_stanza sub _exefile_stanza { my($self,$build_dir,$local_file) = @_; my $fh = FileHandle->new; my $script_file = File::Spec->catfile($build_dir,$local_file); $fh->open($script_file) or Carp::croak("Could not open script '$script_file': $!"); local $/ = "\n"; # parse name and prereq my($state) = "poddir"; my($name, $prereq) = ("", ""); while (<$fh>) { if ($state eq "poddir" && /^=head\d\s+(\S+)/) { if ($1 eq 'NAME') { $state = "name"; } elsif ($1 eq 'PREREQUISITES') { $state = "prereq"; } } elsif ($state =~ m{^(name|prereq)$}) { if (/^=/) { $state = "poddir"; } elsif (/^\s*$/) { # nop } elsif ($state eq "name") { if ($name eq "") { ($name) = /^(\S+)/; $state = "poddir"; } } elsif ($state eq "prereq") { $prereq .= $_; } } elsif (/^=cut\b/) { last; } } $fh->close; for ($name) { s{.*<}{}; # strip X<...> s{>.*}{}; } chomp $prereq; $prereq = join " ", split /\s+/, $prereq; my($PREREQ_PM) = join("\n", map { s{.*<}{}; # strip X<...> s{>.*}{}; if (/[\s\'\"]/) { # prose? } else { s/[^\w:]$//; # period? " "x28 . "'$_' => 0,"; } } split /\s*,\s*/, $prereq); if ($name) { my $to_file = File::Spec->catfile($build_dir, $name); rename $script_file, $to_file or die "Can't rename $script_file to $to_file: $!"; } return " EXE_FILES => ['$name'], PREREQ_PM => { $PREREQ_PM }, "; } #-> CPAN::Distribution::_signature_business sub _signature_business { my($self) = @_; my $check_sigs = CPAN::HandleConfig->prefs_lookup($self, q{check_sigs}); if ($check_sigs) { if ($CPAN::META->has_inst("Module::Signature")) { if (-f "SIGNATURE") { $self->debug("Module::Signature is installed, verifying") if $CPAN::DEBUG; my $rv = Module::Signature::verify(); if ($rv != Module::Signature::SIGNATURE_OK() and $rv != Module::Signature::SIGNATURE_MISSING()) { $CPAN::Frontend->mywarn( qq{\nSignature invalid for }. qq{distribution file. }. qq{Please investigate.\n\n} ); my $wrap = sprintf(qq{I'd recommend removing %s. Some error occurred }. qq{while checking its signature, so it could }. qq{be invalid. Maybe you have configured }. qq{your 'urllist' with a bad URL. Please check this }. qq{array with 'o conf urllist' and retry. Or }. qq{examine the distribution in a subshell. Try look %s and run cpansign -v }, $self->{localfile}, $self->pretty_id, ); $self->{signature_verify} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(Text::Wrap::wrap("","",$wrap)); $CPAN::Frontend->mysleep(5) if $CPAN::Frontend->can("mysleep"); } else { $self->{signature_verify} = CPAN::Distrostatus->new("YES"); $self->debug("Module::Signature has verified") if $CPAN::DEBUG; } } else { $CPAN::Frontend->mywarn(qq{Package came without SIGNATURE\n\n}); } } else { $self->debug("Module::Signature is NOT installed") if $CPAN::DEBUG; } } } #-> CPAN::Distribution::untar_me ; sub untar_me { my($self,$ct) = @_; $self->{archived} = "tar"; my $result = eval { $ct->untar() }; if ($result) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { # unfortunately we have no $@ here, Tarzip is using mydie which dies with "\n" $self->{unwrapped} = CPAN::Distrostatus->new("NO -- untar failed"); } } # CPAN::Distribution::unzip_me ; sub unzip_me { my($self,$ct) = @_; $self->{archived} = "zip"; if (eval { $ct->unzip() }) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- unzip failed during unzip"); } return; } sub handle_singlefile { my($self,$local_file) = @_; if ( $local_file =~ /\.pm(\.(gz|Z))?(?!\n)\Z/ ) { $self->{archived} = "pm"; } elsif ( $local_file =~ /\.patch(\.(gz|bz2))?(?!\n)\Z/ ) { $self->{archived} = "patch"; } else { $self->{archived} = "maybe_pl"; } my $to = File::Basename::basename($local_file); if ($to =~ s/\.(gz|Z)(?!\n)\Z//) { if (eval{CPAN::Tarzip->new($local_file)->gunzip($to)}) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- uncompressing failed"); } } else { if (File::Copy::cp($local_file,".")) { $self->{unwrapped} = CPAN::Distrostatus->new("YES"); } else { $self->{unwrapped} = CPAN::Distrostatus->new("NO -- copying failed"); } } return $to; } #-> sub CPAN::Distribution::new ; sub new { my($class,%att) = @_; # $CPAN::META->{cachemgr} ||= CPAN::CacheMgr->new(); my $this = { %att }; return bless $this, $class; } #-> sub CPAN::Distribution::look ; sub look { my($self) = @_; if ($^O eq 'MacOS') { $self->Mac::BuildTools::look; return; } if ( $CPAN::Config->{'shell'} ) { $CPAN::Frontend->myprint(qq{ Trying to open a subshell in the build directory... }); } else { $CPAN::Frontend->myprint(qq{ Your configuration does not define a value for subshells. Please define it with "o conf shell " }); return; } my $dist = $self->id; my $dir; unless ($dir = $self->dir) { $self->get; } unless ($dir ||= $self->dir) { $CPAN::Frontend->mywarn(qq{ Could not determine which directory to use for looking at $dist. }); return; } my $pwd = CPAN::anycwd(); $self->safe_chdir($dir); $CPAN::Frontend->myprint(qq{Working directory is $dir\n}); { local $ENV{CPAN_SHELL_LEVEL} = $ENV{CPAN_SHELL_LEVEL}||0; $ENV{CPAN_SHELL_LEVEL} += 1; my $shell = CPAN::HandleConfig->safe_quote($CPAN::Config->{'shell'}); local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : ""; # local $ENV{PERL_USE_UNSAFE_INC} = exists $ENV{PERL_USE_UNSAFE_INC} ? $ENV{PERL_USE_UNSAFE_INC} : 1; # look $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls unless (system($shell) == 0) { my $code = $? >> 8; $CPAN::Frontend->mywarn("Subprocess shell exit code $code\n"); } } $self->safe_chdir($pwd); } # CPAN::Distribution::cvs_import ; sub cvs_import { my($self) = @_; $self->get; my $dir = $self->dir; my $package = $self->called_for; my $module = $CPAN::META->instance('CPAN::Module', $package); my $version = $module->cpan_version; my $userid = $self->cpan_userid; my $cvs_dir = (split /\//, $dir)[-1]; $cvs_dir =~ s/-\d+[^-]+(?!\n)\Z//; my $cvs_root = $CPAN::Config->{cvsroot} || $ENV{CVSROOT}; my $cvs_site_perl = $CPAN::Config->{cvs_site_perl} || $ENV{CVS_SITE_PERL}; if ($cvs_site_perl) { $cvs_dir = "$cvs_site_perl/$cvs_dir"; } my $cvs_log = qq{"imported $package $version sources"}; $version =~ s/\./_/g; # XXX cvs: undocumented and unclear how it was meant to work my @cmd = ('cvs', '-d', $cvs_root, 'import', '-m', $cvs_log, "$cvs_dir", $userid, "v$version"); my $pwd = CPAN::anycwd(); chdir($dir) or $CPAN::Frontend->mydie(qq{Could not chdir to "$dir": $!}); $CPAN::Frontend->myprint(qq{Working directory is $dir\n}); $CPAN::Frontend->myprint(qq{@cmd\n}); system(@cmd) == 0 or # XXX cvs $CPAN::Frontend->mydie("cvs import failed"); chdir($pwd) or $CPAN::Frontend->mydie(qq{Could not chdir to "$pwd": $!}); } #-> sub CPAN::Distribution::readme ; sub readme { my($self) = @_; my($dist) = $self->id; my($sans,$suffix) = $dist =~ /(.+)\.(tgz|tar[\._-]gz|tar\.Z|zip)$/; $self->debug("sans[$sans] suffix[$suffix]\n") if $CPAN::DEBUG; my($local_file); my($local_wanted) = File::Spec->catfile( $CPAN::Config->{keep_source_where}, "authors", "id", split(/\//,"$sans.readme"), ); my $readme = "authors/id/$sans.readme"; $self->debug("Doing localize for '$readme'") if $CPAN::DEBUG; $local_file = CPAN::FTP->localize($readme, $local_wanted) or $CPAN::Frontend->mydie(qq{No $sans.readme found}); if ($^O eq 'MacOS') { Mac::BuildTools::launch_file($local_file); return; } my $fh_pager = FileHandle->new; local($SIG{PIPE}) = "IGNORE"; my $pager = $CPAN::Config->{'pager'} || "cat"; $fh_pager->open("|$pager") or die "Could not open pager $pager\: $!"; my $fh_readme = FileHandle->new; $fh_readme->open($local_file) or $CPAN::Frontend->mydie(qq{Could not open "$local_file": $!}); $CPAN::Frontend->myprint(qq{ Displaying file $local_file with pager "$pager" }); $fh_pager->print(<$fh_readme>); $fh_pager->close; } #-> sub CPAN::Distribution::verifyCHECKSUM ; sub verifyCHECKSUM { my($self) = @_; EXCUSE: { my @e; $self->{CHECKSUM_STATUS} ||= ""; $self->{CHECKSUM_STATUS} eq "OK" and push @e, "Checksum was ok"; $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; } my($lc_want,$lc_file,@local,$basename); @local = split(/\//,$self->id); pop @local; push @local, "CHECKSUMS"; $lc_want = File::Spec->catfile($CPAN::Config->{keep_source_where}, "authors", "id", @local); local($") = "/"; if (my $size = -s $lc_want) { $self->debug("lc_want[$lc_want]size[$size]") if $CPAN::DEBUG; my @stat = stat $lc_want; my $epoch_starting_support_of_cpan_path = 1637471530; if ($stat[9] >= $epoch_starting_support_of_cpan_path) { if ($self->CHECKSUM_check_file($lc_want, 1)) { return $self->{CHECKSUM_STATUS} = "OK"; } } else { unlink $lc_want; } } $lc_file = CPAN::FTP->localize("authors/id/@local", $lc_want,1); unless ($lc_file) { $CPAN::Frontend->myprint("Trying $lc_want.gz\n"); $local[-1] .= ".gz"; $lc_file = CPAN::FTP->localize("authors/id/@local", "$lc_want.gz",1); if ($lc_file) { $lc_file =~ s/\.gz(?!\n)\Z//; eval{CPAN::Tarzip->new("$lc_file.gz")->gunzip($lc_file)}; } else { return; } } if ($self->CHECKSUM_check_file($lc_file)) { return $self->{CHECKSUM_STATUS} = "OK"; } } #-> sub CPAN::Distribution::SIG_check_file ; sub SIG_check_file { my($self,$chk_file) = @_; my $rv = eval { Module::Signature::_verify($chk_file) }; if ($rv eq Module::Signature::CANNOT_VERIFY()) { $CPAN::Frontend->myprint(qq{\nSignature for }. qq{file $chk_file could not be verified for an unknown reason. }. $self->as_string. qq{Module::Signature verification returned value $rv\n\n} ); my $wrap = qq{The manual says for this case: Cannot verify the OpenPGP signature, maybe due to the lack of a network connection to the key server, or if neither gnupg nor Crypt::OpenPGP exists on the system. You probably want to analyse the situation and if you cannot fix it you will have to decide whether you want to stop this session or you want to turn off signature verification. The latter would be done with the command 'o conf init check_sigs'}; $CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap)); } if ($rv == Module::Signature::SIGNATURE_OK()) { $CPAN::Frontend->myprint("Signature for $chk_file ok\n"); return $self->{SIG_STATUS} = "OK"; } else { $CPAN::Frontend->mywarn(qq{\nSignature invalid for }. qq{file $chk_file. }. qq{Please investigate.\n\n}. $self->as_string. qq{Module::Signature verification returned value $rv\n\n} ); my $wrap = qq{I\'d recommend removing $chk_file. Its signature is invalid. Maybe you have configured your 'urllist' with a bad URL. Please check this array with 'o conf urllist', and retry.}; $CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap)); } } #-> sub CPAN::Distribution::CHECKSUM_check_file ; # sloppy is 1 when we have an old checksums file that maybe is good # enough sub CHECKSUM_check_file { my($self,$chk_file,$sloppy) = @_; my($cksum,$file,$basename); $sloppy ||= 0; $self->debug("chk_file[$chk_file]sloppy[$sloppy]") if $CPAN::DEBUG; my $check_sigs = CPAN::HandleConfig->prefs_lookup($self, q{check_sigs}); if ($check_sigs) { if ($CPAN::META->has_inst("Module::Signature")) { $self->debug("Module::Signature is installed, verifying") if $CPAN::DEBUG; $self->SIG_check_file($chk_file); } else { $self->debug("Module::Signature is NOT installed") if $CPAN::DEBUG; } } $file = $self->{localfile}; $basename = File::Basename::basename($file); my($signed_data); my $fh = FileHandle->new; if ($check_sigs) { my $tempdir; if ($CPAN::META->has_usable("File::Temp")) { $tempdir = File::Temp::tempdir("CHECKSUMS-XXXX", CLEANUP => 1, DIR => "/tmp" ); } else { $tempdir = File::Spec->catdir(File::Spec->tmpdir, "CHECKSUMS-$$"); File::Path::mkpath($tempdir); } my $tempfile = File::Spec->catfile($tempdir, "CHECKSUMS.$$"); unlink $tempfile; # ignore missing file my $devnull = File::Spec->devnull; my $gpg = $CPAN::Config->{gpg} or $CPAN::Frontend->mydie("Your configuration suggests that you do not have 'gpg' installed. This is needed to verify checksums with the config variable 'check_sigs' on. Please configure it with 'o conf init gpg'"); my $system = qq{"$gpg" --verify --batch --no-tty --output "$tempfile" "$chk_file" 2> "$devnull"}; 0 == system $system or $CPAN::Frontend->mydie("gpg run was failing, cannot continue: $system"); open $fh, $tempfile or $CPAN::Frontend->mydie("Could not open $tempfile: $!"); local $/; $signed_data = <$fh>; close $fh; File::Path::rmtree($tempdir); } else { my $fh = FileHandle->new; if (open $fh, $chk_file) { local($/); $signed_data = <$fh>; } else { $CPAN::Frontend->mydie("Could not open $chk_file for reading"); } close $fh; } $signed_data =~ s/\015?\012/\n/g; my($compmt) = Safe->new(); $cksum = $compmt->reval($signed_data); if ($@) { rename $chk_file, "$chk_file.bad"; Carp::confess($@) if $@; } if (! ref $cksum or ref $cksum ne "HASH") { $CPAN::Frontend->mywarn(qq{ Warning: checksum file '$chk_file' broken. When trying to read that file I expected to get a hash reference for further processing, but got garbage instead. }); my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed nonetheless?", "no"); $answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n"); $self->{CHECKSUM_STATUS} = "NIL -- CHECKSUMS file broken"; return; } elsif (exists $cksum->{$basename} && ! exists $cksum->{$basename}{cpan_path}) { $CPAN::Frontend->mywarn(qq{ Warning: checksum file '$chk_file' not conforming. The cksum does not contain the key 'cpan_path' for '$basename'. }); my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed nonetheless?", "no"); $answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n"); $self->{CHECKSUM_STATUS} = "NIL -- CHECKSUMS file without cpan_path"; return; } elsif (exists $cksum->{$basename} && substr($self->{ID},0,length($cksum->{$basename}{cpan_path})) ne $cksum->{$basename}{cpan_path}) { $CPAN::Frontend->mywarn(qq{ Warning: checksum file not matching path '$self->{ID}'. The cksum contain the key 'cpan_path=$cksum->{$basename}{cpan_path}' which does not match the ID of the distribution '$self->{ID}'. Something's suspicious might be going on here. Please investigate. }); my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed nonetheless?", "no"); $answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n"); $self->{CHECKSUM_STATUS} = "NIL -- CHECKSUMS non-matching cpan_path vs. ID"; return; } elsif (exists $cksum->{$basename}{sha256}) { $self->debug("Found checksum for $basename:" . "$cksum->{$basename}{sha256}\n") if $CPAN::DEBUG; open($fh, $file); binmode $fh; my $eq = $self->eq_CHECKSUM($fh,$cksum->{$basename}{sha256}); $fh->close; $fh = CPAN::Tarzip->TIEHANDLE($file); unless ($eq) { my $dg = Digest::SHA->new(256); my($data,$ref); $ref = \$data; while ($fh->READ($ref, 4096) > 0) { $dg->add($data); } my $hexdigest = $dg->hexdigest; $eq += $hexdigest eq $cksum->{$basename}{'sha256-ungz'}; } if ($eq) { $CPAN::Frontend->myprint("Checksum for $file ok\n"); return $self->{CHECKSUM_STATUS} = "OK"; } else { $CPAN::Frontend->myprint(qq{\nChecksum mismatch for }. qq{distribution file. }. qq{Please investigate.\n\n}. $self->as_string, $CPAN::META->instance( 'CPAN::Author', $self->cpan_userid )->as_string); my $wrap = qq{I\'d recommend removing $file. Its checksum is incorrect. Maybe you have configured your 'urllist' with a bad URL. Please check this array with 'o conf urllist', and retry.}; $CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap)); # former versions just returned here but this seems a # serious threat that deserves a die # $CPAN::Frontend->myprint("\n\n"); # sleep 3; # return; } # close $fh if fileno($fh); } else { return if $sloppy; unless ($self->{CHECKSUM_STATUS}) { $CPAN::Frontend->mywarn(qq{ Warning: No checksum for $basename in $chk_file. The cause for this may be that the file is very new and the checksum has not yet been calculated, but it may also be that something is going awry right now. }); my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed?", "yes"); $answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n"); } $self->{CHECKSUM_STATUS} = "NIL -- distro not in CHECKSUMS file"; return; } } #-> sub CPAN::Distribution::eq_CHECKSUM ; sub eq_CHECKSUM { my($self,$fh,$expect) = @_; if ($CPAN::META->has_inst("Digest::SHA")) { my $dg = Digest::SHA->new(256); my($data); while (read($fh, $data, 4096)) { $dg->add($data); } my $hexdigest = $dg->hexdigest; # warn "fh[$fh] hex[$hexdigest] aexp[$expectMD5]"; return $hexdigest eq $expect; } return 1; } #-> sub CPAN::Distribution::force ; # Both CPAN::Modules and CPAN::Distributions know if "force" is in # effect by autoinspection, not by inspecting a global variable. One # of the reason why this was chosen to work that way was the treatment # of dependencies. They should not automatically inherit the force # status. But this has the downside that ^C and die() will return to # the prompt but will not be able to reset the force_update # attributes. We try to correct for it currently in the read_metadata # routine, and immediately before we check for a Signal. I hope this # works out in one of v1.57_53ff # "Force get forgets previous error conditions" #-> sub CPAN::Distribution::fforce ; sub fforce { my($self, $method) = @_; $self->force($method,1); } #-> sub CPAN::Distribution::force ; sub force { my($self, $method,$fforce) = @_; my %phase_map = ( get => [ "unwrapped", "build_dir", "archived", "localfile", "CHECKSUM_STATUS", "signature_verify", "prefs", "prefs_file", "prefs_file_doc", "cleanup_after_install_done", ], make => [ "writemakefile", "make", "modulebuild", "prereq_pm", "cleanup_after_install_done", ], test => [ "badtestcnt", "make_test", "cleanup_after_install_done", ], install => [ "install", "cleanup_after_install_done", ], unknown => [ "reqtype", "yaml_content", "cleanup_after_install_done", ], ); my $methodmatch = 0; my $ldebug = 0; PHASE: for my $phase (qw(unknown get make test install)) { # order matters $methodmatch = 1 if $fforce || ($method && $phase eq $method); next unless $methodmatch; ATTRIBUTE: for my $att (@{$phase_map{$phase}}) { if ($phase eq "get") { if (substr($self->id,-1,1) eq "." && $att =~ /(unwrapped|build_dir|archived)/ ) { # cannot be undone for local distros next ATTRIBUTE; } if ($att eq "build_dir" && $self->{build_dir} && $CPAN::META->{is_tested} ) { delete $CPAN::META->{is_tested}{$self->{build_dir}}; } } elsif ($phase eq "test") { if ($att eq "make_test" && $self->{make_test} && $self->{make_test}{COMMANDID} && $self->{make_test}{COMMANDID} == $CPAN::CurrentCommandId ) { # endless loop too likely next ATTRIBUTE; } } delete $self->{$att}; if ($ldebug || $CPAN::DEBUG) { # local $CPAN::DEBUG = 16; # Distribution CPAN->debug(sprintf "id[%s]phase[%s]att[%s]", $self->id, $phase, $att); } } } if ($method && $method =~ /make|test|install/) { $self->{force_update} = 1; # name should probably have been force_install } } #-> sub CPAN::Distribution::notest ; sub notest { my($self, $method) = @_; # $CPAN::Frontend->mywarn("XDEBUG: set notest for $self $method"); $self->{"notest"}++; # name should probably have been force_install } #-> sub CPAN::Distribution::unnotest ; sub unnotest { my($self) = @_; # warn "XDEBUG: deleting notest"; delete $self->{notest}; } #-> sub CPAN::Distribution::unforce ; sub unforce { my($self) = @_; delete $self->{force_update}; } #-> sub CPAN::Distribution::isa_perl ; sub isa_perl { my($self) = @_; my $file = File::Basename::basename($self->id); if ($file =~ m{ ^ perl ( -(5\.\d+\.\d+) | (5)[._-](00[0-5](?:_[0-4][0-9])?) ) \.tar[._-](?:gz|bz2) (?!\n)\Z }xs) { my $perl_version; if ($2) { $perl_version = $2; } else { $perl_version = "$3.$4"; } return $perl_version; } elsif ($self->cpan_comment && $self->cpan_comment =~ /isa_perl\(.+?\)/) { return $1; } } #-> sub CPAN::Distribution::perl ; sub perl { my ($self) = @_; if (! $self) { use Carp qw(carp); carp __PACKAGE__ . "::perl was called without parameters."; } return CPAN::HandleConfig->safe_quote($CPAN::Perl); } #-> sub CPAN::Distribution::shortcut_prepare ; # return values: undef means don't shortcut; 0 means shortcut as fail; # and 1 means shortcut as success sub shortcut_prepare { my ($self) = @_; $self->debug("checking archive type[$self->{ID}]") if $CPAN::DEBUG; if (!$self->{archived} || $self->{archived} eq "NO") { return $self->goodbye("Is neither a tar nor a zip archive."); } $self->debug("checking unwrapping[$self->{ID}]") if $CPAN::DEBUG; if (!$self->{unwrapped} || ( UNIVERSAL::can($self->{unwrapped},"failed") ? $self->{unwrapped}->failed : $self->{unwrapped} =~ /^NO/ )) { return $self->goodbye("Had problems unarchiving. Please build manually"); } $self->debug("checking signature[$self->{ID}]") if $CPAN::DEBUG; if ( ! $self->{force_update} && exists $self->{signature_verify} && ( UNIVERSAL::can($self->{signature_verify},"failed") ? $self->{signature_verify}->failed : $self->{signature_verify} =~ /^NO/ ) ) { return $self->goodbye("Did not pass the signature test."); } $self->debug("checking writemakefile[$self->{ID}]") if $CPAN::DEBUG; if ($self->{writemakefile}) { if ( UNIVERSAL::can($self->{writemakefile},"failed") ? $self->{writemakefile}->failed : $self->{writemakefile} =~ /^NO/ ) { # XXX maybe a retry would be in order? my $err = UNIVERSAL::can($self->{writemakefile},"text") ? $self->{writemakefile}->text : $self->{writemakefile}; $err =~ s/^NO\s*(--\s+)?//; $err ||= "Had some problem writing Makefile"; $err .= ", not re-running"; return $self->goodbye($err); } else { return $self->success("Has already been prepared"); } } $self->debug("checking configure_requires_later[$self->{ID}]") if $CPAN::DEBUG; if( my $later = $self->{configure_requires_later} ) { # see also undelay return $self->goodbye($later); } return undef; # no shortcut } sub prepare { my ($self) = @_; $self->get or return; if ( defined( my $sc = $self->shortcut_prepare) ) { return $sc; } local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : ""; local $ENV{PERL_USE_UNSAFE_INC} = exists $ENV{PERL_USE_UNSAFE_INC} && defined $ENV{PERL_USE_UNSAFE_INC} ? $ENV{PERL_USE_UNSAFE_INC} : 1; # prepare $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls if ($CPAN::Signal) { delete $self->{force_update}; return; } my $builddir = $self->dir or $CPAN::Frontend->mydie("PANIC: Cannot determine build directory\n"); unless (chdir $builddir) { $CPAN::Frontend->mywarn("Couldn't chdir to '$builddir': $!"); return; } if ($CPAN::Signal) { delete $self->{force_update}; return; } $self->debug("Changed directory to $builddir") if $CPAN::DEBUG; local $ENV{PERL_AUTOINSTALL} = $ENV{PERL_AUTOINSTALL} || ''; local $ENV{PERL_EXTUTILS_AUTOINSTALL} = $ENV{PERL_EXTUTILS_AUTOINSTALL} || ''; $self->choose_MM_or_MB or return; my $configurator = $self->{configure} ? "Configure" : $self->{modulebuild} ? "Build.PL" : "Makefile.PL"; $CPAN::Frontend->myprint("Configuring ".$self->id." with $configurator\n"); if ($CPAN::Config->{prerequisites_policy} eq "follow") { $ENV{PERL_AUTOINSTALL} ||= "--defaultdeps"; $ENV{PERL_EXTUTILS_AUTOINSTALL} ||= "--defaultdeps"; } my $system; my $pl_commandline; if ($self->prefs->{pl}) { $pl_commandline = $self->prefs->{pl}{commandline}; } local $ENV{PERL} = defined $ENV{PERL}? $ENV{PERL} : $^X; local $ENV{PERL5_CPAN_IS_EXECUTING} = $ENV{PERL5_CPAN_IS_EXECUTING} || ''; local $ENV{PERL_MM_USE_DEFAULT} = 1 if $CPAN::Config->{use_prompt_default}; local $ENV{NONINTERACTIVE_TESTING} = 1 if $CPAN::Config->{use_prompt_default}; if ($pl_commandline) { $system = $pl_commandline; $ENV{PERL} = $^X; } elsif ($self->{'configure'}) { $system = $self->{'configure'}; } elsif ($self->{modulebuild}) { my($perl) = $self->perl or die "Couldn\'t find executable perl\n"; my $mbuildpl_arg = $self->_make_phase_arg("pl"); $system = sprintf("%s Build.PL%s", $perl, $mbuildpl_arg ? " $mbuildpl_arg" : "", ); } else { my($perl) = $self->perl or die "Couldn\'t find executable perl\n"; my $switch = ""; # This needs a handler that can be turned on or off: # $switch = "-MExtUtils::MakeMaker ". # "-Mops=:default,:filesys_read,:filesys_open,require,chdir" # if $] > 5.00310; my $makepl_arg = $self->_make_phase_arg("pl"); $ENV{PERL5_CPAN_IS_EXECUTING} = File::Spec->catfile($self->{build_dir}, "Makefile.PL"); $system = sprintf("%s%s Makefile.PL%s", $perl, $switch ? " $switch" : "", $makepl_arg ? " $makepl_arg" : "", ); } my $pl_env; if ($self->prefs->{pl}) { $pl_env = $self->prefs->{pl}{env}; } local @ENV{keys %$pl_env} = values %$pl_env if $pl_env; if (exists $self->{writemakefile}) { } else { local($SIG{ALRM}) = sub { die "inactivity_timeout reached\n" }; my($ret,$pid,$output); $@ = ""; my $go_via_alarm; if ($CPAN::Config->{inactivity_timeout}) { require Config; if ($Config::Config{d_alarm} && $Config::Config{d_alarm} eq "define" ) { $go_via_alarm++ } else { $CPAN::Frontend->mywarn("Warning: you have configured the config ". "variable 'inactivity_timeout' to ". "'$CPAN::Config->{inactivity_timeout}'. But ". "on this machine the system call 'alarm' ". "isn't available. This means that we cannot ". "provide the feature of intercepting long ". "waiting code and will turn this feature off.\n" ); $CPAN::Config->{inactivity_timeout} = 0; } } if ($go_via_alarm) { if ( $self->_should_report('pl') ) { ($output, $ret) = CPAN::Reporter::record_command( $system, $CPAN::Config->{inactivity_timeout}, ); CPAN::Reporter::grade_PL( $self, $system, $output, $ret ); } else { eval { alarm $CPAN::Config->{inactivity_timeout}; local $SIG{CHLD}; # = sub { wait }; if (defined($pid = fork)) { if ($pid) { #parent # wait; waitpid $pid, 0; } else { #child # note, this exec isn't necessary if # inactivity_timeout is 0. On the Mac I'd # suggest, we set it always to 0. exec $system; } } else { $CPAN::Frontend->myprint("Cannot fork: $!"); return; } }; alarm 0; if ($@) { kill 9, $pid; waitpid $pid, 0; my $err = "$@"; $CPAN::Frontend->myprint($err); $self->{writemakefile} = CPAN::Distrostatus->new("NO $err"); $@ = ""; $self->store_persistent_state; return $self->goodbye("$system -- TIMED OUT"); } } } else { if (my $expect_model = $self->_prefs_with_expect("pl")) { # XXX probably want to check _should_report here and warn # about not being able to use CPAN::Reporter with expect $ret = $self->_run_via_expect($system,'writemakefile',$expect_model); if (! defined $ret && $self->{writemakefile} && $self->{writemakefile}->failed) { # timeout return; } } elsif ( $self->_should_report('pl') ) { ($output, $ret) = eval { CPAN::Reporter::record_command($system) }; if (! defined $output or $@) { my $err = $@ || "Unknown error"; $CPAN::Frontend->mywarn("Error while running PL phase: $err\n"); $self->{writemakefile} = CPAN::Distrostatus ->new("NO '$system' returned status $ret and no output"); return $self->goodbye("$system -- NOT OK"); } CPAN::Reporter::grade_PL( $self, $system, $output, $ret ); } else { $ret = system($system); } if ($ret != 0) { $self->{writemakefile} = CPAN::Distrostatus ->new("NO '$system' returned status $ret"); $CPAN::Frontend->mywarn("Warning: No success on command[$system]\n"); $self->store_persistent_state; return $self->goodbye("$system -- NOT OK"); } } if (-f "Makefile" || -f "Build" || ($^O eq 'VMS' && (-f 'descrip.mms' || -f 'Build.com'))) { $self->{writemakefile} = CPAN::Distrostatus->new("YES"); delete $self->{make_clean}; # if cleaned before, enable next $self->store_persistent_state; return $self->success("$system -- OK"); } else { my $makefile = $self->{modulebuild} ? "Build" : "Makefile"; my $why = "No '$makefile' created"; $CPAN::Frontend->mywarn($why); $self->{writemakefile} = CPAN::Distrostatus ->new(qq{NO -- $why\n}); $self->store_persistent_state; return $self->goodbye("$system -- NOT OK"); } } $self->store_persistent_state; return 1; # success } #-> sub CPAN::Distribution::shortcut_make ; # return values: undef means don't shortcut; 0 means shortcut as fail; # and 1 means shortcut as success sub shortcut_make { my ($self) = @_; $self->debug("checking make/build results[$self->{ID}]") if $CPAN::DEBUG; if (defined $self->{make}) { if (UNIVERSAL::can($self->{make},"failed") ? $self->{make}->failed : $self->{make} =~ /^NO/ ) { if ($self->{force_update}) { # Trying an already failed 'make' (unless somebody else blocks) return undef; # no shortcut } else { # introduced for turning recursion detection into a distrostatus my $error = length $self->{make}>3 ? substr($self->{make},3) : "Unknown error"; $self->store_persistent_state; return $self->goodbye("Could not make: $error\n"); } } else { return $self->success("Has already been made") } } return undef; # no shortcut } #-> sub CPAN::Distribution::make ; sub make { my($self) = @_; $self->pre_make(); if (exists $self->{cleanup_after_install_done}) { $self->post_make(); return $self->get; } $self->debug("checking goto id[$self->{ID}]") if $CPAN::DEBUG; if (my $goto = $self->prefs->{goto}) { $self->post_make(); return $self->goto($goto); } # Emergency brake if they said install Pippi and get newest perl # XXX Would this make more sense in shortcut_prepare, since # that doesn't make sense on a perl dist either? Broader # question: what is the purpose of suggesting force install # on a perl distribution? That seems unlikely to result in # such a dependency being satisfied, even if the perl is # successfully installed. This situation is tantamount to # a prereq on a version of perl greater than the current one # so I think we should just abort. -- xdg, 2012-04-06 if ($self->isa_perl) { if ( $self->called_for ne $self->id && ! $self->{force_update} ) { # if we die here, we break bundles $CPAN::Frontend ->mywarn(sprintf( qq{The most recent version "%s" of the module "%s" is part of the perl-%s distribution. To install that, you need to run force install %s --or-- install %s }, $CPAN::META->instance( 'CPAN::Module', $self->called_for )->cpan_version, $self->called_for, $self->isa_perl, $self->called_for, $self->pretty_id, )); $self->{make} = CPAN::Distrostatus->new("NO isa perl"); $CPAN::Frontend->mysleep(1); $self->post_make(); return; } } unless ($self->prepare){ $self->post_make(); return; } if ( defined( my $sc = $self->shortcut_make) ) { $self->post_make(); return $sc; } if ($CPAN::Signal) { delete $self->{force_update}; $self->post_make(); return; } my $builddir = $self->dir or $CPAN::Frontend->mydie("PANIC: Cannot determine build directory\n"); unless (chdir $builddir) { $CPAN::Frontend->mywarn("Couldn't chdir to '$builddir': $!"); $self->post_make(); return; } my $make = $self->{modulebuild} ? "Build" : "make"; $CPAN::Frontend->myprint(sprintf "Running %s for %s\n", $make, $self->id); local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : ""; local $ENV{PERL_USE_UNSAFE_INC} = exists $ENV{PERL_USE_UNSAFE_INC} && defined $ENV{PERL_USE_UNSAFE_INC} ? $ENV{PERL_USE_UNSAFE_INC} : 1; # make $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls if ($CPAN::Signal) { delete $self->{force_update}; $self->post_make(); return; } if ($^O eq 'MacOS') { Mac::BuildTools::make($self); $self->post_make(); return; } my %env; while (my($k,$v) = each %ENV) { next if defined $v; $env{$k} = ''; } local @ENV{keys %env} = values %env; my $satisfied = eval { $self->satisfy_requires }; if ($@) { return $self->goodbye($@); } unless ($satisfied){ $self->post_make(); return; } if ($CPAN::Signal) { delete $self->{force_update}; $self->post_make(); return; } # need to chdir again, because $self->satisfy_requires might change the directory unless (chdir $builddir) { $CPAN::Frontend->mywarn("Couldn't chdir to '$builddir': $!"); $self->post_make(); return; } my $system; my $make_commandline; if ($self->prefs->{make}) { $make_commandline = $self->prefs->{make}{commandline}; } local $ENV{PERL} = defined $ENV{PERL}? $ENV{PERL} : $^X; local $ENV{PERL_MM_USE_DEFAULT} = 1 if $CPAN::Config->{use_prompt_default}; local $ENV{NONINTERACTIVE_TESTING} = 1 if $CPAN::Config->{use_prompt_default}; if ($make_commandline) { $system = $make_commandline; $ENV{PERL} = CPAN::find_perl(); } else { if ($self->{modulebuild}) { unless (-f "Build" || ($^O eq 'VMS' && -f 'Build.com')) { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mywarn("Alert: no Build file available for 'make $self->{id}'". " in cwd[$cwd]. Danger, Will Robinson!\n"); $CPAN::Frontend->mysleep(5); } $system = join " ", $self->_build_command(), $CPAN::Config->{mbuild_arg}; } else { $system = join " ", $self->_make_command(), $CPAN::Config->{make_arg}; } $system =~ s/\s+$//; my $make_arg = $self->_make_phase_arg("make"); $system = sprintf("%s%s", $system, $make_arg ? " $make_arg" : "", ); } my $make_env; if ($self->prefs->{make}) { $make_env = $self->prefs->{make}{env}; } local @ENV{keys %$make_env} = values %$make_env if $make_env; my $expect_model = $self->_prefs_with_expect("make"); my $want_expect = 0; if ( $expect_model && @{$expect_model->{talk}} ) { my $can_expect = $CPAN::META->has_inst("Expect"); if ($can_expect) { $want_expect = 1; } else { $CPAN::Frontend->mywarn("Expect not installed, falling back to ". "system()\n"); } } my ($system_ok, $system_err); if ($want_expect) { # XXX probably want to check _should_report here and # warn about not being able to use CPAN::Reporter with expect $system_ok = $self->_run_via_expect($system,'make',$expect_model) == 0; } elsif ( $self->_should_report('make') ) { my ($output, $ret) = CPAN::Reporter::record_command($system); CPAN::Reporter::grade_make( $self, $system, $output, $ret ); $system_ok = ! $ret; } else { my $rc = system($system); $system_ok = $rc == 0; $system_err = $! if $rc == -1; } $self->introduce_myself; if ( $system_ok ) { $CPAN::Frontend->myprint(" $system -- OK\n"); $self->{make} = CPAN::Distrostatus->new("YES"); } else { $self->{writemakefile} ||= CPAN::Distrostatus->new("YES"); $self->{make} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); $CPAN::Frontend->mywarn(" $system_err\n") if defined $system_err; } $self->store_persistent_state; $self->post_make(); return !! $system_ok; } # CPAN::Distribution::goodbye ; sub goodbye { my($self,$goodbye) = @_; my $id = $self->pretty_id; $CPAN::Frontend->mywarn(" $id\n $goodbye\n"); return 0; # must be explicit false, not undef } sub success { my($self,$why) = @_; my $id = $self->pretty_id; $CPAN::Frontend->myprint(" $id\n $why\n"); return 1; } # CPAN::Distribution::_run_via_expect ; sub _run_via_expect { my($self,$system,$phase,$expect_model) = @_; CPAN->debug("system[$system]expect_model[$expect_model]") if $CPAN::DEBUG; if ($CPAN::META->has_inst("Expect")) { my $expo = Expect->new; # expo Expect object; $expo->spawn($system); $expect_model->{mode} ||= "deterministic"; if ($expect_model->{mode} eq "deterministic") { return $self->_run_via_expect_deterministic($expo,$phase,$expect_model); } elsif ($expect_model->{mode} eq "anyorder") { return $self->_run_via_expect_anyorder($expo,$phase,$expect_model); } else { die "Panic: Illegal expect mode: $expect_model->{mode}"; } } else { $CPAN::Frontend->mywarn("Expect not installed, falling back to system()\n"); return system($system); } } sub _run_via_expect_anyorder { my($self,$expo,$phase,$expect_model) = @_; my $timeout = $expect_model->{timeout} || 5; my $reuse = $expect_model->{reuse}; my @expectacopy = @{$expect_model->{talk}}; # we trash it! my $but = ""; my $timeout_start = time; EXPECT: while () { my($eof,$ran_into_timeout); # XXX not up to the full power of expect. one could certainly # wrap all of the talk pairs into a single expect call and on # success tweak it and step ahead to the next question. The # current implementation unnecessarily limits itself to a # single match. my @match = $expo->expect(1, [ eof => sub { $eof++; } ], [ timeout => sub { $ran_into_timeout++; } ], -re => eval"qr{.}", ); if ($match[2]) { $but .= $match[2]; } $but .= $expo->clear_accum; if ($eof) { $expo->soft_close; return $expo->exitstatus(); } elsif ($ran_into_timeout) { # warn "DEBUG: they are asking a question, but[$but]"; for (my $i = 0; $i <= $#expectacopy; $i+=2) { my($next,$send) = @expectacopy[$i,$i+1]; my $regex = eval "qr{$next}"; # warn "DEBUG: will compare with regex[$regex]."; if ($but =~ /$regex/) { # warn "DEBUG: will send send[$send]"; $expo->send($send); # never allow reusing an QA pair unless they told us splice @expectacopy, $i, 2 unless $reuse; $but =~ s/(?s:^.*?)$regex//; $timeout_start = time; next EXPECT; } } my $have_waited = time - $timeout_start; if ($have_waited < $timeout) { # warn "DEBUG: have_waited[$have_waited]timeout[$timeout]"; next EXPECT; } my $why = "could not answer a question during the dialog"; $CPAN::Frontend->mywarn("Failing: $why\n"); $self->{$phase} = CPAN::Distrostatus->new("NO $why"); return 0; } } } sub _run_via_expect_deterministic { my($self,$expo,$phase,$expect_model) = @_; my $ran_into_timeout; my $ran_into_eof; my $timeout = $expect_model->{timeout} || 15; # currently unsettable my $expecta = $expect_model->{talk}; EXPECT: for (my $i = 0; $i <= $#$expecta; $i+=2) { my($re,$send) = @$expecta[$i,$i+1]; CPAN->debug("timeout[$timeout]re[$re]") if $CPAN::DEBUG; my $regex = eval "qr{$re}"; $expo->expect($timeout, [ eof => sub { my $but = $expo->clear_accum; $CPAN::Frontend->mywarn("EOF (maybe harmless) expected[$regex]\nbut[$but]\n\n"); $ran_into_eof++; } ], [ timeout => sub { my $but = $expo->clear_accum; $CPAN::Frontend->mywarn("TIMEOUT expected[$regex]\nbut[$but]\n\n"); $ran_into_timeout++; } ], -re => $regex); if ($ran_into_timeout) { # note that the caller expects 0 for success $self->{$phase} = CPAN::Distrostatus->new("NO timeout during expect dialog"); return 0; } elsif ($ran_into_eof) { last EXPECT; } $expo->send($send); } $expo->soft_close; return $expo->exitstatus(); } #-> CPAN::Distribution::_validate_distropref sub _validate_distropref { my($self,@args) = @_; if ( $CPAN::META->has_inst("CPAN::Kwalify") && $CPAN::META->has_inst("Kwalify") ) { eval {CPAN::Kwalify::_validate("distroprefs",@args);}; if ($@) { $CPAN::Frontend->mywarn($@); } } else { CPAN->debug("not validating '@args'") if $CPAN::DEBUG; } } #-> CPAN::Distribution::_find_prefs sub _find_prefs { my($self) = @_; my $distroid = $self->pretty_id; #CPAN->debug("distroid[$distroid]") if $CPAN::DEBUG; my $prefs_dir = $CPAN::Config->{prefs_dir}; return if $prefs_dir =~ /^\s*$/; eval { File::Path::mkpath($prefs_dir); }; if ($@) { $CPAN::Frontend->mydie("Cannot create directory $prefs_dir"); } # shortcut if there are no distroprefs files { my $dh = DirHandle->new($prefs_dir) or $CPAN::Frontend->mydie("Couldn't open '$prefs_dir': $!"); my @files = map { /\.(yml|dd|st)\z/i } $dh->read; return unless @files; } my $yaml_module = CPAN::_yaml_module(); my $ext_map = {}; my @extensions; if ($CPAN::META->has_inst($yaml_module)) { $ext_map->{yml} = 'CPAN'; } else { my @fallbacks; if ($CPAN::META->has_inst("Data::Dumper")) { push @fallbacks, $ext_map->{dd} = 'Data::Dumper'; } if ($CPAN::META->has_inst("Storable")) { push @fallbacks, $ext_map->{st} = 'Storable'; } if (@fallbacks) { local $" = " and "; unless ($self->{have_complained_about_missing_yaml}++) { $CPAN::Frontend->mywarnonce("'$yaml_module' not installed, falling back ". "to @fallbacks to read prefs '$prefs_dir'\n"); } } else { unless ($self->{have_complained_about_missing_yaml}++) { $CPAN::Frontend->mywarnonce("'$yaml_module' not installed, cannot ". "read prefs '$prefs_dir'\n"); } } } my $finder = CPAN::Distroprefs->find($prefs_dir, $ext_map); DIRENT: while (my $result = $finder->next) { if ($result->is_warning) { $CPAN::Frontend->mywarn($result->as_string); $CPAN::Frontend->mysleep(1); next DIRENT; } elsif ($result->is_fatal) { $CPAN::Frontend->mydie($result->as_string); } my @prefs = @{ $result->prefs }; ELEMENT: for my $y (0..$#prefs) { my $pref = $prefs[$y]; $self->_validate_distropref($pref->data, $result->abs, $y); # I don't know why we silently skip when there's no match, but # complain if there's an empty match hashref, and there's no # comment explaining why -- hdp, 2008-03-18 unless ($pref->has_any_match) { next ELEMENT; } unless ($pref->has_valid_subkeys) { $CPAN::Frontend->mydie(sprintf "Nonconforming .%s file '%s': " . "missing match/* subattribute. " . "Please remove, cannot continue.", $result->ext, $result->abs, ); } my $arg = { env => \%ENV, distribution => $distroid, perl => \&CPAN::find_perl, perlconfig => \%Config::Config, module => sub { [ $self->containsmods ] }, }; if ($pref->matches($arg)) { return { prefs => $pref->data, prefs_file => $result->abs, prefs_file_doc => $y, }; } } } return; } # CPAN::Distribution::prefs sub prefs { my($self) = @_; if (exists $self->{negative_prefs_cache} && $self->{negative_prefs_cache} != $CPAN::CurrentCommandId ) { delete $self->{negative_prefs_cache}; delete $self->{prefs}; } if (exists $self->{prefs}) { return $self->{prefs}; # XXX comment out during debugging } if ($CPAN::Config->{prefs_dir}) { CPAN->debug("prefs_dir[$CPAN::Config->{prefs_dir}]") if $CPAN::DEBUG; my $prefs = $self->_find_prefs(); $prefs ||= ""; # avoid warning next line CPAN->debug("prefs[$prefs]") if $CPAN::DEBUG; if ($prefs) { for my $x (qw(prefs prefs_file prefs_file_doc)) { $self->{$x} = $prefs->{$x}; } my $bs = sprintf( "%s[%s]", File::Basename::basename($self->{prefs_file}), $self->{prefs_file_doc}, ); my $filler1 = "_" x 22; my $filler2 = int(66 - length($bs))/2; $filler2 = 0 if $filler2 < 0; $filler2 = " " x $filler2; $CPAN::Frontend->myprint(" $filler1 D i s t r o P r e f s $filler1 $filler2 $bs $filler2 "); $CPAN::Frontend->mysleep(1); return $self->{prefs}; } } $self->{negative_prefs_cache} = $CPAN::CurrentCommandId; return $self->{prefs} = +{}; } # CPAN::Distribution::_make_phase_arg sub _make_phase_arg { my($self, $phase) = @_; my $_make_phase_arg; my $prefs = $self->prefs; if ( $prefs && exists $prefs->{$phase} && exists $prefs->{$phase}{args} && $prefs->{$phase}{args} ) { $_make_phase_arg = join(" ", map {CPAN::HandleConfig ->safe_quote($_)} @{$prefs->{$phase}{args}}, ); } # cpan[2]> o conf make[TAB] # make make_install_make_command # make_arg makepl_arg # make_install_arg # cpan[2]> o conf mbuild[TAB] # mbuild_arg mbuild_install_build_command # mbuild_install_arg mbuildpl_arg my $mantra; # must switch make/mbuild here if ($self->{modulebuild}) { $mantra = "mbuild"; } else { $mantra = "make"; } my %map = ( pl => "pl_arg", make => "_arg", test => "_test_arg", # does not really exist but maybe # will some day and now protects # us from unini warnings install => "_install_arg", ); my $phase_underscore_meshup = $map{$phase}; my $what = sprintf "%s%s", $mantra, $phase_underscore_meshup; $_make_phase_arg ||= $CPAN::Config->{$what}; return $_make_phase_arg; } # CPAN::Distribution::_make_command sub _make_command { my ($self) = @_; if ($self) { return CPAN::HandleConfig ->safe_quote( CPAN::HandleConfig->prefs_lookup($self, q{make}) || $Config::Config{make} || 'make' ); } else { # Old style call, without object. Deprecated Carp::confess("CPAN::_make_command() used as function. Don't Do That."); return safe_quote(undef, CPAN::HandleConfig->prefs_lookup($self,q{make}) || $CPAN::Config->{make} || $Config::Config{make} || 'make'); } } sub _make_install_make_command { my ($self) = @_; my $mimc = CPAN::HandleConfig->prefs_lookup($self, q{make_install_make_command}); return $self->_make_command() unless $mimc; # Quote the "make install" make command on Windows, where it is commonly # found in, e.g., C:\Program Files\... and therefore needs quoting. We can't # do this in general because the command maybe "sudo make..." (i.e. a # program with arguments), but that is unlikely to be the case on Windows. $mimc = CPAN::HandleConfig->safe_quote($mimc) if $^O eq 'MSWin32'; return $mimc; } #-> sub CPAN::Distribution::is_locally_optional sub is_locally_optional { my($self, $prereq_pm, $prereq) = @_; $prereq_pm ||= $self->{prereq_pm}; my($nmo,$opt); for my $rt (qw(requires build_requires)) { if (exists $prereq_pm->{$rt}{$prereq}) { # rt 121914 $nmo ||= $CPAN::META->instance("CPAN::Module",$prereq); my $av = $nmo->available_version; return 0 if !$av || CPAN::Version->vlt($av,$prereq_pm->{$rt}{$prereq}); } if (exists $prereq_pm->{"opt_$rt"}{$prereq}) { $opt = 1; } } return $opt||0; } #-> sub CPAN::Distribution::follow_prereqs ; sub follow_prereqs { my($self) = shift; my($slot) = shift; my(@prereq_tuples) = grep {$_->[0] ne "perl"} @_; return unless @prereq_tuples; my(@good_prereq_tuples); for my $p (@prereq_tuples) { # e.g. $p = ['Devel::PartialDump', 'r', 1] # promote if possible if ($p->[1] =~ /^(r|c)$/) { push @good_prereq_tuples, $p; } elsif ($p->[1] =~ /^(b)$/) { my $reqtype = CPAN::Queue->reqtype_of($p->[0]); if ($reqtype =~ /^(r|c)$/) { push @good_prereq_tuples, [$p->[0], $reqtype, $p->[2]]; } else { push @good_prereq_tuples, $p; } } else { die "Panic: in follow_prereqs: reqtype[$p->[1]] seen, should never happen"; } } my $pretty_id = $self->pretty_id; my %map = ( b => "build_requires", r => "requires", c => "commandline", ); my($filler1,$filler2,$filler3,$filler4); my $unsat = "Unsatisfied dependencies detected during"; my $w = length($unsat) > length($pretty_id) ? length($unsat) : length($pretty_id); { my $r = int(($w - length($unsat))/2); my $l = $w - length($unsat) - $r; $filler1 = "-"x4 . " "x$l; $filler2 = " "x$r . "-"x4 . "\n"; } { my $r = int(($w - length($pretty_id))/2); my $l = $w - length($pretty_id) - $r; $filler3 = "-"x4 . " "x$l; $filler4 = " "x$r . "-"x4 . "\n"; } $CPAN::Frontend-> myprint("$filler1 $unsat $filler2". "$filler3 $pretty_id $filler4". join("", map {sprintf " %s \[%s%s]\n", $_->[0], $map{$_->[1]}, $self->is_locally_optional(undef,$_->[0]) ? ",optional" : ""} @good_prereq_tuples), ); my $follow = 0; if ($CPAN::Config->{prerequisites_policy} eq "follow") { $follow = 1; } elsif ($CPAN::Config->{prerequisites_policy} eq "ask") { my $answer = CPAN::Shell::colorable_makemaker_prompt( "Shall I follow them and prepend them to the queue of modules we are processing right now?", "yes"); $follow = $answer =~ /^\s*y/i; } else { my @prereq = map { $_->[0] } @good_prereq_tuples; local($") = ", "; $CPAN::Frontend-> myprint(" Ignoring dependencies on modules @prereq\n"); } if ($follow) { my $id = $self->id; my(@to_queue_mand,@to_queue_opt); for my $gp (@good_prereq_tuples) { my($prereq,$reqtype,$optional) = @$gp; my $qthing = +{qmod=>$prereq,reqtype=>$reqtype,optional=>$optional}; if ($optional && $self->is_locally_optional(undef,$prereq) ){ # Since we do not depend on this one, we do not need # this in a mandatory arrangement: push @to_queue_opt, $qthing; } else { my $any = CPAN::Shell->expandany($prereq); $self->{$slot . "_for"}{$any->id}++; if ($any) { unless ($optional) { # No recursion check in an optional area of the tree $any->color_cmd_tmps(0,2); } } else { $CPAN::Frontend->mywarn("Warning (maybe a bug): Cannot expand prereq '$prereq'\n"); $CPAN::Frontend->mysleep(2); } # order everything that is not locally_optional just # like mandatory items: this keeps leaves before # branches unshift @to_queue_mand, $qthing; } } if (@to_queue_mand) { unshift @to_queue_mand, {qmod => $id, reqtype => $self->{reqtype}, optional=> !$self->{mandatory}}; CPAN::Queue->jumpqueue(@to_queue_opt,@to_queue_mand); $self->{$slot} = "Delayed until after prerequisites"; return 1; # signal we need dependencies } elsif (@to_queue_opt) { CPAN::Queue->jumpqueue(@to_queue_opt); } } return; } sub _feature_depends { my($self) = @_; my $meta_yml = $self->parse_meta_yml(); my $optf = $meta_yml->{optional_features} or return; if (!ref $optf or ref $optf ne "HASH"){ $CPAN::Frontend->mywarn("The content of optional_features is not a HASH reference. Cannot use it.\n"); $optf = {}; } my $wantf = $self->prefs->{features} or return; if (!ref $wantf or ref $wantf ne "ARRAY"){ $CPAN::Frontend->mywarn("The content of 'features' is not an ARRAY reference. Cannot use it.\n"); $wantf = []; } my $dep = +{}; for my $wf (@$wantf) { if (my $f = $optf->{$wf}) { $CPAN::Frontend->myprint("Found the demanded feature '$wf' that ". "is accompanied by this description:\n". $f->{description}. "\n\n" ); # configure_requires currently not in the spec, unlikely to be useful anyway for my $reqtype (qw(configure_requires build_requires requires)) { my $reqhash = $f->{$reqtype} or next; while (my($k,$v) = each %$reqhash) { $dep->{$reqtype}{$k} = $v; } } } else { $CPAN::Frontend->mywarn("The demanded feature '$wf' was not ". "found in the META.yml file". "\n\n" ); } } $dep; } sub prereqs_for_slot { my($self,$slot) = @_; my($prereq_pm); unless ($CPAN::META->has_usable("CPAN::Meta::Requirements")) { my $whynot = "not available"; if (defined $CPAN::Meta::Requirements::VERSION) { $whynot = "version $CPAN::Meta::Requirements::VERSION not sufficient"; } $CPAN::Frontend->mywarn("CPAN::Meta::Requirements $whynot\n"); my $before = ""; if ($self->{CALLED_FOR}){ if ($self->{CALLED_FOR} =~ /^( CPAN::Meta::Requirements |CPAN::DistnameInfo |version |parent |ExtUtils::MakeMaker |Test::Harness )$/x) { $CPAN::Frontend->mywarn("Please install CPAN::Meta::Requirements ". "as soon as possible; it is needed for a reliable operation of ". "the cpan shell; setting requirements to nil for '$1' for now ". "to prevent deadlock during bootstrapping\n"); return; } $before = " before $self->{CALLED_FOR}"; } $CPAN::Frontend->mydie("Please install CPAN::Meta::Requirements manually$before"); } my $merged = CPAN::Meta::Requirements->new; my $prefs_depends = $self->prefs->{depends}||{}; my $feature_depends = $self->_feature_depends(); if ($slot eq "configure_requires_later") { for my $hash ( $self->configure_requires, $prefs_depends->{configure_requires}, $feature_depends->{configure_requires}, ) { $merged->add_requirements( CPAN::Meta::Requirements->from_string_hash($hash) ); } if (-f "Build.PL" && ! -f File::Spec->catfile($self->{build_dir},"Makefile.PL") && ! @{[ $merged->required_modules ]} && ! $CPAN::META->has_inst("Module::Build") ) { $CPAN::Frontend->mywarn( " Warning: CPAN.pm discovered Module::Build as undeclared prerequisite.\n". " Adding it now as such.\n" ); $CPAN::Frontend->mysleep(5); $merged->add_minimum( "Module::Build" => 0 ); delete $self->{writemakefile}; } $prereq_pm = {}; # configure_requires defined as "b" } elsif ($slot eq "later") { my $prereq_pm_0 = $self->prereq_pm || {}; for my $reqtype (qw(requires build_requires opt_requires opt_build_requires)) { $prereq_pm->{$reqtype} = {%{$prereq_pm_0->{$reqtype}||{}}}; # copy to not pollute it for my $dep ($prefs_depends,$feature_depends) { for my $k (keys %{$dep->{$reqtype}||{}}) { $prereq_pm->{$reqtype}{$k} = $dep->{$reqtype}{$k}; } } } # XXX what about optional_req|breq? -- xdg, 2012-04-01 for my $hash ( $prereq_pm->{requires}, $prereq_pm->{build_requires}, $prereq_pm->{opt_requires}, $prereq_pm->{opt_build_requires}, ) { $merged->add_requirements( CPAN::Meta::Requirements->from_string_hash($hash) ); } } else { die "Panic: illegal slot '$slot'"; } return ($merged->as_string_hash, $prereq_pm); } #-> sub CPAN::Distribution::unsat_prereq ; # return ([Foo,"r"],[Bar,"b"]) for normal modules # return ([perl=>5.008]) if we need a newer perl than we are running under # (sorry for the inconsistency, it was an accident) sub unsat_prereq { my($self,$slot) = @_; my($merged_hash,$prereq_pm) = $self->prereqs_for_slot($slot); my(@need); unless ($CPAN::META->has_usable("CPAN::Meta::Requirements")) { $CPAN::Frontend->mywarn("CPAN::Meta::Requirements not available, please install as soon as possible, trying to continue with severly limited capabilities\n"); return; } my $merged = CPAN::Meta::Requirements->from_string_hash($merged_hash); my @merged = sort $merged->required_modules; CPAN->debug("all merged_prereqs[@merged]") if $CPAN::DEBUG; NEED: for my $need_module ( @merged ) { my $need_version = $merged->requirements_for_module($need_module); my($available_version,$inst_file,$available_file,$nmo); if ($need_module eq "perl") { $available_version = $]; $available_file = CPAN::find_perl(); } else { if (CPAN::_sqlite_running()) { CPAN::Index->reload; $CPAN::SQLite->search("CPAN::Module",$need_module); } $nmo = $CPAN::META->instance("CPAN::Module",$need_module); $inst_file = $nmo->inst_file || ''; $available_file = $nmo->available_file || ''; $available_version = $nmo->available_version; if ($nmo->uptodate) { my $accepts = eval { $merged->accepts_module($need_module, $available_version); }; unless ($accepts) { my $rq = $merged->requirements_for_module( $need_module ); $CPAN::Frontend->mywarn( "Warning: Version '$available_version' of ". "'$need_module' is up to date but does not ". "fulfill requirements ($rq). I will continue, ". "but chances to succeed are low.\n"); } next NEED; } # if they have not specified a version, we accept any # installed one; in that case inst_file is always # sufficient and available_file is sufficient on # both build_requires and configure_requires my $sufficient = $inst_file || ( exists $prereq_pm->{requires}{$need_module} ? 0 : $available_file ); if ( $sufficient and ( # a few quick short circuits not defined $need_version or $need_version eq '0' # "==" would trigger warning when not numeric or $need_version eq "undef" )) { unless ($nmo->inst_deprecated) { next NEED; } } } # We only want to install prereqs if either they're not installed # or if the installed version is too old. We cannot omit this # check, because if 'force' is in effect, nobody else will check. # But we don't want to accept a deprecated module installed as part # of the Perl core, so we continue if the available file is the installed # one and is deprecated if ( $available_file ) { my $fulfills_all_version_rqs = $self->_fulfills_all_version_rqs ( $need_module, $available_file, $available_version, $need_version, ); if ( $inst_file && $available_file eq $inst_file && $nmo->inst_deprecated ) { # continue installing as a prereq. we really want that # because the deprecated module may spit out warnings # and third party did not know until today. Only one # exception is OK, because CPANPLUS is special after # all: if ( $fulfills_all_version_rqs and $nmo->id =~ /^CPANPLUS(?:::Dist::Build)$/ ) { # here we have an available version that is good # enough although deprecated (preventing circular # loop CPANPLUS => CPANPLUS::Dist::Build RT#83042) next NEED; } } elsif ( $self->{reqtype} # e.g. maybe we came via goto? && $self->{reqtype} =~ /^(r|c)$/ && ( exists $prereq_pm->{requires}{$need_module} || exists $prereq_pm->{opt_requires}{$need_module} ) && $nmo && !$inst_file ) { # continue installing as a prereq; this may be a # distro we already used when it was a build_requires # so we did not install it. But suddenly somebody # wants it as a requires my $need_distro = $nmo->distribution; if ($need_distro->{install} && $need_distro->{install}->failed && $need_distro->{install}->text =~ /is only/) { my $id = $need_distro->pretty_id; $CPAN::Frontend->myprint("Promoting $id from build_requires to requires due $need_module\n"); delete $need_distro->{install}; # promote to another installation attempt $need_distro->{reqtype} = "r"; $need_distro->install; next NEED; } } else { next NEED if $fulfills_all_version_rqs; } } if ($need_module eq "perl") { return ["perl", $need_version]; } $self->{sponsored_mods}{$need_module} ||= 0; CPAN->debug("need_module[$need_module]s/s/n[$self->{sponsored_mods}{$need_module}]") if $CPAN::DEBUG; if (my $sponsoring = $self->{sponsored_mods}{$need_module}++) { # We have already sponsored it and for some reason it's still # not available. So we do ... what?? # if we push it again, we have a potential infinite loop # The following "next" was a very problematic construct. # It helped a lot but broke some day and had to be # replaced. # We must be able to deal with modules that come again and # again as a prereq and have themselves prereqs and the # queue becomes long but finally we would find the correct # order. The RecursiveDependency check should trigger a # die when it's becoming too weird. Unfortunately removing # this next breaks many other things. # The bug that brought this up is described in Todo under # "5.8.9 cannot install Compress::Zlib" # next; # this is the next that had to go away # The following "next NEED" are fine and the error message # explains well what is going on. For example when the DBI # fails and consequently DBD::SQLite fails and now we are # processing CPAN::SQLite. Then we must have a "next" for # DBD::SQLite. How can we get it and how can we identify # all other cases we must identify? my $do = $nmo->distribution; next NEED unless $do; # not on CPAN if (CPAN::Version->vcmp($need_version, $nmo->ro->{CPAN_VERSION}) > 0){ $CPAN::Frontend->mywarn("Warning: Prerequisite ". "'$need_module => $need_version' ". "for '$self->{ID}' seems ". "not available according to the indices\n" ); next NEED; } NOSAYER: for my $nosayer ( "unwrapped", "writemakefile", "signature_verify", "make", "make_test", "install", "make_clean", ) { if ($do->{$nosayer}) { my $selfid = $self->pretty_id; my $did = $do->pretty_id; if (UNIVERSAL::can($do->{$nosayer},"failed") ? $do->{$nosayer}->failed : $do->{$nosayer} =~ /^NO/) { if ($nosayer eq "make_test" && $do->{make_test}{COMMANDID} != $CPAN::CurrentCommandId ) { next NOSAYER; } ### XXX don't complain about missing optional deps -- xdg, 2012-04-01 if ($self->is_locally_optional($prereq_pm, $need_module)) { # don't complain about failing optional prereqs } else { $CPAN::Frontend->mywarn("Warning: Prerequisite ". "'$need_module => $need_version' ". "for '$selfid' failed when ". "processing '$did' with ". "'$nosayer => $do->{$nosayer}'. Continuing, ". "but chances to succeed are limited.\n" ); $CPAN::Frontend->mysleep($sponsoring/10); } next NEED; } else { # the other guy succeeded if ($nosayer =~ /^(install|make_test)$/) { # we had this with # DMAKI/DateTime-Calendar-Chinese-0.05.tar.gz # in 2007-03 for 'make install' # and 2008-04: #30464 (for 'make test') # $CPAN::Frontend->mywarn("Warning: Prerequisite ". # "'$need_module => $need_version' ". # "for '$selfid' already built ". # "but the result looks suspicious. ". # "Skipping another build attempt, ". # "to prevent looping endlessly.\n" # ); next NEED; } } } } } my $needed_as; if (0) { } elsif (exists $prereq_pm->{requires}{$need_module} || exists $prereq_pm->{opt_requires}{$need_module} ) { $needed_as = "r"; } elsif ($slot eq "configure_requires_later") { # in ae872487d5 we said: C< we have not yet run the # {Build,Makefile}.PL, we must presume "r" >; but the # meta.yml standard says C< These dependencies are not # required after the distribution is installed. >; so now # we change it back to "b" and care for the proper # promotion later. $needed_as = "b"; } else { $needed_as = "b"; } # here need to flag as optional for recommends/suggests # -- xdg, 2012-04-01 $self->debug(sprintf "%s manadory?[%s]", $self->pretty_id, $self->{mandatory}) if $CPAN::DEBUG; my $optional = !$self->{mandatory} || $self->is_locally_optional($prereq_pm, $need_module); push @need, [$need_module,$needed_as,$optional]; } my @unfolded = map { "[".join(",",@$_)."]" } @need; CPAN->debug("returning from unsat_prereq[@unfolded]") if $CPAN::DEBUG; @need; } sub _fulfills_all_version_rqs { my($self,$need_module,$available_file,$available_version,$need_version) = @_; my(@all_requirements) = split /\s*,\s*/, $need_version; local($^W) = 0; my $ok = 0; RQ: for my $rq (@all_requirements) { if ($rq =~ s|>=\s*||) { } elsif ($rq =~ s|>\s*||) { # 2005-12: one user if (CPAN::Version->vgt($available_version,$rq)) { $ok++; } next RQ; } elsif ($rq =~ s|!=\s*||) { # 2005-12: no user if (CPAN::Version->vcmp($available_version,$rq)) { $ok++; next RQ; } else { $ok=0; last RQ; } } elsif ($rq =~ m|<=?\s*|) { # 2005-12: no user $CPAN::Frontend->mywarn("Downgrading not supported (rq[$rq])\n"); $ok++; next RQ; } elsif ($rq =~ s|==\s*||) { # 2009-07: ELLIOTJS/Perl-Critic-1.099_002.tar.gz if (CPAN::Version->vcmp($available_version,$rq)) { $ok=0; last RQ; } else { $ok++; next RQ; } } if (! CPAN::Version->vgt($rq, $available_version)) { $ok++; } CPAN->debug(sprintf("need_module[%s]available_file[%s]". "available_version[%s]rq[%s]ok[%d]", $need_module, $available_file, $available_version, CPAN::Version->readable($rq), $ok, )) if $CPAN::DEBUG; } my $ret = $ok == @all_requirements; CPAN->debug(sprintf("need_module[%s]ok[%s]all_requirements[%d]",$need_module, $ok, scalar @all_requirements)) if $CPAN::DEBUG; return $ret; } #-> sub CPAN::Distribution::read_meta # read any sort of meta files, return CPAN::Meta object if no errors sub read_meta { my($self) = @_; my $meta_file = $self->pick_meta_file or return; return unless $CPAN::META->has_usable("CPAN::Meta"); my $meta = eval { CPAN::Meta->load_file($meta_file)} or return; # Very old EU::MM could have wrong META if ($meta_file eq 'META.yml' && $meta->generated_by =~ /ExtUtils::MakeMaker version ([\d\._]+)/ ) { my $eummv = do { local $^W = 0; $1+0; }; return if $eummv < 6.2501; } return $meta; } #-> sub CPAN::Distribution::read_yaml ; # XXX This should be DEPRECATED -- dagolden, 2011-02-05 sub read_yaml { my($self) = @_; my $meta_file = $self->pick_meta_file('\.yml$'); $self->debug("meta_file[$meta_file]") if $CPAN::DEBUG; return unless $meta_file; my $yaml; eval { $yaml = $self->parse_meta_yml($meta_file) }; if ($@ or ! $yaml) { return undef; # if we die, then we cannot read YAML's own META.yml } # not "authoritative" if (defined $yaml && (! ref $yaml || ref $yaml ne "HASH")) { $CPAN::Frontend->mywarn("META.yml does not seem to be conforming, cannot use it.\n"); $yaml = undef; } $self->debug(sprintf "yaml[%s]", $yaml || "UNDEF") if $CPAN::DEBUG; $self->debug($yaml) if $CPAN::DEBUG && $yaml; # MYMETA.yml is static and authoritative by definition if ( $meta_file =~ /MYMETA\.yml/ ) { return $yaml; } # META.yml is authoritative only if dynamic_config is defined and false if ( defined $yaml->{dynamic_config} && ! $yaml->{dynamic_config} ) { return $yaml; } # otherwise, we can't use what we found return undef; } #-> sub CPAN::Distribution::configure_requires ; sub configure_requires { my($self) = @_; return unless my $meta_file = $self->pick_meta_file('^META'); if (my $meta_obj = $self->read_meta) { my $prereqs = $meta_obj->effective_prereqs; my $cr = $prereqs->requirements_for(qw/configure requires/); return $cr ? $cr->as_string_hash : undef; } else { my $yaml = eval { $self->parse_meta_yml($meta_file) }; return $yaml->{configure_requires}; } } #-> sub CPAN::Distribution::prereq_pm ; sub prereq_pm { my($self) = @_; return unless $self->{writemakefile} # no need to have succeeded # but we must have run it || $self->{modulebuild}; unless ($self->{build_dir}) { return; } # no Makefile/Build means configuration aborted, so don't look for prereqs my $makefile = File::Spec->catfile($self->{build_dir}, $^O eq 'VMS' ? 'descrip.mms' : 'Makefile'); my $buildfile = File::Spec->catfile($self->{build_dir}, $^O eq 'VMS' ? 'Build.com' : 'Build'); return unless -f $makefile || -f $buildfile; CPAN->debug(sprintf "writemakefile[%s]modulebuild[%s]", $self->{writemakefile}||"", $self->{modulebuild}||"", ) if $CPAN::DEBUG; my($req,$breq, $opt_req, $opt_breq); my $meta_obj = $self->read_meta; # META/MYMETA is only authoritative if dynamic_config is false if ($meta_obj && ! $meta_obj->dynamic_config) { my $prereqs = $meta_obj->effective_prereqs; my $requires = $prereqs->requirements_for(qw/runtime requires/); my $build_requires = $prereqs->requirements_for(qw/build requires/); my $test_requires = $prereqs->requirements_for(qw/test requires/); # XXX we don't yet distinguish build vs test, so merge them for now $build_requires->add_requirements($test_requires); $req = $requires->as_string_hash; $breq = $build_requires->as_string_hash; # XXX assemble optional_req && optional_breq from recommends/suggests # depending on corresponding policies -- xdg, 2012-04-01 CPAN->use_inst("CPAN::Meta::Requirements"); my $opt_runtime = CPAN::Meta::Requirements->new; my $opt_build = CPAN::Meta::Requirements->new; if ( $CPAN::Config->{recommends_policy} ) { $opt_runtime->add_requirements( $prereqs->requirements_for(qw/runtime recommends/)); $opt_build->add_requirements( $prereqs->requirements_for(qw/build recommends/)); $opt_build->add_requirements( $prereqs->requirements_for(qw/test recommends/)); } if ( $CPAN::Config->{suggests_policy} ) { $opt_runtime->add_requirements( $prereqs->requirements_for(qw/runtime suggests/)); $opt_build->add_requirements( $prereqs->requirements_for(qw/build suggests/)); $opt_build->add_requirements( $prereqs->requirements_for(qw/test suggests/)); } $opt_req = $opt_runtime->as_string_hash; $opt_breq = $opt_build->as_string_hash; } elsif (my $yaml = $self->read_yaml) { # often dynamic_config prevents a result here $req = $yaml->{requires} || {}; $breq = $yaml->{build_requires} || {}; if ( $CPAN::Config->{recommends_policy} ) { $opt_req = $yaml->{recommends} || {}; } undef $req unless ref $req eq "HASH" && %$req; if ($req) { if ($yaml->{generated_by} && $yaml->{generated_by} =~ /ExtUtils::MakeMaker version ([\d\._]+)/) { my $eummv = do { local $^W = 0; $1+0; }; if ($eummv < 6.2501) { # thanks to Slaven for digging that out: MM before # that could be wrong because it could reflect a # previous release undef $req; } } my $areq; my $do_replace; foreach my $k (sort keys %{$req||{}}) { my $v = $req->{$k}; next unless defined $v; if ($v =~ /\d/) { $areq->{$k} = $v; } elsif ($k =~ /[A-Za-z]/ && $v =~ /[A-Za-z]/ && $CPAN::META->exists("CPAN::Module",$v) ) { $CPAN::Frontend->mywarn("Suspicious key-value pair in META.yml's ". "requires hash: $k => $v; I'll take both ". "key and value as a module name\n"); $CPAN::Frontend->mysleep(1); $areq->{$k} = 0; $areq->{$v} = 0; $do_replace++; } } $req = $areq if $do_replace; } } else { $CPAN::Frontend->mywarnonce("Could not read metadata file. Falling back to other ". "methods to determine prerequisites\n"); } unless ($req || $breq) { my $build_dir; unless ( $build_dir = $self->{build_dir} ) { return; } my $makefile = File::Spec->catfile($build_dir,"Makefile"); my $fh; if (-f $makefile and $fh = FileHandle->new("<$makefile\0")) { CPAN->debug("Getting prereq from Makefile") if $CPAN::DEBUG; local($/) = "\n"; while (<$fh>) { last if /MakeMaker post_initialize section/; my($p) = m{^[\#] \s+PREREQ_PM\s+=>\s+(.+) }x; next unless $p; # warn "Found prereq expr[$p]"; # Regexp modified by A.Speer to remember actual version of file # PREREQ_PM hash key wants, then add to while ( $p =~ m/(?:\s)([\w\:]+)=>(q\[.*?\]|undef),?/g ) { my($m,$n) = ($1,$2); # When a prereq is mentioned twice: let the bigger # win; usual culprit is that they declared # build_requires separately from requires; see # rt.cpan.org #47774 my($prevn); if ( defined $req->{$m} ) { $prevn = $req->{$m}; } if ($n =~ /^q\[(.*?)\]$/) { $n = $1; } if (!$prevn || CPAN::Version->vlt($prevn, $n)){ $req->{$m} = $n; } } last; } } } unless ($req || $breq) { my $build_dir = $self->{build_dir} or die "Panic: no build_dir?"; my $buildfile = File::Spec->catfile($build_dir,"Build"); if (-f $buildfile) { CPAN->debug("Found '$buildfile'") if $CPAN::DEBUG; my $build_prereqs = File::Spec->catfile($build_dir,"_build","prereqs"); if (-f $build_prereqs) { CPAN->debug("Getting prerequisites from '$build_prereqs'") if $CPAN::DEBUG; my $content = do { local *FH; open FH, $build_prereqs or $CPAN::Frontend->mydie("Could not open ". "'$build_prereqs': $!"); local $/; ; }; my $bphash = eval $content; if ($@) { } else { $req = $bphash->{requires} || +{}; $breq = $bphash->{build_requires} || +{}; } } } } # XXX needs to be adapted for optional_req & optional_breq -- xdg, 2012-04-01 if ($req || $breq || $opt_req || $opt_breq ) { return $self->{prereq_pm} = { requires => $req, build_requires => $breq, opt_requires => $opt_req, opt_build_requires => $opt_breq, }; } } #-> sub CPAN::Distribution::shortcut_test ; # return values: undef means don't shortcut; 0 means shortcut as fail; # and 1 means shortcut as success sub shortcut_test { my ($self) = @_; $self->debug("checking badtestcnt[$self->{ID}]") if $CPAN::DEBUG; $self->{badtestcnt} ||= 0; if ($self->{badtestcnt} > 0) { require Data::Dumper; CPAN->debug(sprintf "NOREPEAT[%s]", Data::Dumper::Dumper($self)) if $CPAN::DEBUG; return $self->goodbye("Won't repeat unsuccessful test during this command"); } for my $slot ( qw/later configure_requires_later/ ) { $self->debug("checking $slot slot[$self->{ID}]") if $CPAN::DEBUG; return $self->success($self->{$slot}) if $self->{$slot}; } $self->debug("checking if tests passed[$self->{ID}]") if $CPAN::DEBUG; if ( $self->{make_test} ) { if ( UNIVERSAL::can($self->{make_test},"failed") ? $self->{make_test}->failed : $self->{make_test} =~ /^NO/ ) { if ( UNIVERSAL::can($self->{make_test},"commandid") && $self->{make_test}->commandid == $CPAN::CurrentCommandId ) { return $self->goodbye("Has already been tested within this command"); } } else { # if global "is_tested" has been cleared, we need to mark this to # be added to PERL5LIB if not already installed if ($self->tested_ok_but_not_installed) { $CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME}); } return $self->success("Has already been tested successfully"); } } if ($self->{notest}) { $self->{make_test} = CPAN::Distrostatus->new("YES"); return $self->success("Skipping test because of notest pragma"); } return undef; # no shortcut } #-> sub CPAN::Distribution::_exe_files ; sub _exe_files { my($self) = @_; return unless $self->{writemakefile} # no need to have succeeded # but we must have run it || $self->{modulebuild}; unless ($self->{build_dir}) { return; } CPAN->debug(sprintf "writemakefile[%s]modulebuild[%s]", $self->{writemakefile}||"", $self->{modulebuild}||"", ) if $CPAN::DEBUG; my $build_dir; unless ( $build_dir = $self->{build_dir} ) { return; } my $makefile = File::Spec->catfile($build_dir,"Makefile"); my $fh; my @exe_files; if (-f $makefile and $fh = FileHandle->new("<$makefile\0")) { CPAN->debug("Getting exefiles from Makefile") if $CPAN::DEBUG; local($/) = "\n"; while (<$fh>) { last if /MakeMaker post_initialize section/; my($p) = m{^[\#] \s+EXE_FILES\s+=>\s+\[(.+)\] }x; next unless $p; # warn "Found exefiles expr[$p]"; my @p = split /,\s*/, $p; for my $p2 (@p) { if ($p2 =~ /^q\[(.+)\]/) { push @exe_files, $1; } } } } return \@exe_files if @exe_files; my $buildparams = File::Spec->catfile($build_dir,"_build","build_params"); if (-f $buildparams) { CPAN->debug("Found '$buildparams'") if $CPAN::DEBUG; my $x = do $buildparams; for my $sf ($x->[2]{script_files}) { if (my $reftype = ref $sf) { if ($reftype eq "ARRAY") { push @exe_files, @$sf; } elsif ($reftype eq "HASH") { push @exe_files, keys %$sf; } else { $CPAN::Frontend->mywarn("Invalid reftype $reftype for Build.PL 'script_files'\n"); } } elsif (defined $sf) { push @exe_files, $sf; } } } return \@exe_files; } #-> sub CPAN::Distribution::test ; sub test { my($self) = @_; $self->pre_test(); if (exists $self->{cleanup_after_install_done}) { $self->post_test(); return $self->make; } $self->debug("checking goto id[$self->{ID}]") if $CPAN::DEBUG; if (my $goto = $self->prefs->{goto}) { $self->post_test(); return $self->goto($goto); } unless ($self->make){ $self->post_test(); return; } if ( defined( my $sc = $self->shortcut_test ) ) { $self->post_test(); return $sc; } if ($CPAN::Signal) { delete $self->{force_update}; $self->post_test(); return; } # warn "XDEBUG: checking for notest: $self->{notest} $self"; my $make = $self->{modulebuild} ? "Build" : "make"; local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : ""; local $ENV{PERL_USE_UNSAFE_INC} = exists $ENV{PERL_USE_UNSAFE_INC} && defined $ENV{PERL_USE_UNSAFE_INC} ? $ENV{PERL_USE_UNSAFE_INC} : 1; # test $CPAN::META->set_perl5lib; local $ENV{MAKEFLAGS}; # protect us from outer make calls local $ENV{PERL_MM_USE_DEFAULT} = 1 if $CPAN::Config->{use_prompt_default}; local $ENV{NONINTERACTIVE_TESTING} = 1 if $CPAN::Config->{use_prompt_default}; if ($run_allow_installing_within_test) { my($allow_installing, $why) = $self->_allow_installing; if (! $allow_installing) { $CPAN::Frontend->mywarn("Testing/Installation stopped: $why\n"); $self->introduce_myself; $self->{make_test} = CPAN::Distrostatus->new("NO -- testing/installation stopped due $why"); $CPAN::Frontend->mywarn(" [testing] -- NOT OK\n"); delete $self->{force_update}; $self->post_test(); return; } } $CPAN::Frontend->myprint(sprintf "Running %s test for %s\n", $make, $self->pretty_id); my $builddir = $self->dir or $CPAN::Frontend->mydie("PANIC: Cannot determine build directory\n"); unless (chdir $builddir) { $CPAN::Frontend->mywarn("Couldn't chdir to '$builddir': $!"); $self->post_test(); return; } $self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG; if ($^O eq 'MacOS') { Mac::BuildTools::make_test($self); $self->post_test(); return; } if ($self->{modulebuild}) { my $thm = CPAN::Shell->expand("Module","Test::Harness"); my $v = $thm->inst_version; if (CPAN::Version->vlt($v,2.62)) { # XXX Eric Wilhelm reported this as a bug: klapperl: # Test::Harness 3.0 self-tests, so that should be 'unless # installing Test::Harness' unless ($self->id eq $thm->distribution->id) { $CPAN::Frontend->mywarn(qq{The version of your Test::Harness is only '$v', you need at least '2.62'. Please upgrade your Test::Harness.\n}); $self->{make_test} = CPAN::Distrostatus->new("NO Test::Harness too old"); $self->post_test(); return; } } } if ( ! $self->{force_update} ) { # bypass actual tests if "trust_test_report_history" and have a report my $have_tested_fcn; if ( $CPAN::Config->{trust_test_report_history} && $CPAN::META->has_inst("CPAN::Reporter::History") && ( $have_tested_fcn = CPAN::Reporter::History->can("have_tested" ))) { if ( my @reports = $have_tested_fcn->( dist => $self->base_id ) ) { # Do nothing if grade was DISCARD if ( $reports[-1]->{grade} =~ /^(?:PASS|UNKNOWN)$/ ) { $self->{make_test} = CPAN::Distrostatus->new("YES"); # if global "is_tested" has been cleared, we need to mark this to # be added to PERL5LIB if not already installed if ($self->tested_ok_but_not_installed) { $CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME}); } $CPAN::Frontend->myprint("Found prior test report -- OK\n"); $self->post_test(); return; } elsif ( $reports[-1]->{grade} =~ /^(?:FAIL|NA)$/ ) { $self->{make_test} = CPAN::Distrostatus->new("NO"); $self->{badtestcnt}++; $CPAN::Frontend->mywarn("Found prior test report -- NOT OK\n"); $self->post_test(); return; } } } } my $system; my $prefs_test = $self->prefs->{test}; if (my $commandline = exists $prefs_test->{commandline} ? $prefs_test->{commandline} : "") { $system = $commandline; $ENV{PERL} = CPAN::find_perl(); } elsif ($self->{modulebuild}) { $system = sprintf "%s test", $self->_build_command(); unless (-e "Build" || ($^O eq 'VMS' && -e "Build.com")) { my $id = $self->pretty_id; $CPAN::Frontend->mywarn("Alert: no 'Build' file found while trying to test '$id'"); } } else { $system = join " ", $self->_make_command(), "test"; } my $make_test_arg = $self->_make_phase_arg("test"); $system = sprintf("%s%s", $system, $make_test_arg ? " $make_test_arg" : "", ); my($tests_ok); my $test_env; if ($self->prefs->{test}) { $test_env = $self->prefs->{test}{env}; } local @ENV{keys %$test_env} = values %$test_env if $test_env; my $expect_model = $self->_prefs_with_expect("test"); my $want_expect = 0; if ( $expect_model && @{$expect_model->{talk}} ) { my $can_expect = $CPAN::META->has_inst("Expect"); if ($can_expect) { $want_expect = 1; } else { $CPAN::Frontend->mywarn("Expect not installed, falling back to ". "testing without\n"); } } FORK: { my $pid = fork; if (! defined $pid) { # contention warn "Contention '$!', sleeping 2"; sleep 2; redo FORK; } elsif ($pid) { # parent if ($^O eq "MSWin32") { wait; } else { SUPERVISE: while (waitpid($pid, WNOHANG) <= 0) { if ($CPAN::Signal) { kill 9, -$pid; } sleep 1; } } $tests_ok = !$?; } else { # child POSIX::setsid() unless $^O eq "MSWin32"; my $c_ok; $|=1; if ($want_expect) { if ($self->_should_report('test')) { $CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is currently ". "not supported when distroprefs specify ". "an interactive test\n"); } $c_ok = $self->_run_via_expect($system,'test',$expect_model) == 0; } elsif ( $self->_should_report('test') ) { $c_ok = CPAN::Reporter::test($self, $system); } else { $c_ok = system($system) == 0; } exit !$c_ok; } } # FORK $self->introduce_myself; my $but = $self->_make_test_illuminate_prereqs(); if ( $tests_ok ) { if ($but) { $CPAN::Frontend->mywarn("Tests succeeded but $but\n"); $self->{make_test} = CPAN::Distrostatus->new("NO $but"); $self->store_persistent_state; $self->post_test(); return $self->goodbye("[dependencies] -- NA"); } $CPAN::Frontend->myprint(" $system -- OK\n"); $self->{make_test} = CPAN::Distrostatus->new("YES"); $CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME}); # probably impossible to need the next line because badtestcnt # has a lifespan of one command delete $self->{badtestcnt}; } else { if ($but) { $but .= "; additionally test harness failed"; $CPAN::Frontend->mywarn("$but\n"); $self->{make_test} = CPAN::Distrostatus->new("NO $but"); } elsif ( $self->{force_update} ) { $self->{make_test} = CPAN::Distrostatus->new( "NO but failure ignored because 'force' in effect" ); } elsif ($CPAN::Signal) { $self->{make_test} = CPAN::Distrostatus->new("NO -- Interrupted"); } else { $self->{make_test} = CPAN::Distrostatus->new("NO"); } $self->{badtestcnt}++; $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); CPAN::Shell->optprint ("hint", sprintf ("//hint// to see the cpan-testers results for installing this module, try: reports %s\n", $self->pretty_id)); } $self->store_persistent_state; $self->post_test(); return $self->{force_update} ? 1 : !! $tests_ok; } sub _make_test_illuminate_prereqs { my($self) = @_; my @prereq; # local $CPAN::DEBUG = 16; # Distribution for my $m (sort keys %{$self->{sponsored_mods}}) { next unless $self->{sponsored_mods}{$m} > 0; my $m_obj = CPAN::Shell->expand("Module",$m) or next; # XXX we need available_version which reflects # $ENV{PERL5LIB} so that already tested but not yet # installed modules are counted. my $available_version = $m_obj->available_version; my $available_file = $m_obj->available_file; if ($available_version && !CPAN::Version->vlt($available_version,$self->{prereq_pm}{$m}) ) { CPAN->debug("m[$m] good enough available_version[$available_version]") if $CPAN::DEBUG; } elsif ($available_file && ( !$self->{prereq_pm}{$m} || $self->{prereq_pm}{$m} == 0 ) ) { # lex Class::Accessor::Chained::Fast which has no $VERSION CPAN->debug("m[$m] have available_file[$available_file]") if $CPAN::DEBUG; } else { push @prereq, $m unless $self->is_locally_optional(undef, $m); } } my $but; if (@prereq) { my $cnt = @prereq; my $which = join ",", @prereq; $but = $cnt == 1 ? "one dependency not OK ($which)" : "$cnt dependencies missing ($which)"; } $but; } sub _prefs_with_expect { my($self,$where) = @_; return unless my $prefs = $self->prefs; return unless my $where_prefs = $prefs->{$where}; if ($where_prefs->{expect}) { return { mode => "deterministic", timeout => 15, talk => $where_prefs->{expect}, }; } elsif ($where_prefs->{"eexpect"}) { return $where_prefs->{"eexpect"}; } return; } #-> sub CPAN::Distribution::clean ; sub clean { my($self) = @_; my $make = $self->{modulebuild} ? "Build" : "make"; $CPAN::Frontend->myprint(sprintf "Running %s clean for %s\n", $make, $self->pretty_id); unless (exists $self->{archived}) { $CPAN::Frontend->mywarn("Distribution seems to have never been unzipped". "/untarred, nothing done\n"); return 1; } unless (exists $self->{build_dir}) { $CPAN::Frontend->mywarn("Distribution has no own directory, nothing to do.\n"); return 1; } if (exists $self->{writemakefile} and $self->{writemakefile}->failed ) { $CPAN::Frontend->mywarn("No Makefile, don't know how to 'make clean'\n"); return 1; } EXCUSE: { my @e; exists $self->{make_clean} and $self->{make_clean} eq "YES" and push @e, "make clean already called once"; $CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e; } chdir "$self->{build_dir}" or Carp::confess("Couldn't chdir to $self->{build_dir}: $!"); $self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG; if ($^O eq 'MacOS') { Mac::BuildTools::make_clean($self); return; } my $system; if ($self->{modulebuild}) { unless (-f "Build") { my $cwd = CPAN::anycwd(); $CPAN::Frontend->mywarn("Alert: no Build file available for 'clean $self->{id}". " in cwd[$cwd]. Danger, Will Robinson!"); $CPAN::Frontend->mysleep(5); } $system = sprintf "%s clean", $self->_build_command(); } else { $system = join " ", $self->_make_command(), "clean"; } my $system_ok = system($system) == 0; $self->introduce_myself; if ( $system_ok ) { $CPAN::Frontend->myprint(" $system -- OK\n"); # $self->force; # Jost Krieger pointed out that this "force" was wrong because # it has the effect that the next "install" on this distribution # will untar everything again. Instead we should bring the # object's state back to where it is after untarring. for my $k (qw( force_update install writemakefile make make_test )) { delete $self->{$k}; } $self->{make_clean} = CPAN::Distrostatus->new("YES"); } else { # Hmmm, what to do if make clean failed? $self->{make_clean} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(qq{ $system -- NOT OK\n}); # 2006-02-27: seems silly to me to force a make now # $self->force("make"); # so that this directory won't be used again } $self->store_persistent_state; } #-> sub CPAN::Distribution::check_disabled ; sub check_disabled { my ($self) = @_; $self->debug("checking disabled id[$self->{ID}]") if $CPAN::DEBUG; if ($self->prefs->{disabled} && ! $self->{force_update}) { return sprintf( "Disabled via prefs file '%s' doc %d", $self->{prefs_file}, $self->{prefs_file_doc}, ); } return; } #-> sub CPAN::Distribution::goto ; sub goto { my($self,$goto) = @_; $goto = $self->normalize($goto); my $why = sprintf( "Goto '$goto' via prefs file '%s' doc %d", $self->{prefs_file}, $self->{prefs_file_doc}, ); $self->{unwrapped} = CPAN::Distrostatus->new("NO $why"); # 2007-07-16 akoenig : Better than NA would be if we could inherit # the status of the $goto distro but given the exceptional nature # of 'goto' I feel reluctant to implement it my $goodbye_message = "[goto] -- NA $why"; $self->goodbye($goodbye_message); # inject into the queue CPAN::Queue->delete($self->id); CPAN::Queue->jumpqueue({qmod => $goto, reqtype => $self->{reqtype}}); # and run where we left off my($method) = (caller(1))[3]; my $goto_do = CPAN->instance("CPAN::Distribution",$goto); $goto_do->called_for($self->called_for) unless $goto_do->called_for; $goto_do->{mandatory} ||= $self->{mandatory}; $goto_do->{reqtype} ||= $self->{reqtype}; $goto_do->{coming_from} = $self->pretty_id; $goto_do->$method(); CPAN::Queue->delete_first($goto); # XXX delete_first returns undef; is that what this should return # up the call stack, eg. return $sefl->goto($goto) -- xdg, 2012-04-04 } #-> sub CPAN::Distribution::shortcut_install ; # return values: undef means don't shortcut; 0 means shortcut as fail; # and 1 means shortcut as success sub shortcut_install { my ($self) = @_; $self->debug("checking previous install results[$self->{ID}]") if $CPAN::DEBUG; if (exists $self->{install}) { my $text = UNIVERSAL::can($self->{install},"text") ? $self->{install}->text : $self->{install}; if ($text =~ /^YES/) { $CPAN::META->is_installed($self->{build_dir}); return $self->success("Already done"); } elsif ($text =~ /is only/) { # e.g. 'is only build_requires': may be overruled later return $self->goodbye($text); } else { # comment in Todo on 2006-02-11; maybe retry? return $self->goodbye("Already tried without success"); } } for my $slot ( qw/later configure_requires_later/ ) { return $self->success($self->{$slot}) if $self->{$slot}; } return undef; } #-> sub CPAN::Distribution::is_being_sponsored ; # returns true if we find a distro object in the queue that has # sponsored this one sub is_being_sponsored { my($self) = @_; my $iterator = CPAN::Queue->iterator; QITEM: while (my $q = $iterator->()) { my $s = $q->as_string; my $obj = CPAN::Shell->expandany($s) or next QITEM; my $type = ref $obj; if ( $type eq 'CPAN::Distribution' ){ for my $module (sort keys %{$obj->{sponsored_mods} || {}}) { return 1 if grep { $_ eq $module } $self->containsmods; } } } return 0; } #-> sub CPAN::Distribution::install ; sub install { my($self) = @_; $self->pre_install(); if (exists $self->{cleanup_after_install_done}) { return $self->test; } $self->debug("checking goto id[$self->{ID}]") if $CPAN::DEBUG; if (my $goto = $self->prefs->{goto}) { $self->goto($goto); $self->post_install(); return; } unless ($self->test) { $self->post_install(); return; } if ( defined( my $sc = $self->shortcut_install ) ) { $self->post_install(); return $sc; } if ($CPAN::Signal) { delete $self->{force_update}; $self->post_install(); return; } my $builddir = $self->dir or $CPAN::Frontend->mydie("PANIC: Cannot determine build directory\n"); unless (chdir $builddir) { $CPAN::Frontend->mywarn("Couldn't chdir to '$builddir': $!"); $self->post_install(); return; } $self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG; my $make = $self->{modulebuild} ? "Build" : "make"; $CPAN::Frontend->myprint(sprintf "Running %s install for %s\n", $make, $self->pretty_id); if ($^O eq 'MacOS') { Mac::BuildTools::make_install($self); $self->post_install(); return; } my $system; if (my $commandline = $self->prefs->{install}{commandline}) { $system = $commandline; $ENV{PERL} = CPAN::find_perl(); } elsif ($self->{modulebuild}) { my($mbuild_install_build_command) = exists $CPAN::HandleConfig::keys{mbuild_install_build_command} && $CPAN::Config->{mbuild_install_build_command} ? $CPAN::Config->{mbuild_install_build_command} : $self->_build_command(); my $install_directive = $^O eq 'VMS' ? '"install"' : 'install'; $system = sprintf("%s %s %s", $mbuild_install_build_command, $install_directive, $CPAN::Config->{mbuild_install_arg}, ); } else { my($make_install_make_command) = $self->_make_install_make_command(); $system = sprintf("%s install %s", $make_install_make_command, $CPAN::Config->{make_install_arg}, ); } my($stderr) = $^O eq "MSWin32" || $^O eq 'VMS' ? "" : " 2>&1 "; my $brip = CPAN::HandleConfig->prefs_lookup($self, q{build_requires_install_policy}); $brip ||="ask/yes"; my $id = $self->id; my $reqtype = $self->{reqtype} ||= "c"; # in doubt it was a command my $want_install = "yes"; if ($reqtype eq "b") { if ($brip eq "no") { $want_install = "no"; } elsif ($brip =~ m|^ask/(.+)|) { my $default = $1; $default = "yes" unless $default =~ /^(y|n)/i; $want_install = CPAN::Shell::colorable_makemaker_prompt ("$id is just needed temporarily during building or testing. ". "Do you want to install it permanently?", $default); } } unless ($want_install =~ /^y/i) { my $is_only = "is only 'build_requires'"; $self->{install} = CPAN::Distrostatus->new("NO -- $is_only"); delete $self->{force_update}; $self->goodbye("Not installing because $is_only"); $self->post_install(); return; } local $ENV{PERL5LIB} = defined($ENV{PERL5LIB}) ? $ENV{PERL5LIB} : ($ENV{PERLLIB} || ""); local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : ""; local $ENV{PERL_USE_UNSAFE_INC} = exists $ENV{PERL_USE_UNSAFE_INC} && defined $ENV{PERL_USE_UNSAFE_INC} ? $ENV{PERL_USE_UNSAFE_INC} : 1; # install $CPAN::META->set_perl5lib; local $ENV{PERL_MM_USE_DEFAULT} = 1 if $CPAN::Config->{use_prompt_default}; local $ENV{NONINTERACTIVE_TESTING} = 1 if $CPAN::Config->{use_prompt_default}; my $install_env; if ($self->prefs->{install}) { $install_env = $self->prefs->{install}{env}; } local @ENV{keys %$install_env} = values %$install_env if $install_env; if (! $run_allow_installing_within_test) { my($allow_installing, $why) = $self->_allow_installing; if (! $allow_installing) { $CPAN::Frontend->mywarn("Installation stopped: $why\n"); $self->introduce_myself; $self->{install} = CPAN::Distrostatus->new("NO -- installation stopped due $why"); $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); delete $self->{force_update}; $self->post_install(); return; } } my($pipe) = FileHandle->new("$system $stderr |"); unless ($pipe) { $CPAN::Frontend->mywarn("Can't execute $system: $!"); $self->introduce_myself; $self->{install} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); delete $self->{force_update}; $self->post_install(); return; } my($makeout) = ""; while (<$pipe>) { print $_; # intentionally NOT use Frontend->myprint because it # looks irritating when we markup in color what we # just pass through from an external program $makeout .= $_; } $pipe->close; my $close_ok = $? == 0; $self->introduce_myself; if ( $close_ok ) { $CPAN::Frontend->myprint(" $system -- OK\n"); $CPAN::META->is_installed($self->{build_dir}); $self->{install} = CPAN::Distrostatus->new("YES"); if ($CPAN::Config->{'cleanup_after_install'} && ! $self->is_dot_dist && ! $self->is_being_sponsored) { my $parent = File::Spec->catdir( $self->{build_dir}, File::Spec->updir ); chdir $parent or $CPAN::Frontend->mydie("Couldn't chdir to $parent: $!\n"); File::Path::rmtree($self->{build_dir}); my $yml = "$self->{build_dir}.yml"; if (-e $yml) { unlink $yml or $CPAN::Frontend->mydie("Couldn't unlink $yml: $!\n"); } $self->{cleanup_after_install_done}=1; } } else { $self->{install} = CPAN::Distrostatus->new("NO"); $CPAN::Frontend->mywarn(" $system -- NOT OK\n"); my $mimc = CPAN::HandleConfig->prefs_lookup($self, q{make_install_make_command}); if ( $makeout =~ /permission/s && $> > 0 && ( ! $mimc || $mimc eq (CPAN::HandleConfig->prefs_lookup($self, q{make})) ) ) { $CPAN::Frontend->myprint( qq{----\n}. qq{ You may have to su }. qq{to root to install the package\n}. qq{ (Or you may want to run something like\n}. qq{ o conf make_install_make_command 'sudo make'\n}. qq{ to raise your permissions.} ); } } delete $self->{force_update}; unless ($CPAN::Config->{'cleanup_after_install'}) { $self->store_persistent_state; } $self->post_install(); return !! $close_ok; } sub blib_pm_walk { my @queue = grep { -e $_ } File::Spec->catdir("blib","lib"), File::Spec->catdir("blib","arch"); return sub { LOOP: { if (@queue) { my $file = shift @queue; if (-d $file) { my $dh; opendir $dh, $file or next; my @newfiles = map { my @ret; my $maybedir = File::Spec->catdir($file, $_); if (-d $maybedir) { unless (File::Spec->catdir("blib","arch","auto") eq $maybedir) { # prune the blib/arch/auto directory, no pm files there @ret = $maybedir; } } elsif (/\.pm$/) { my $mustbefile = File::Spec->catfile($file, $_); if (-f $mustbefile) { @ret = $mustbefile; } } @ret; } grep { $_ ne "." && $_ ne ".." } readdir $dh; push @queue, @newfiles; redo LOOP; } else { return $file; } } else { return; } } }; } sub _allow_installing { my($self) = @_; my $id = my $pretty_id = $self->pretty_id; if ($self->{CALLED_FOR}) { $id .= " (called for $self->{CALLED_FOR})"; } my $allow_down = CPAN::HandleConfig->prefs_lookup($self,q{allow_installing_module_downgrades}); $allow_down ||= "ask/yes"; my $allow_outdd = CPAN::HandleConfig->prefs_lookup($self,q{allow_installing_outdated_dists}); $allow_outdd ||= "ask/yes"; return 1 if $allow_down eq "yes" && $allow_outdd eq "yes"; if (($allow_outdd ne "yes") && ! $CPAN::META->has_inst('CPAN::DistnameInfo')) { return 1 if grep { $_ eq 'CPAN::DistnameInfo'} $self->containsmods; if ($allow_outdd ne "yes") { $CPAN::Frontend->mywarn("The current configuration of allow_installing_outdated_dists is '$allow_outdd', but for this option we would need 'CPAN::DistnameInfo' installed. Please install 'CPAN::DistnameInfo' as soon as possible. As long as we are not equipped with 'CPAN::DistnameInfo' this option does not take effect\n"); $allow_outdd = "yes"; } } return 1 if $allow_down eq "yes" && $allow_outdd eq "yes"; my($dist_version, $dist_dist); if ($allow_outdd ne "yes"){ my $dni = CPAN::DistnameInfo->new($pretty_id); $dist_version = $dni->version; $dist_dist = $dni->dist; } my $iterator = blib_pm_walk(); my(@down,@outdd); while (my $file = $iterator->()) { my $version = CPAN::Module->parse_version($file); my($volume, $directories, $pmfile) = File::Spec->splitpath( $file ); my @dirs = File::Spec->splitdir( $directories ); my(@blib_plus1) = splice @dirs, 0, 2; my($pmpath) = File::Spec->catfile(grep { length($_) } @dirs, $pmfile); unless ($allow_down eq "yes") { if (my $inst_file = $self->_file_in_path($pmpath, \@INC)) { my $inst_version = CPAN::Module->parse_version($inst_file); my $cmp = CPAN::Version->vcmp($version, $inst_version); if ($cmp) { if ($cmp < 0) { push @down, { pmpath => $pmpath, version => $version, inst_version => $inst_version }; } } if (@down) { my $why = "allow_installing_module_downgrades: $id contains downgrading module(s) (e.g. '$down[0]{pmpath}' would downgrade installed '$down[0]{inst_version}' to '$down[0]{version}')"; if (my($default) = $allow_down =~ m|^ask/(.+)|) { $default = "yes" unless $default =~ /^(y|n)/i; my $answer = CPAN::Shell::colorable_makemaker_prompt ("$why. Do you want to allow installing it?", $default, "colorize_warn"); $allow_down = $answer =~ /^\s*y/i ? "yes" : "no"; } if ($allow_down eq "no") { return (0, $why); } } } } unless ($allow_outdd eq "yes") { my @pmpath = (@dirs, $pmfile); $pmpath[-1] =~ s/\.pm$//; my $mo = CPAN::Shell->expand("Module",join "::", grep { length($_) } @pmpath); if ($mo) { my $cpan_version = $mo->cpan_version; my $is_lower = CPAN::Version->vlt($version, $cpan_version); my $other_dist; if (my $mo_dist = $mo->distribution) { $other_dist = $mo_dist->pretty_id; my $dni = CPAN::DistnameInfo->new($other_dist); if ($dni->dist eq $dist_dist){ if (CPAN::Version->vgt($dni->version, $dist_version)) { push @outdd, { pmpath => $pmpath, cpan_path => $dni->pathname, dist_version => $dni->version, dist_dist => $dni->dist, }; } } } } if (@outdd && $allow_outdd ne "yes") { my $why = "allow_installing_outdated_dists: $id contains module(s) that are indexed on the CPAN with a different distro: (e.g. '$outdd[0]{pmpath}' is indexed with '$outdd[0]{cpan_path}')"; if ($outdd[0]{dist_dist} eq $dist_dist) { $why .= ", and this has a higher distribution-version, i.e. version '$outdd[0]{dist_version}' is higher than '$dist_version')"; } if (my($default) = $allow_outdd =~ m|^ask/(.+)|) { $default = "yes" unless $default =~ /^(y|n)/i; my $answer = CPAN::Shell::colorable_makemaker_prompt ("$why. Do you want to allow installing it?", $default, "colorize_warn"); $allow_outdd = $answer =~ /^\s*y/i ? "yes" : "no"; } if ($allow_outdd eq "no") { return (0, $why); } } } } return 1; } sub _file_in_path { # similar to CPAN::Module::_file_in_path my($self,$pmpath,$incpath) = @_; my($dir,@packpath); foreach $dir (@$incpath) { my $pmfile = File::Spec->catfile($dir,$pmpath); if (-f $pmfile) { return $pmfile; } } return; } sub introduce_myself { my($self) = @_; $CPAN::Frontend->myprint(sprintf(" %s\n",$self->pretty_id)); } #-> sub CPAN::Distribution::dir ; sub dir { shift->{build_dir}; } #-> sub CPAN::Distribution::perldoc ; sub perldoc { my($self) = @_; my($dist) = $self->id; my $package = $self->called_for; if ($CPAN::META->has_inst("Pod::Perldocs")) { my($perl) = $self->perl or $CPAN::Frontend->mydie("Couldn't find executable perl\n"); my @args = ($perl, q{-MPod::Perldocs}, q{-e}, q{Pod::Perldocs->run()}, $package); my($wstatus); unless ( ($wstatus = system(@args)) == 0 ) { my $estatus = $wstatus >> 8; $CPAN::Frontend->myprint(qq{ Function system("@args") returned status $estatus (wstat $wstatus) }); } } else { $self->_display_url( $CPAN::Defaultdocs . $package ); } } #-> sub CPAN::Distribution::_check_binary ; sub _check_binary { my ($dist,$shell,$binary) = @_; my ($pid,$out); $CPAN::Frontend->myprint(qq{ + _check_binary($binary)\n}) if $CPAN::DEBUG; if ($CPAN::META->has_inst("File::Which")) { return File::Which::which($binary); } else { local *README; $pid = open README, "which $binary|" or $CPAN::Frontend->mywarn(qq{Could not fork 'which $binary': $!\n}); return unless $pid; while () { $out .= $_; } close README or $CPAN::Frontend->mywarn("Could not run 'which $binary': $!\n") and return; } $CPAN::Frontend->myprint(qq{ + $out \n}) if $CPAN::DEBUG && $out; return $out; } #-> sub CPAN::Distribution::_display_url ; sub _display_url { my($self,$url) = @_; my($res,$saved_file,$pid,$out); $CPAN::Frontend->myprint(qq{ + _display_url($url)\n}) if $CPAN::DEBUG; # should we define it in the config instead? my $html_converter = "html2text.pl"; my $web_browser = $CPAN::Config->{'lynx'} || undef; my $web_browser_out = $web_browser ? CPAN::Distribution->_check_binary($self,$web_browser) : undef; if ($web_browser_out) { # web browser found, run the action my $browser = CPAN::HandleConfig->safe_quote($CPAN::Config->{'lynx'}); $CPAN::Frontend->myprint(qq{system[$browser $url]}) if $CPAN::DEBUG; $CPAN::Frontend->myprint(qq{ Displaying URL $url with browser $browser }); $CPAN::Frontend->mysleep(1); system("$browser $url"); if ($saved_file) { 1 while unlink($saved_file) } } else { # web browser not found, let's try text only my $html_converter_out = CPAN::Distribution->_check_binary($self,$html_converter); $html_converter_out = CPAN::HandleConfig->safe_quote($html_converter_out); if ($html_converter_out ) { # html2text found, run it $saved_file = CPAN::Distribution->_getsave_url( $self, $url ); $CPAN::Frontend->mydie(qq{ERROR: problems while getting $url\n}) unless defined($saved_file); local *README; $pid = open README, "$html_converter $saved_file |" or $CPAN::Frontend->mydie(qq{ Could not fork '$html_converter $saved_file': $!}); my($fh,$filename); if ($CPAN::META->has_usable("File::Temp")) { $fh = File::Temp->new( dir => File::Spec->tmpdir, template => 'cpan_htmlconvert_XXXX', suffix => '.txt', unlink => 0, ); $filename = $fh->filename; } else { $filename = "cpan_htmlconvert_$$.txt"; $fh = FileHandle->new(); open $fh, ">$filename" or die; } while () { $fh->print($_); } close README or $CPAN::Frontend->mydie(qq{Could not run '$html_converter $saved_file': $!}); my $tmpin = $fh->filename; $CPAN::Frontend->myprint(sprintf(qq{ Run '%s %s' and saved output to %s\n}, $html_converter, $saved_file, $tmpin, )) if $CPAN::DEBUG; close $fh; local *FH; open FH, $tmpin or $CPAN::Frontend->mydie(qq{Could not open "$tmpin": $!}); my $fh_pager = FileHandle->new; local($SIG{PIPE}) = "IGNORE"; my $pager = $CPAN::Config->{'pager'} || "cat"; $fh_pager->open("|$pager") or $CPAN::Frontend->mydie(qq{ Could not open pager '$pager': $!}); $CPAN::Frontend->myprint(qq{ Displaying URL $url with pager "$pager" }); $CPAN::Frontend->mysleep(1); $fh_pager->print(); $fh_pager->close; } else { # coldn't find the web browser or html converter $CPAN::Frontend->myprint(qq{ You need to install lynx or $html_converter to use this feature.}); } } } #-> sub CPAN::Distribution::_getsave_url ; sub _getsave_url { my($dist, $shell, $url) = @_; $CPAN::Frontend->myprint(qq{ + _getsave_url($url)\n}) if $CPAN::DEBUG; my($fh,$filename); if ($CPAN::META->has_usable("File::Temp")) { $fh = File::Temp->new( dir => File::Spec->tmpdir, template => "cpan_getsave_url_XXXX", suffix => ".html", unlink => 0, ); $filename = $fh->filename; } else { $fh = FileHandle->new; $filename = "cpan_getsave_url_$$.html"; } my $tmpin = $filename; if ($CPAN::META->has_usable('LWP')) { $CPAN::Frontend->myprint("Fetching with LWP: $url "); my $Ua; CPAN::LWP::UserAgent->config; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mywarn("ERROR: CPAN::LWP::UserAgent->new dies with $@\n"); return; } else { my($var); $Ua->proxy('http', $var) if $var = $CPAN::Config->{http_proxy} || $ENV{http_proxy}; $Ua->no_proxy($var) if $var = $CPAN::Config->{no_proxy} || $ENV{no_proxy}; } my $req = HTTP::Request->new(GET => $url); $req->header('Accept' => 'text/html'); my $res = $Ua->request($req); if ($res->is_success) { $CPAN::Frontend->myprint(" + request successful.\n") if $CPAN::DEBUG; print $fh $res->content; close $fh; $CPAN::Frontend->myprint(qq{ + saved content to $tmpin \n}) if $CPAN::DEBUG; return $tmpin; } else { $CPAN::Frontend->myprint(sprintf( "LWP failed with code[%s], message[%s]\n", $res->code, $res->message, )); return; } } else { $CPAN::Frontend->mywarn(" LWP not available\n"); return; } } #-> sub CPAN::Distribution::_build_command sub _build_command { my($self) = @_; if ($^O eq "MSWin32") { # special code needed at least up to # Module::Build 0.2611 and 0.2706; a fix # in M:B has been promised 2006-01-30 my($perl) = $self->perl or $CPAN::Frontend->mydie("Couldn't find executable perl\n"); return "$perl ./Build"; } elsif ($^O eq 'VMS') { return "$^X Build.com"; } return "./Build"; } #-> sub CPAN::Distribution::_should_report sub _should_report { my($self, $phase) = @_; die "_should_report() requires a 'phase' argument" if ! defined $phase; return unless $CPAN::META->has_usable("CPAN::Reporter"); # configured my $test_report = CPAN::HandleConfig->prefs_lookup($self, q{test_report}); return unless $test_report; # don't repeat if we cached a result return $self->{should_report} if exists $self->{should_report}; # don't report if we generated a Makefile.PL if ( $self->{had_no_makefile_pl} ) { $CPAN::Frontend->mywarn( "Will not send CPAN Testers report with generated Makefile.PL.\n" ); return $self->{should_report} = 0; } # available if ( ! $CPAN::META->has_inst("CPAN::Reporter")) { $CPAN::Frontend->mywarnonce( "CPAN::Reporter not installed. No reports will be sent.\n" ); return $self->{should_report} = 0; } # capable my $crv = CPAN::Reporter->VERSION; if ( CPAN::Version->vlt( $crv, 0.99 ) ) { # don't cache $self->{should_report} -- need to check each phase if ( $phase eq 'test' ) { return 1; } else { $CPAN::Frontend->mywarn( "Reporting on the '$phase' phase requires CPAN::Reporter 0.99, but \n" . "you only have version $crv\. Only 'test' phase reports will be sent.\n" ); return; } } # appropriate if ($self->is_dot_dist) { $CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is disabled ". "for local directories\n"); return $self->{should_report} = 0; } if ($self->prefs->{patches} && @{$self->prefs->{patches}} && $self->{patched} ) { $CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is disabled ". "when the source has been patched\n"); return $self->{should_report} = 0; } # proceed and cache success return $self->{should_report} = 1; } #-> sub CPAN::Distribution::reports sub reports { my($self) = @_; my $pathname = $self->id; $CPAN::Frontend->myprint("Distribution: $pathname\n"); unless ($CPAN::META->has_inst("CPAN::DistnameInfo")) { $CPAN::Frontend->mydie("CPAN::DistnameInfo not installed; cannot continue"); } unless ($CPAN::META->has_usable("LWP")) { $CPAN::Frontend->mydie("LWP not installed; cannot continue"); } unless ($CPAN::META->has_usable("File::Temp")) { $CPAN::Frontend->mydie("File::Temp not installed; cannot continue"); } my $format; if ($CPAN::META->has_inst("YAML::XS") || $CPAN::META->has_inst("YAML::Syck")){ $format = 'yaml'; } elsif (!$format && $CPAN::META->has_inst("JSON::PP") ) { $format = 'json'; } else { $CPAN::Frontend->mydie("JSON::PP not installed, cannot continue"); } my $d = CPAN::DistnameInfo->new($pathname); my $dist = $d->dist; # "CPAN-DistnameInfo" my $version = $d->version; # "0.02" my $maturity = $d->maturity; # "released" my $filename = $d->filename; # "CPAN-DistnameInfo-0.02.tar.gz" my $cpanid = $d->cpanid; # "GBARR" my $distvname = $d->distvname; # "CPAN-DistnameInfo-0.02" my $url = sprintf "http://www.cpantesters.org/show/%s.%s", $dist, $format; CPAN::LWP::UserAgent->config; my $Ua; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mydie("CPAN::LWP::UserAgent->new dies with $@\n"); } $CPAN::Frontend->myprint("Fetching '$url'..."); my $resp = $Ua->get($url); unless ($resp->is_success) { $CPAN::Frontend->mydie(sprintf "Could not download '%s': %s\n", $url, $resp->code); } $CPAN::Frontend->myprint("DONE\n\n"); my $unserialized; if ( $format eq 'yaml' ) { my $yaml = $resp->content; # what a long way round! my $fh = File::Temp->new( dir => File::Spec->tmpdir, template => 'cpan_reports_XXXX', suffix => '.yaml', unlink => 0, ); my $tfilename = $fh->filename; print $fh $yaml; close $fh or $CPAN::Frontend->mydie("Could not close '$tfilename': $!"); $unserialized = CPAN->_yaml_loadfile($tfilename)->[0]; unlink $tfilename or $CPAN::Frontend->mydie("Could not unlink '$tfilename': $!"); } else { require JSON::PP; $unserialized = JSON::PP->new->utf8->decode($resp->content); } my %other_versions; my $this_version_seen; for my $rep (@$unserialized) { my $rversion = $rep->{version}; if ($rversion eq $version) { unless ($this_version_seen++) { $CPAN::Frontend->myprint ("$rep->{version}:\n"); } my $arch = $rep->{archname} || $rep->{platform} || '????'; my $grade = $rep->{action} || $rep->{status} || '????'; my $ostext = $rep->{ostext} || ucfirst($rep->{osname}) || '????'; $CPAN::Frontend->myprint (sprintf("%1s%1s%-4s %s on %s %s (%s)\n", $arch eq $Config::Config{archname}?"*":"", $grade eq "PASS"?"+":$grade eq"FAIL"?"-":"", $grade, $rep->{perl}, $ostext, $rep->{osvers}, $arch, )); } else { $other_versions{$rep->{version}}++; } } unless ($this_version_seen) { $CPAN::Frontend->myprint("No reports found for version '$version' Reports for other versions:\n"); for my $v (sort keys %other_versions) { $CPAN::Frontend->myprint(" $v\: $other_versions{$v}\n"); } } $url = substr($url,0,-4) . 'html'; $CPAN::Frontend->myprint("See $url for details\n"); } 1; PK!:perl5/CPAN/Complete.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Complete; use strict; @CPAN::Complete::ISA = qw(CPAN::Debug); # Q: where is the "How do I add a new command" HOWTO? # A: git log -p -1 355c44e9caaec857e4b12f51afb96498833c3e36 where andk added the report command @CPAN::Complete::COMMANDS = sort qw( ? ! a b d h i m o q r u autobundle bye clean cvs_import dump exit failed force fforce hosts install install_tested is_tested look ls make mkmyconfig notest perldoc quit readme recent recompile reload report reports scripts smoke test upgrade ); use vars qw( $VERSION ); $VERSION = "5.5001"; package CPAN::Complete; use strict; sub gnu_cpl { my($text, $line, $start, $end) = @_; my(@perlret) = cpl($text, $line, $start); # find longest common match. Can anybody show me how to peruse # T::R::Gnu to have this done automatically? Seems expensive. return () unless @perlret; my($newtext) = $text; for (my $i = length($text)+1;;$i++) { last unless length($perlret[0]) && length($perlret[0]) >= $i; my $try = substr($perlret[0],0,$i); my @tries = grep {substr($_,0,$i) eq $try} @perlret; # warn "try[$try]tries[@tries]"; if (@tries == @perlret) { $newtext = $try; } else { last; } } ($newtext,@perlret); } #-> sub CPAN::Complete::cpl ; sub cpl { my($word,$line,$pos) = @_; $word ||= ""; $line ||= ""; $pos ||= 0; CPAN->debug("word [$word] line[$line] pos[$pos]") if $CPAN::DEBUG; $line =~ s/^\s*//; if ($line =~ s/^((?:notest|f?force)\s*)//) { $pos -= length($1); } my @return; if ($pos == 0 || $line =~ /^(?:h(?:elp)?|\?)\s/) { @return = grep /^\Q$word\E/, @CPAN::Complete::COMMANDS; } elsif ( $line !~ /^[\!abcdghimorutl]/ ) { @return = (); } elsif ($line =~ /^a\s/) { @return = cplx('CPAN::Author',uc($word)); } elsif ($line =~ /^ls\s/) { my($author,$rest) = $word =~ m|([^/]+)/?(.*)|; @return = $rest ? () : map {"$_/"} cplx('CPAN::Author',uc($author||"")); if (0 && 1==@return) { # XXX too slow and even wrong when there is a * already @return = grep /^\Q$word\E/, map {"$author/$_->[2]"} CPAN::Shell->expand("Author",$author)->ls("$rest*","2"); } } elsif ($line =~ /^b\s/) { CPAN::Shell->local_bundles; @return = cplx('CPAN::Bundle',$word); } elsif ($line =~ /^d\s/) { @return = cplx('CPAN::Distribution',$word); } elsif ($line =~ m/^( [mru]|make|clean|dump|get|test|install|readme|look|cvs_import|perldoc|recent )\s/x ) { if ($word =~ /^Bundle::/) { CPAN::Shell->local_bundles; } @return = (cplx('CPAN::Module',$word),cplx('CPAN::Bundle',$word)); } elsif ($line =~ /^i\s/) { @return = cpl_any($word); } elsif ($line =~ /^reload\s/) { @return = cpl_reload($word,$line,$pos); } elsif ($line =~ /^o\s/) { @return = cpl_option($word,$line,$pos); } elsif ($line =~ m/^\S+\s/ ) { # fallback for future commands and what we have forgotten above @return = (cplx('CPAN::Module',$word),cplx('CPAN::Bundle',$word)); } else { @return = (); } return @return; } #-> sub CPAN::Complete::cplx ; sub cplx { my($class, $word) = @_; if (CPAN::_sqlite_running()) { $CPAN::SQLite->search($class, "^\Q$word\E"); } my $method = "id"; $method = "pretty_id" if $class eq "CPAN::Distribution"; sort grep /^\Q$word\E/, map { $_->$method() } $CPAN::META->all_objects($class); } #-> sub CPAN::Complete::cpl_any ; sub cpl_any { my($word) = shift; return ( cplx('CPAN::Author',$word), cplx('CPAN::Bundle',$word), cplx('CPAN::Distribution',$word), cplx('CPAN::Module',$word), ); } #-> sub CPAN::Complete::cpl_reload ; sub cpl_reload { my($word,$line,$pos) = @_; $word ||= ""; my(@words) = split " ", $line; CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG; my(@ok) = qw(cpan index); return @ok if @words == 1; return grep /^\Q$word\E/, @ok if @words == 2 && $word; } #-> sub CPAN::Complete::cpl_option ; sub cpl_option { my($word,$line,$pos) = @_; $word ||= ""; my(@words) = split " ", $line; CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG; my(@ok) = qw(conf debug); return @ok if @words == 1; return grep /^\Q$word\E/, @ok if @words == 2 && length($word); if (0) { } elsif ($words[1] eq 'index') { return (); } elsif ($words[1] eq 'conf') { return CPAN::HandleConfig::cpl(@_); } elsif ($words[1] eq 'debug') { return sort grep /^\Q$word\E/i, sort keys %CPAN::DEBUG, 'all'; } } 1; PK!hz.ηperl5/CPAN/FTP.pmnu6$# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::FTP; use strict; use Errno (); use Fcntl qw(:flock); use File::Basename qw(dirname); use File::Path qw(mkpath); use CPAN::FTP::netrc; use vars qw($connect_to_internet_ok $Ua $Thesite $ThesiteURL $Themethod); @CPAN::FTP::ISA = qw(CPAN::Debug); use vars qw( $VERSION ); $VERSION = "5.5016"; sub _plus_append_open { my($fh, $file) = @_; my $parent_dir = dirname $file; mkpath $parent_dir; my($cnt); until (open $fh, "+>>$file") { next if exists &Errno::EAGAIN && $! == &Errno::EAGAIN; # don't increment on EAGAIN $CPAN::Frontend->mydie("Could not open '$file' after 10000 tries: $!") if ++$cnt > 100000; sleep 0.0001; mkpath $parent_dir; } } #-> sub CPAN::FTP::ftp_statistics # if they want to rewrite, they need to pass in a filehandle sub _ftp_statistics { my($self,$fh) = @_; my $ftpstats_size = $CPAN::Config->{ftpstats_size}; return if defined $ftpstats_size && $ftpstats_size <= 0; my $locktype = $fh ? LOCK_EX : LOCK_SH; # XXX On Windows flock() implements mandatory locking, so we can # XXX only use shared locking to still allow _yaml_loadfile() to # XXX read from the file using a different filehandle. $locktype = LOCK_SH if $^O eq "MSWin32"; $fh ||= FileHandle->new; my $file = File::Spec->catfile($CPAN::Config->{cpan_home},"FTPstats.yml"); _plus_append_open($fh,$file); my $sleep = 1; my $waitstart; while (!CPAN::_flock($fh, $locktype|LOCK_NB)) { $waitstart ||= localtime(); if ($sleep>3) { my $now = localtime(); $CPAN::Frontend->mywarn("$now: waiting for read lock on '$file' (since $waitstart)\n"); } sleep($sleep); # this sleep must not be overridden; # Frontend->mysleep with AUTOMATED_TESTING has # provoked complete lock contention on my NFS if ($sleep <= 6) { $sleep+=0.5; } else { # retry to get a fresh handle. If it is NFS and the handle is stale, we will never get an flock _plus_append_open($fh, $file); } } my $stats = eval { CPAN->_yaml_loadfile($file, {loadblessed => 1}); }; if ($@) { if (ref $@) { if (ref $@ eq "CPAN::Exception::yaml_not_installed") { chomp $@; $CPAN::Frontend->myprintonce("Warning (usually harmless): $@\n"); return; } elsif (ref $@ eq "CPAN::Exception::yaml_process_error") { my $time = time; my $to = "$file.$time"; $CPAN::Frontend->mywarn("Error reading '$file': $@ Trying to stash it away as '$to' to prevent further interruptions. You may want to remove that file later.\n"); # may fail because somebody else has moved it away in the meantime: rename $file, $to or $CPAN::Frontend->mywarn("Could not rename '$file' to '$to': $!\n"); return; } } else { $CPAN::Frontend->mydie($@); } } CPAN::_flock($fh, LOCK_UN); return $stats->[0]; } #-> sub CPAN::FTP::_mytime sub _mytime () { if (CPAN->has_inst("Time::HiRes")) { return Time::HiRes::time(); } else { return time; } } #-> sub CPAN::FTP::_new_stats sub _new_stats { my($self,$file) = @_; my $ret = { file => $file, attempts => [], start => _mytime, }; $ret; } #-> sub CPAN::FTP::_add_to_statistics sub _add_to_statistics { my($self,$stats) = @_; my $yaml_module = CPAN::_yaml_module(); $self->debug("yaml_module[$yaml_module]") if $CPAN::DEBUG; if ($CPAN::META->has_inst($yaml_module)) { $stats->{thesiteurl} = $ThesiteURL; $stats->{end} = CPAN::FTP::_mytime(); my $fh = FileHandle->new; my $time = time; my $sdebug = 0; my @debug; @debug = $time if $sdebug; my $fullstats = $self->_ftp_statistics($fh); close $fh if $fh && defined(fileno($fh)); $fullstats->{history} ||= []; push @debug, scalar @{$fullstats->{history}} if $sdebug; push @debug, time if $sdebug; push @{$fullstats->{history}}, $stats; # YAML.pm 0.62 is unacceptably slow with 999; # YAML::Syck 0.82 has no noticable performance problem with 999; my $ftpstats_size = $CPAN::Config->{ftpstats_size}; $ftpstats_size = 99 unless defined $ftpstats_size; my $ftpstats_period = $CPAN::Config->{ftpstats_period} || 14; while ( @{$fullstats->{history} || []} && ( @{$fullstats->{history}} > $ftpstats_size || $time - $fullstats->{history}[0]{start} > 86400*$ftpstats_period ) ) { shift @{$fullstats->{history}} } push @debug, scalar @{$fullstats->{history}} if $sdebug; push @debug, time if $sdebug; push @debug, scalar localtime($fullstats->{history}[0]{start}) if $sdebug; # need no eval because if this fails, it is serious my $sfile = File::Spec->catfile($CPAN::Config->{cpan_home},"FTPstats.yml"); CPAN->_yaml_dumpfile("$sfile.$$",$fullstats); if ( $sdebug ) { local $CPAN::DEBUG = 512; # FTP push @debug, time; CPAN->debug(sprintf("DEBUG history: before_read[%d]before[%d]at[%d]". "after[%d]at[%d]oldest[%s]dumped backat[%d]", @debug, )); } # Win32 cannot rename a file to an existing filename unlink($sfile) if ($^O eq 'MSWin32' or $^O eq 'os2'); _copy_stat($sfile, "$sfile.$$") if -e $sfile; rename "$sfile.$$", $sfile or $CPAN::Frontend->mywarn("Could not rename '$sfile.$$' to '$sfile': $!\nGiving up\n"); } } # Copy some stat information (owner, group, mode and) from one file to # another. # This is a utility function which might be moved to a utility repository. #-> sub CPAN::FTP::_copy_stat sub _copy_stat { my($src, $dest) = @_; my @stat = stat($src); if (!@stat) { $CPAN::Frontend->mywarn("Can't stat '$src': $!\n"); return; } eval { chmod $stat[2], $dest or $CPAN::Frontend->mywarn("Can't chmod '$dest' to " . sprintf("0%o", $stat[2]) . ": $!\n"); }; warn $@ if $@; eval { chown $stat[4], $stat[5], $dest or do { my $save_err = $!; # otherwise it's lost in the get... calls $CPAN::Frontend->mywarn("Can't chown '$dest' to " . (getpwuid($stat[4]))[0] . "/" . (getgrgid($stat[5]))[0] . ": $save_err\n" ); }; }; warn $@ if $@; } # if file is CHECKSUMS, suggest the place where we got the file to be # checked from, maybe only for young files? #-> sub CPAN::FTP::_recommend_url_for sub _recommend_url_for { my($self, $file, $urllist) = @_; if ($file =~ s|/CHECKSUMS(.gz)?$||) { my $fullstats = $self->_ftp_statistics(); my $history = $fullstats->{history} || []; while (my $last = pop @$history) { last if $last->{end} - time > 3600; # only young results are interesting next unless $last->{file}; # dirname of nothing dies! next unless $file eq dirname($last->{file}); return $last->{thesiteurl}; } } if ($CPAN::Config->{randomize_urllist} && rand(1) < $CPAN::Config->{randomize_urllist} ) { $urllist->[int rand scalar @$urllist]; } else { return (); } } #-> sub CPAN::FTP::_get_urllist sub _get_urllist { my($self, $with_defaults) = @_; $with_defaults ||= 0; CPAN->debug("with_defaults[$with_defaults]") if $CPAN::DEBUG; $CPAN::Config->{urllist} ||= []; unless (ref $CPAN::Config->{urllist} eq 'ARRAY') { $CPAN::Frontend->mywarn("Malformed urllist; ignoring. Configuration file corrupt?\n"); $CPAN::Config->{urllist} = []; } my @urllist = grep { defined $_ and length $_ } @{$CPAN::Config->{urllist}}; push @urllist, @CPAN::Defaultsites if $with_defaults; for my $u (@urllist) { CPAN->debug("u[$u]") if $CPAN::DEBUG; if (UNIVERSAL::can($u,"text")) { $u->{TEXT} .= "/" unless substr($u->{TEXT},-1) eq "/"; } else { $u .= "/" unless substr($u,-1) eq "/"; $u = CPAN::URL->new(TEXT => $u, FROM => "USER"); } } \@urllist; } #-> sub CPAN::FTP::ftp_get ; sub ftp_get { my($class,$host,$dir,$file,$target) = @_; $class->debug( qq[Going to fetch file [$file] from dir [$dir] on host [$host] as local [$target]\n] ) if $CPAN::DEBUG; my $ftp = Net::FTP->new($host); unless ($ftp) { $CPAN::Frontend->mywarn(" Could not connect to host '$host' with Net::FTP\n"); return; } return 0 unless defined $ftp; $ftp->debug(1) if $CPAN::DEBUG{'FTP'} & $CPAN::DEBUG; $class->debug(qq[Going to login("anonymous","$Config::Config{cf_email}")]); unless ( $ftp->login("anonymous",$Config::Config{'cf_email'}) ) { my $msg = $ftp->message; $CPAN::Frontend->mywarn(" Couldn't login on $host: $msg\n"); return; } unless ( $ftp->cwd($dir) ) { my $msg = $ftp->message; $CPAN::Frontend->mywarn(" Couldn't cwd $dir: $msg\n"); return; } $ftp->binary; $class->debug(qq[Going to ->get("$file","$target")\n]) if $CPAN::DEBUG; unless ( $ftp->get($file,$target) ) { my $msg = $ftp->message; $CPAN::Frontend->mywarn(" Couldn't fetch $file from $host: $msg\n"); return; } $ftp->quit; # it's ok if this fails return 1; } # If more accuracy is wanted/needed, Chris Leach sent me this patch... # > *** /install/perl/live/lib/CPAN.pm- Wed Sep 24 13:08:48 1997 # > --- /tmp/cp Wed Sep 24 13:26:40 1997 # > *************** # > *** 1562,1567 **** # > --- 1562,1580 ---- # > return 1 if substr($url,0,4) eq "file"; # > return 1 unless $url =~ m|://([^/]+)|; # > my $host = $1; # > + my $proxy = $CPAN::Config->{'http_proxy'} || $ENV{'http_proxy'}; # > + if ($proxy) { # > + $proxy =~ m|://([^/:]+)|; # > + $proxy = $1; # > + my $noproxy = $CPAN::Config->{'no_proxy'} || $ENV{'no_proxy'}; # > + if ($noproxy) { # > + if ($host !~ /$noproxy$/) { # > + $host = $proxy; # > + } # > + } else { # > + $host = $proxy; # > + } # > + } # > require Net::Ping; # > return 1 unless $Net::Ping::VERSION >= 2; # > my $p; #-> sub CPAN::FTP::localize ; sub localize { my($self,$file,$aslocal,$force,$with_defaults) = @_; $force ||= 0; Carp::croak( "Usage: ->localize(cpan_file,as_local_file[,\$force])" ) unless defined $aslocal; if ($CPAN::DEBUG){ require Carp; my $longmess = Carp::longmess(); $self->debug("file[$file] aslocal[$aslocal] force[$force] carplongmess[$longmess]"); } for ($CPAN::Config->{connect_to_internet_ok}) { $connect_to_internet_ok = $_ if not defined $connect_to_internet_ok and defined $_; } my $ph = $CPAN::Config->{pushy_https}; if (!defined $ph || $ph) { return $self->localize_2021($file,$aslocal,$force,$with_defaults); } else { return $self->localize_1995ff($file,$aslocal,$force,$with_defaults); } } sub have_promising_aslocal { my($self, $aslocal, $force) = @_; if (-f $aslocal && -r _ && !($force & 1)) { my $size; if ($size = -s $aslocal) { $self->debug("aslocal[$aslocal]size[$size]") if $CPAN::DEBUG; return 1; } else { # empty file from a previous unsuccessful attempt to download it unlink $aslocal or $CPAN::Frontend->mydie("Found a zero-length '$aslocal' that I ". "could not remove."); } } return; } #-> sub CPAN::FTP::localize ; sub localize_2021 { my($self,$file,$aslocal,$force,$with_defaults) = @_; return $aslocal if $self->have_promising_aslocal($aslocal, $force); my($aslocal_dir) = dirname($aslocal); my $ret; $self->mymkpath($aslocal_dir); my $aslocal_tempfile = $aslocal . ".tmp" . $$; my $base; if ( ($CPAN::META->has_usable('HTTP::Tiny') && $CPAN::META->has_usable('Net::SSLeay') && $CPAN::META->has_usable('IO::Socket::SSL') ) || $CPAN::Config->{curl} || $CPAN::Config->{wget} ) { for my $prx (qw(https_proxy no_proxy)) { $ENV{$prx} = $CPAN::Config->{$prx} if $CPAN::Config->{$prx}; } $base = "https://cpan.org/"; } else { my @missing_modules = grep { ! $CPAN::META->has_usable($_) } qw(HTTP::Tiny Net::SSLeay IO::Socket::SSL); my $miss = join ", ", map { "'$_'" } @missing_modules; my $modules = @missing_modules == 1 ? "module" : "modules"; $CPAN::Frontend->mywarn("Missing or unusable $modules $miss, and found neither curl nor wget installed.\n"); if ($CPAN::META->has_usable('HTTP::Tiny')) { $CPAN::Frontend->mywarn("Need to fall back to http.\n") } for my $prx (qw(http_proxy no_proxy)) { $ENV{$prx} = $CPAN::Config->{$prx} if $CPAN::Config->{$prx}; } $base = "http://www.cpan.org/"; } $ret = $self->hostdl_2021($base,$file,$aslocal_tempfile); if ($ret) { # c&p from below CPAN->debug("ret[$ret]aslocal[$aslocal]") if $CPAN::DEBUG; if ($ret eq $aslocal_tempfile) { # if we got it exactly as we asked for, only then we # want to rename rename $aslocal_tempfile, $aslocal or $CPAN::Frontend->mydie("Error while trying to rename ". "'$ret' to '$aslocal': $!"); $ret = $aslocal; } } else { unlink $aslocal_tempfile; return; } return $ret; } sub hostdl_2021 { my($self, $base, $file, $aslocal) = @_; # the $aslocal is $aslocal_tempfile in the caller (old convention) my $proxy_vars = $self->_proxy_vars($base); my($proto) = $base =~ /^(https?)/; my $url = "$base$file"; # hostdl_2021 may be called with either http or https urls if ( $CPAN::META->has_usable('HTTP::Tiny') && ( $proto eq "http" || ( $CPAN::META->has_usable('Net::SSLeay') && $CPAN::META->has_usable('IO::Socket::SSL') ) ) ){ # mostly c&p from below require CPAN::HTTP::Client; my $chc = CPAN::HTTP::Client->new( proxy => $CPAN::Config->{http_proxy} || $ENV{http_proxy}, no_proxy => $CPAN::Config->{no_proxy} || $ENV{no_proxy}, ); for my $try ( $url, ( $url !~ /\.gz(?!\n)\Z/ ? "$url.gz" : () ) ) { $CPAN::Frontend->myprint("Fetching with HTTP::Tiny:\n$try\n"); my $res = eval { $chc->mirror($try, $aslocal) }; if ( $res && $res->{success} ) { my $now = time; utime $now, $now, $aslocal; # download time is more # important than upload # time return $aslocal; } elsif ( $res && $res->{status} ne '599') { $CPAN::Frontend->myprint(sprintf( "HTTP::Tiny failed with code[%s] message[%s]\n", $res->{status}, $res->{reason}, ) ); } elsif ( $res && $res->{status} eq '599') { $CPAN::Frontend->myprint(sprintf( "HTTP::Tiny failed with an internal error: %s\n", $res->{content}, ) ); } else { my $err = $@ || 'Unknown error'; $CPAN::Frontend->myprint(sprintf( "Error downloading with HTTP::Tiny: %s\n", $err ) ); } } } elsif ($CPAN::Config->{curl} || $CPAN::Config->{wget}){ # c&p from further down my($src_switch, $stdout_redir); my($devnull) = $CPAN::Config->{devnull} || ""; DLPRG: for my $dlprg (qw(curl wget)) { my $dlprg_configured = $CPAN::Config->{$dlprg}; next unless defined $dlprg_configured && length $dlprg_configured; my $funkyftp = CPAN::HandleConfig->safe_quote($dlprg_configured); if ($dlprg eq "wget") { $src_switch = " -O \"$aslocal\""; $stdout_redir = ""; } elsif ($dlprg eq 'curl') { $src_switch = ' -L -f -s -S --netrc-optional'; $stdout_redir = " > \"$aslocal\""; if ($proxy_vars->{http_proxy}) { $src_switch .= qq{ -U "$proxy_vars->{proxy_user}:$proxy_vars->{proxy_pass}" -x "$proxy_vars->{http_proxy}"}; } } $CPAN::Frontend->myprint( qq[ Trying with $funkyftp$src_switch to get $url ]); my($system) = "$funkyftp$src_switch \"$url\" $devnull$stdout_redir"; $self->debug("system[$system]") if $CPAN::DEBUG; my($wstatus) = system($system); if ($wstatus == 0) { return $aslocal; } else { my $estatus = $wstatus >> 8; my $size = -f $aslocal ? ", left\n$aslocal with size ".-s _ : "\nWarning: expected file [$aslocal] doesn't exist"; $CPAN::Frontend->myprint(qq{ Function system("$system") returned status $estatus (wstat $wstatus)$size }); } } # DLPRG } # curl, wget return; } #-> sub CPAN::FTP::localize ; sub localize_1995ff { my($self,$file,$aslocal,$force,$with_defaults) = @_; if ($^O eq 'MacOS') { # Comment by AK on 2000-09-03: Uniq short filenames would be # available in CHECKSUMS file my($name, $path) = File::Basename::fileparse($aslocal, ''); if (length($name) > 31) { $name =~ s/( \.( readme(\.(gz|Z))? | (tar\.)?(gz|Z) | tgz | zip | pm\.(gz|Z) ) )$//x; my $suf = $1; my $size = 31 - length($suf); while (length($name) > $size) { chop $name; } $name .= $suf; $aslocal = File::Spec->catfile($path, $name); } } return $aslocal if $self->have_promising_aslocal($aslocal, $force); my($maybe_restore) = 0; if (-f $aslocal) { rename $aslocal, "$aslocal.bak$$"; $maybe_restore++; } my($aslocal_dir) = dirname($aslocal); # Inheritance is not easier to manage than a few if/else branches if ($CPAN::META->has_usable('LWP::UserAgent')) { unless ($Ua) { CPAN::LWP::UserAgent->config; eval {$Ua = CPAN::LWP::UserAgent->new;}; # Why is has_usable still not fit enough? if ($@) { $CPAN::Frontend->mywarn("CPAN::LWP::UserAgent->new dies with $@\n") if $CPAN::DEBUG; } else { my($var); $Ua->proxy('ftp', $var) if $var = $CPAN::Config->{ftp_proxy} || $ENV{ftp_proxy}; $Ua->proxy('http', $var) if $var = $CPAN::Config->{http_proxy} || $ENV{http_proxy}; $Ua->no_proxy($var) if $var = $CPAN::Config->{no_proxy} || $ENV{no_proxy}; } } } for my $prx (qw(ftp_proxy http_proxy no_proxy)) { $ENV{$prx} = $CPAN::Config->{$prx} if $CPAN::Config->{$prx}; } # Try the list of urls for each single object. We keep a record # where we did get a file from my(@reordered,$last); my $ccurllist = $self->_get_urllist($with_defaults); $last = $#$ccurllist; if ($force & 2) { # local cpans probably out of date, don't reorder @reordered = (0..$last); } else { @reordered = sort { (substr($ccurllist->[$b],0,4) eq "file") <=> (substr($ccurllist->[$a],0,4) eq "file") or defined($ThesiteURL) and ($ccurllist->[$b] eq $ThesiteURL) <=> ($ccurllist->[$a] eq $ThesiteURL) } 0..$last; } my(@levels); $Themethod ||= ""; $self->debug("Themethod[$Themethod]reordered[@reordered]") if $CPAN::DEBUG; my @all_levels = ( ["dleasy", "file"], ["dleasy"], ["dlhard"], ["dlhardest"], ["dleasy", "http","defaultsites"], ["dlhard", "http","defaultsites"], ["dleasy", "ftp", "defaultsites"], ["dlhard", "ftp", "defaultsites"], ["dlhardest","", "defaultsites"], ); if ($Themethod) { @levels = grep {$_->[0] eq $Themethod} @all_levels; push @levels, grep {$_->[0] ne $Themethod} @all_levels; } else { @levels = @all_levels; } @levels = qw/dleasy/ if $^O eq 'MacOS'; my($levelno); local $ENV{FTP_PASSIVE} = exists $CPAN::Config->{ftp_passive} ? $CPAN::Config->{ftp_passive} : 1; my $ret; my $stats = $self->_new_stats($file); LEVEL: for $levelno (0..$#levels) { my $level_tuple = $levels[$levelno]; my($level,$scheme,$sitetag) = @$level_tuple; $self->mymkpath($aslocal_dir) unless $scheme && "file" eq $scheme; my $defaultsites = $sitetag && $sitetag eq "defaultsites" && !@$ccurllist; my @urllist; if ($defaultsites) { unless (defined $connect_to_internet_ok) { $CPAN::Frontend->myprint(sprintf qq{ I would like to connect to one of the following sites to get '%s': %s }, $file, join("",map { " ".$_->text."\n" } @CPAN::Defaultsites), ); my $answer = CPAN::Shell::colorable_makemaker_prompt("Is it OK to try to connect to the Internet?", "yes"); if ($answer =~ /^y/i) { $connect_to_internet_ok = 1; } else { $connect_to_internet_ok = 0; } } if ($connect_to_internet_ok) { @urllist = @CPAN::Defaultsites; } else { my $sleep = 2; # the tricky thing about dying here is that everybody # believes that calls to exists() or all_objects() are # safe. require CPAN::Exception::blocked_urllist; die CPAN::Exception::blocked_urllist->new; } } else { # ! $defaultsites my @host_seq = $level =~ /dleasy/ ? @reordered : 0..$last; # reordered has file and $Thesiteurl first @urllist = map { $ccurllist->[$_] } @host_seq; } $self->debug("synth. urllist[@urllist]") if $CPAN::DEBUG; my $aslocal_tempfile = $aslocal . ".tmp" . $$; if (my $recommend = $self->_recommend_url_for($file,\@urllist)) { @urllist = grep { $_ ne $recommend } @urllist; unshift @urllist, $recommend; } $self->debug("synth. urllist[@urllist]") if $CPAN::DEBUG; $ret = $self->hostdlxxx($level,$scheme,\@urllist,$file,$aslocal_tempfile,$stats); if ($ret) { CPAN->debug("ret[$ret]aslocal[$aslocal]") if $CPAN::DEBUG; if ($ret eq $aslocal_tempfile) { # if we got it exactly as we asked for, only then we # want to rename rename $aslocal_tempfile, $aslocal or $CPAN::Frontend->mydie("Error while trying to rename ". "'$ret' to '$aslocal': $!"); $ret = $aslocal; } elsif (-f $ret && $scheme eq 'file' ) { # it's a local file, so there's nothing left to do, we # let them read from where it is } $Themethod = $level; my $now = time; # utime $now, $now, $aslocal; # too bad, if we do that, we # might alter a local mirror $self->debug("level[$level]") if $CPAN::DEBUG; last LEVEL; } else { unlink $aslocal_tempfile; last if $CPAN::Signal; # need to cleanup } } if ($ret) { $stats->{filesize} = -s $ret; } $self->debug("before _add_to_statistics") if $CPAN::DEBUG; $self->_add_to_statistics($stats); $self->debug("after _add_to_statistics") if $CPAN::DEBUG; if ($ret) { unlink "$aslocal.bak$$"; return $ret; } unless ($CPAN::Signal) { my(@mess); local $" = " "; if (@{$CPAN::Config->{urllist}}) { push @mess, qq{Please check, if the URLs I found in your configuration file \(}. join(", ", @{$CPAN::Config->{urllist}}). qq{\) are valid.}; } else { push @mess, qq{Your urllist is empty!}; } push @mess, qq{The urllist can be edited.}, qq{E.g. with 'o conf urllist push ftp://myurl/'}; $CPAN::Frontend->mywarn(Text::Wrap::wrap("","","@mess"). "\n\n"); $CPAN::Frontend->mydie("Could not fetch $file\n"); } if ($maybe_restore) { rename "$aslocal.bak$$", $aslocal; $CPAN::Frontend->myprint("Trying to get away with old file:\n" . $self->ls($aslocal) . "\n"); return $aslocal; } return; } sub mymkpath { my($self, $aslocal_dir) = @_; mkpath($aslocal_dir); $CPAN::Frontend->mywarn(qq{Warning: You are not allowed to write into }. qq{directory "$aslocal_dir". I\'ll continue, but if you encounter problems, they may be due to insufficient permissions.\n}) unless -w $aslocal_dir; } sub hostdlxxx { my $self = shift; my $level = shift; my $scheme = shift; my $h = shift; $h = [ grep /^\Q$scheme\E:/, @$h ] if $scheme; my $method = "host$level"; $self->$method($h, @_); } sub _set_attempt { my($self,$stats,$method,$url) = @_; push @{$stats->{attempts}}, { method => $method, start => _mytime, url => $url, }; } # package CPAN::FTP; sub hostdleasy { #called from hostdlxxx my($self,$host_seq,$file,$aslocal,$stats) = @_; my($ro_url); HOSTEASY: for $ro_url (@$host_seq) { $self->_set_attempt($stats,"dleasy",$ro_url); my $url = "$ro_url$file"; $self->debug("localizing perlish[$url]") if $CPAN::DEBUG; if ($url =~ /^file:/) { my $l; if ($CPAN::META->has_inst('URI::URL')) { my $u = URI::URL->new($url); $l = $u->file; } else { # works only on Unix, is poorly constructed, but # hopefully better than nothing. # RFC 1738 says fileurl BNF is # fileurl = "file://" [ host | "localhost" ] "/" fpath # Thanks to "Mark D. Baushke" for # the code ($l = $url) =~ s|^file://[^/]*/|/|; # discard the host part $l =~ s|^file:||; # assume they # meant # file://localhost $l =~ s|^/||s if ! -f $l && $l =~ m|^/\w:|; # e.g. /P: } $self->debug("local file[$l]") if $CPAN::DEBUG; if ( -f $l && -r _) { $ThesiteURL = $ro_url; return $l; } # If request is for a compressed file and we can find the # uncompressed file also, return the path of the uncompressed file # otherwise, decompress it and return the resulting path if ($l =~ /(.+)\.gz$/) { my $ungz = $1; if ( -f $ungz && -r _) { $ThesiteURL = $ro_url; return $ungz; } elsif (-f $l && -r _) { eval { CPAN::Tarzip->new($l)->gunzip($aslocal) }; if ( -f $aslocal && -s _) { $ThesiteURL = $ro_url; return $aslocal; } elsif (! -s $aslocal) { unlink $aslocal; } elsif (-f $l) { $CPAN::Frontend->mywarn("Error decompressing '$l': $@\n") if $@; return; } } } # Otherwise, return the local file path if it exists elsif ( -f $l && -r _) { $ThesiteURL = $ro_url; return $l; } # If we can't find it, but there is a compressed version # of it, then decompress it elsif (-f "$l.gz") { $self->debug("found compressed $l.gz") if $CPAN::DEBUG; eval { CPAN::Tarzip->new("$l.gz")->gunzip($aslocal) }; if ( -f $aslocal) { $ThesiteURL = $ro_url; return $aslocal; } else { $CPAN::Frontend->mywarn("Error decompressing '$l': $@\n") if $@; return; } } $CPAN::Frontend->mywarn("Could not find '$l'\n"); } $self->debug("it was not a file URL") if $CPAN::DEBUG; if ($CPAN::META->has_usable('LWP')) { $CPAN::Frontend->myprint("Fetching with LWP:\n$url\n"); unless ($Ua) { CPAN::LWP::UserAgent->config; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mywarn("CPAN::LWP::UserAgent->new dies with $@\n"); } } my $res = $Ua->mirror($url, $aslocal); if ($res->is_success) { $ThesiteURL = $ro_url; my $now = time; utime $now, $now, $aslocal; # download time is more # important than upload # time return $aslocal; } elsif ($url !~ /\.gz(?!\n)\Z/) { my $gzurl = "$url.gz"; $CPAN::Frontend->myprint("Fetching with LWP:\n$gzurl\n"); $res = $Ua->mirror($gzurl, "$aslocal.gz"); if ($res->is_success) { if (eval {CPAN::Tarzip->new("$aslocal.gz")->gunzip($aslocal)}) { $ThesiteURL = $ro_url; return $aslocal; } } } else { $CPAN::Frontend->myprint(sprintf( "LWP failed with code[%s] message[%s]\n", $res->code, $res->message, )); # Alan Burlison informed me that in firewall environments # Net::FTP can still succeed where LWP fails. So we do not # skip Net::FTP anymore when LWP is available. } } elsif ($url =~ /^http:/i && $CPAN::META->has_usable('HTTP::Tiny')) { require CPAN::HTTP::Client; my $chc = CPAN::HTTP::Client->new( proxy => $CPAN::Config->{http_proxy} || $ENV{http_proxy}, no_proxy => $CPAN::Config->{no_proxy} || $ENV{no_proxy}, ); for my $try ( $url, ( $url !~ /\.gz(?!\n)\Z/ ? "$url.gz" : () ) ) { $CPAN::Frontend->myprint("Fetching with HTTP::Tiny:\n$try\n"); my $res = eval { $chc->mirror($try, $aslocal) }; if ( $res && $res->{success} ) { $ThesiteURL = $ro_url; my $now = time; utime $now, $now, $aslocal; # download time is more # important than upload # time return $aslocal; } elsif ( $res && $res->{status} ne '599') { $CPAN::Frontend->myprint(sprintf( "HTTP::Tiny failed with code[%s] message[%s]\n", $res->{status}, $res->{reason}, ) ); } elsif ( $res && $res->{status} eq '599') { $CPAN::Frontend->myprint(sprintf( "HTTP::Tiny failed with an internal error: %s\n", $res->{content}, ) ); } else { my $err = $@ || 'Unknown error'; $CPAN::Frontend->myprint(sprintf( "Error downloading with HTTP::Tiny: %s\n", $err ) ); } } } return if $CPAN::Signal; if ($url =~ m|^ftp://(.*?)/(.*)/(.*)|) { # that's the nice and easy way thanks to Graham $self->debug("recognized ftp") if $CPAN::DEBUG; my($host,$dir,$getfile) = ($1,$2,$3); if ($CPAN::META->has_usable('Net::FTP')) { $dir =~ s|/+|/|g; $CPAN::Frontend->myprint("Fetching with Net::FTP:\n$url\n"); $self->debug("getfile[$getfile]dir[$dir]host[$host]" . "aslocal[$aslocal]") if $CPAN::DEBUG; if (CPAN::FTP->ftp_get($host,$dir,$getfile,$aslocal)) { $ThesiteURL = $ro_url; return $aslocal; } if ($aslocal !~ /\.gz(?!\n)\Z/) { my $gz = "$aslocal.gz"; $CPAN::Frontend->myprint("Fetching with Net::FTP\n$url.gz\n"); if (CPAN::FTP->ftp_get($host, $dir, "$getfile.gz", $gz) && eval{CPAN::Tarzip->new($gz)->gunzip($aslocal)} ) { $ThesiteURL = $ro_url; return $aslocal; } } # next HOSTEASY; } else { CPAN->debug("Net::FTP does not count as usable atm") if $CPAN::DEBUG; } } if ( UNIVERSAL::can($ro_url,"text") and $ro_url->{FROM} eq "USER" ) { ##address #17973: default URLs should not try to override ##user-defined URLs just because LWP is not available my $ret = $self->hostdlhard([$ro_url],$file,$aslocal,$stats); return $ret if $ret; } return if $CPAN::Signal; } } # package CPAN::FTP; sub hostdlhard { my($self,$host_seq,$file,$aslocal,$stats) = @_; # Came back if Net::FTP couldn't establish connection (or # failed otherwise) Maybe they are behind a firewall, but they # gave us a socksified (or other) ftp program... my($ro_url); my($devnull) = $CPAN::Config->{devnull} || ""; # < /dev/null "; my($aslocal_dir) = dirname($aslocal); mkpath($aslocal_dir); my $some_dl_success = 0; my $any_attempt = 0; HOSTHARD: for $ro_url (@$host_seq) { $self->_set_attempt($stats,"dlhard",$ro_url); my $url = "$ro_url$file"; my($proto,$host,$dir,$getfile); # Courtesy Mark Conty mark_conty@cargill.com change from # if ($url =~ m|^ftp://(.*?)/(.*)/(.*)|) { # to if ($url =~ m|^([^:]+)://(.*?)/(.*)/(.*)|) { # proto not yet used ($proto,$host,$dir,$getfile) = ($1,$2,$3,$4); } else { next HOSTHARD; # who said, we could ftp anything except ftp? } next HOSTHARD if $proto eq "file"; # file URLs would have had # success above. Likely a bogus URL # making at least one attempt against a host $any_attempt++; $self->debug("localizing funkyftpwise[$url]") if $CPAN::DEBUG; # Try the most capable first and leave ncftp* for last as it only # does FTP. my $proxy_vars = $self->_proxy_vars($ro_url); DLPRG: for my $f (qw(curl wget lynx ncftpget ncftp)) { my $funkyftp = CPAN::HandleConfig->safe_quote($CPAN::Config->{$f}); next DLPRG unless defined $funkyftp; next DLPRG if $funkyftp =~ /^\s*$/; my($src_switch) = ""; my($chdir) = ""; my($stdout_redir) = " > \"$aslocal\""; if ($f eq "lynx") { $src_switch = " -source"; } elsif ($f eq "ncftp") { next DLPRG unless $url =~ m{\Aftp://}; $src_switch = " -c"; } elsif ($f eq "wget") { $src_switch = " -O \"$aslocal\""; $stdout_redir = ""; } elsif ($f eq 'curl') { $src_switch = ' -L -f -s -S --netrc-optional'; if ($proxy_vars->{http_proxy}) { $src_switch .= qq{ -U "$proxy_vars->{proxy_user}:$proxy_vars->{proxy_pass}" -x "$proxy_vars->{http_proxy}"}; } } elsif ($f eq "ncftpget") { next DLPRG unless $url =~ m{\Aftp://}; $chdir = "cd $aslocal_dir && "; $stdout_redir = ""; } $CPAN::Frontend->myprint( qq[ Trying with $funkyftp$src_switch to get $url ]); my($system) = "$chdir$funkyftp$src_switch \"$url\" $devnull$stdout_redir"; $self->debug("system[$system]") if $CPAN::DEBUG; my($wstatus) = system($system); if ($f eq "lynx") { # lynx returns 0 when it fails somewhere if (-s $aslocal) { my $content = do { local *FH; open FH, $aslocal or die; local $/; }; if ($content =~ /^<.*([45]|Error [45])/si) { $CPAN::Frontend->mywarn(qq{ No success, the file that lynx has downloaded looks like an error message: $content }); $CPAN::Frontend->mysleep(1); next DLPRG; } $some_dl_success++; } else { $CPAN::Frontend->myprint(qq{ No success, the file that lynx has downloaded is an empty file. }); next DLPRG; } } if ($wstatus == 0) { if (-s $aslocal) { # Looks good $some_dl_success++; } $ThesiteURL = $ro_url; return $aslocal; } else { my $estatus = $wstatus >> 8; my $size = -f $aslocal ? ", left\n$aslocal with size ".-s _ : "\nWarning: expected file [$aslocal] doesn't exist"; $CPAN::Frontend->myprint(qq{ Function system("$system") returned status $estatus (wstat $wstatus)$size }); } return if $CPAN::Signal; } # download/transfer programs (DLPRG) } # host return unless $any_attempt; if ($some_dl_success) { $CPAN::Frontend->mywarn("Warning: doesn't seem we had substantial success downloading '$aslocal'. Don't know how to proceed.\n"); } else { $CPAN::Frontend->mywarn("Warning: no success downloading '$aslocal'. Giving up on it.\n"); } return; } #-> CPAN::FTP::_proxy_vars sub _proxy_vars { my($self,$url) = @_; my $ret = +{}; my $http_proxy = $CPAN::Config->{'http_proxy'} || $ENV{'http_proxy'}; if ($http_proxy) { my($host) = $url =~ m|://([^/:]+)|; my $want_proxy = 1; my $noproxy = $CPAN::Config->{'no_proxy'} || $ENV{'no_proxy'} || ""; my @noproxy = split /\s*,\s*/, $noproxy; if ($host) { DOMAIN: for my $domain (@noproxy) { if ($host =~ /\Q$domain\E$/) { # cf. LWP::UserAgent $want_proxy = 0; last DOMAIN; } } } else { $CPAN::Frontend->mywarn(" Could not determine host from http_proxy '$http_proxy'\n"); } if ($want_proxy) { my($user, $pass) = CPAN::HTTP::Credentials->get_proxy_credentials(); $ret = { proxy_user => $user, proxy_pass => $pass, http_proxy => $http_proxy }; } } return $ret; } # package CPAN::FTP; sub hostdlhardest { my($self,$host_seq,$file,$aslocal,$stats) = @_; return unless @$host_seq; my($ro_url); my($aslocal_dir) = dirname($aslocal); mkpath($aslocal_dir); my $ftpbin = $CPAN::Config->{ftp}; unless ($ftpbin && length $ftpbin && MM->maybe_command($ftpbin)) { $CPAN::Frontend->myprint("No external ftp command available\n\n"); return; } $CPAN::Frontend->mywarn(qq{ As a last resort we now switch to the external ftp command '$ftpbin' to get '$aslocal'. Doing so often leads to problems that are hard to diagnose. If you're the victim of such problems, please consider unsetting the ftp config variable with o conf ftp "" o conf commit }); $CPAN::Frontend->mysleep(2); HOSTHARDEST: for $ro_url (@$host_seq) { $self->_set_attempt($stats,"dlhardest",$ro_url); my $url = "$ro_url$file"; $self->debug("localizing ftpwise[$url]") if $CPAN::DEBUG; unless ($url =~ m|^ftp://(.*?)/(.*)/(.*)|) { next; } my($host,$dir,$getfile) = ($1,$2,$3); my $timestamp = 0; my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime, $ctime,$blksize,$blocks) = stat($aslocal); $timestamp = $mtime ||= 0; my($netrc) = CPAN::FTP::netrc->new; my($netrcfile) = $netrc->netrc; my($verbose) = $CPAN::DEBUG{'FTP'} & $CPAN::DEBUG ? " -v" : ""; my $targetfile = File::Basename::basename($aslocal); my(@dialog); push( @dialog, "lcd $aslocal_dir", "cd /", map("cd $_", split /\//, $dir), # RFC 1738 "bin", "passive", "get $getfile $targetfile", "quit" ); if (! $netrcfile) { CPAN->debug("No ~/.netrc file found") if $CPAN::DEBUG; } elsif ($netrc->hasdefault || $netrc->contains($host)) { CPAN->debug(sprintf("hasdef[%d]cont($host)[%d]", $netrc->hasdefault, $netrc->contains($host))) if $CPAN::DEBUG; if ($netrc->protected) { my $dialog = join "", map { " $_\n" } @dialog; my $netrc_explain; if ($netrc->contains($host)) { $netrc_explain = "Relying that your .netrc entry for '$host' ". "manages the login"; } else { $netrc_explain = "Relying that your default .netrc entry ". "manages the login"; } $CPAN::Frontend->myprint(qq{ Trying with external ftp to get '$url' $netrc_explain Sending the dialog $dialog } ); $self->talk_ftp("$ftpbin$verbose $host", @dialog); ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($aslocal); $mtime ||= 0; if ($mtime > $timestamp) { $CPAN::Frontend->myprint("GOT $aslocal\n"); $ThesiteURL = $ro_url; return $aslocal; } else { $CPAN::Frontend->myprint("Hmm... Still failed!\n"); } return if $CPAN::Signal; } else { $CPAN::Frontend->mywarn(qq{Your $netrcfile is not }. qq{correctly protected.\n}); } } else { $CPAN::Frontend->mywarn("Your ~/.netrc neither contains $host nor does it have a default entry\n"); } # OK, they don't have a valid ~/.netrc. Use 'ftp -n' # then and login manually to host, using e-mail as # password. $CPAN::Frontend->myprint(qq{Issuing "$ftpbin$verbose -n"\n}); unshift( @dialog, "open $host", "user anonymous $Config::Config{'cf_email'}" ); my $dialog = join "", map { " $_\n" } @dialog; $CPAN::Frontend->myprint(qq{ Trying with external ftp to get $url Sending the dialog $dialog } ); $self->talk_ftp("$ftpbin$verbose -n", @dialog); ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($aslocal); $mtime ||= 0; if ($mtime > $timestamp) { $CPAN::Frontend->myprint("GOT $aslocal\n"); $ThesiteURL = $ro_url; return $aslocal; } else { $CPAN::Frontend->myprint("Bad luck... Still failed!\n"); } return if $CPAN::Signal; $CPAN::Frontend->mywarn("Can't access URL $url.\n\n"); $CPAN::Frontend->mysleep(2); } # host } # package CPAN::FTP; sub talk_ftp { my($self,$command,@dialog) = @_; my $fh = FileHandle->new; $fh->open("|$command") or die "Couldn't open ftp: $!"; foreach (@dialog) { $fh->print("$_\n") } $fh->close; # Wait for process to complete my $wstatus = $?; my $estatus = $wstatus >> 8; $CPAN::Frontend->myprint(qq{ Subprocess "|$command" returned status $estatus (wstat $wstatus) }) if $wstatus; } # find2perl needs modularization, too, all the following is stolen # from there # CPAN::FTP::ls sub ls { my($self,$name) = @_; my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$sizemm, $atime,$mtime,$ctime,$blksize,$blocks) = lstat($name); my($perms,%user,%group); my $pname = $name; if ($blocks) { $blocks = int(($blocks + 1) / 2); } else { $blocks = int(($sizemm + 1023) / 1024); } if (-f _) { $perms = '-'; } elsif (-d _) { $perms = 'd'; } elsif (-c _) { $perms = 'c'; $sizemm = &sizemm; } elsif (-b _) { $perms = 'b'; $sizemm = &sizemm; } elsif (-p _) { $perms = 'p'; } elsif (-S _) { $perms = 's'; } else { $perms = 'l'; $pname .= ' -> ' . readlink($_); } my(@rwx) = ('---','--x','-w-','-wx','r--','r-x','rw-','rwx'); my(@moname) = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my $tmpmode = $mode; my $tmp = $rwx[$tmpmode & 7]; $tmpmode >>= 3; $tmp = $rwx[$tmpmode & 7] . $tmp; $tmpmode >>= 3; $tmp = $rwx[$tmpmode & 7] . $tmp; substr($tmp,2,1) =~ tr/-x/Ss/ if -u _; substr($tmp,5,1) =~ tr/-x/Ss/ if -g _; substr($tmp,8,1) =~ tr/-x/Tt/ if -k _; $perms .= $tmp; my $user = $user{$uid} || $uid; # too lazy to implement lookup my $group = $group{$gid} || $gid; my($sec,$min,$hour,$mday,$mon,$year) = localtime($mtime); my($timeyear); my($moname) = $moname[$mon]; if (-M _ > 365.25 / 2) { $timeyear = $year + 1900; } else { $timeyear = sprintf("%02d:%02d", $hour, $min); } sprintf "%5lu %4ld %-10s %2d %-8s %-8s %8s %s %2d %5s %s\n", $ino, $blocks, $perms, $nlink, $user, $group, $sizemm, $moname, $mday, $timeyear, $pname; } 1; PK�������!�7=$�$���perl5/CPAN/FirstTime.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::FirstTime; use strict; use ExtUtils::MakeMaker (); use FileHandle (); use File::Basename (); use File::Path (); use File::Spec (); use CPAN::Mirrors (); use CPAN::Version (); use vars qw($VERSION $auto_config); $VERSION = "5.5317"; =head1 NAME CPAN::FirstTime - Utility for CPAN::Config file Initialization =head1 SYNOPSIS CPAN::FirstTime::init() =head1 DESCRIPTION The init routine asks a few questions and writes a CPAN/Config.pm or CPAN/MyConfig.pm file (depending on what it is currently using). In the following all questions and explanations regarding config variables are collected. =cut # down until the next =back the manpage must be parsed by the program # because the text is used in the init dialogues. my @podpara = split /\n\n/, <<'=back'; =over 2 =item allow_installing_module_downgrades The CPAN shell can watch the C<blib/> directories that are built up before running C<make test> to determine whether the current distribution will end up with modules being overwritten with decreasing module version numbers. It can then let the build of this distro fail when it discovers a downgrade. Do you want to allow installing distros with decreasing module versions compared to what you have installed (yes, no, ask/yes, ask/no)? =item allow_installing_outdated_dists The CPAN shell can watch the C<blib/> directories that are built up before running C<make test> to determine whether the current distribution contains modules that are indexed with a distro with a higher distro-version number than the current one. It can then let the build of this distro fail when it would not represent the most up-to-date version of the distro. Note: choosing anything but 'yes' for this option will need CPAN::DistnameInfo being installed for taking effect. Do you want to allow installing distros that are not indexed as the highest distro-version for all contained modules (yes, no, ask/yes, ask/no)? =item auto_commit Normally CPAN.pm keeps config variables in memory and changes need to be saved in a separate 'o conf commit' command to make them permanent between sessions. If you set the 'auto_commit' option to true, changes to a config variable are always automatically committed to disk. Always commit changes to config variables to disk? =item build_cache CPAN.pm can limit the size of the disk area for keeping the build directories with all the intermediate files. Cache size for build directory (in MB)? =item build_dir Directory where the build process takes place? =item build_dir_reuse Until version 1.88 CPAN.pm never trusted the contents of the build_dir directory between sessions. Since 1.88_58 CPAN.pm has a YAML-based mechanism that makes it possible to share the contents of the build_dir/ directory between different sessions with the same version of perl. People who prefer to test things several days before installing will like this feature because it saves a lot of time. If you say yes to the following question, CPAN will try to store enough information about the build process so that it can pick up in future sessions at the same state of affairs as it left a previous session. Store and re-use state information about distributions between CPAN.pm sessions? =item build_requires_install_policy When a module declares another one as a 'build_requires' prerequisite this means that the other module is only needed for building or testing the module but need not be installed permanently. In this case you may wish to install that other module nonetheless or just keep it in the 'build_dir' directory to have it available only temporarily. Installing saves time on future installations but makes the perl installation bigger. You can choose if you want to always install (yes), never install (no) or be always asked. In the latter case you can set the default answer for the question to yes (ask/yes) or no (ask/no). Policy on installing 'build_requires' modules (yes, no, ask/yes, ask/no)? =item cache_metadata To considerably speed up the initial CPAN shell startup, it is possible to use Storable to create a cache of metadata. If Storable is not available, the normal index mechanism will be used. Note: this mechanism is not used when use_sqlite is on and SQLite is running. Cache metadata (yes/no)? =item check_sigs CPAN packages can be digitally signed by authors and thus verified with the security provided by strong cryptography. The exact mechanism is defined in the Module::Signature module. While this is generally considered a good thing, it is not always convenient to the end user to install modules that are signed incorrectly or where the key of the author is not available or where some prerequisite for Module::Signature has a bug and so on. With the check_sigs parameter you can turn signature checking on and off. The default is off for now because the whole tool chain for the functionality is not yet considered mature by some. The author of CPAN.pm would recommend setting it to true most of the time and turning it off only if it turns out to be annoying. Note that if you do not have Module::Signature installed, no signature checks will be performed at all. Always try to check and verify signatures if a SIGNATURE file is in the package and Module::Signature is installed (yes/no)? =item cleanup_after_install Users who install modules and do not intend to look back, can free occupied disk space quickly by letting CPAN.pm cleanup each build directory immediately after a successful install. Remove build directory after a successful install? (yes/no)? =item colorize_output When you have Term::ANSIColor installed, you can turn on colorized output to have some visual differences between normal CPAN.pm output, warnings, debugging output, and the output of the modules being installed. Set your favorite colors after some experimenting with the Term::ANSIColor module. Please note that on Windows platforms colorized output also requires the Win32::Console::ANSI module. Do you want to turn on colored output? =item colorize_print Color for normal output? =item colorize_warn Color for warnings? =item colorize_debug Color for debugging messages? =item commandnumber_in_prompt The prompt of the cpan shell can contain the current command number for easier tracking of the session or be a plain string. Do you want the command number in the prompt (yes/no)? =item connect_to_internet_ok If you have never defined your own C<urllist> in your configuration then C<CPAN.pm> will be hesitant to use the built in default sites for downloading. It will ask you once per session if a connection to the internet is OK and only if you say yes, it will try to connect. But to avoid this question, you can choose your favorite download sites once and get away with it. Or, if you have no favorite download sites answer yes to the following question. If no urllist has been chosen yet, would you prefer CPAN.pm to connect to the built-in default sites without asking? (yes/no)? =item ftp_passive Shall we always set the FTP_PASSIVE environment variable when dealing with ftp download (yes/no)? =item ftpstats_period Statistics about downloads are truncated by size and period simultaneously. How many days shall we keep statistics about downloads? =item ftpstats_size Statistics about downloads are truncated by size and period simultaneously. Setting this to zero or negative disables download statistics. How many items shall we keep in the statistics about downloads? =item getcwd CPAN.pm changes the current working directory often and needs to determine its own current working directory. Per default it uses Cwd::cwd but if this doesn't work on your system for some reason, alternatives can be configured according to the following table: cwd Cwd::cwd getcwd Cwd::getcwd fastcwd Cwd::fastcwd getdcwd Cwd::getdcwd backtickcwd external command cwd Preferred method for determining the current working directory? =item halt_on_failure Normally, CPAN.pm continues processing the full list of targets and dependencies, even if one of them fails. However, you can specify that CPAN should halt after the first failure. (Note that optional recommended or suggested modules that fail will not cause a halt.) Do you want to halt on failure (yes/no)? =item histfile If you have one of the readline packages (Term::ReadLine::Perl, Term::ReadLine::Gnu, possibly others) installed, the interactive CPAN shell will have history support. The next two questions deal with the filename of the history file and with its size. If you do not want to set this variable, please hit SPACE ENTER to the following question. File to save your history? =item histsize Number of lines to save? =item inactivity_timeout Sometimes you may wish to leave the processes run by CPAN alone without caring about them. Because the Makefile.PL or the Build.PL sometimes contains question you're expected to answer, you can set a timer that will kill a 'perl Makefile.PL' process after the specified time in seconds. If you set this value to 0, these processes will wait forever. This is the default and recommended setting. Timeout for inactivity during {Makefile,Build}.PL? =item index_expire The CPAN indexes are usually rebuilt once or twice per hour, but the typical CPAN mirror mirrors only once or twice per day. Depending on the quality of your mirror and your desire to be on the bleeding edge, you may want to set the following value to more or less than one day (which is the default). It determines after how many days CPAN.pm downloads new indexes. Let the index expire after how many days? =item inhibit_startup_message When the CPAN shell is started it normally displays a greeting message that contains the running version and the status of readline support. Do you want to turn this message off? =item keep_source_where Unless you are accessing the CPAN on your filesystem via a file: URL, CPAN.pm needs to keep the source files it downloads somewhere. Please supply a directory where the downloaded files are to be kept. Download target directory? =item load_module_verbosity When CPAN.pm loads a module it needs for some optional feature, it usually reports about module name and version. Choose 'v' to get this message, 'none' to suppress it. Verbosity level for loading modules (none or v)? =item makepl_arg Every Makefile.PL is run by perl in a separate process. Likewise we run 'make' and 'make install' in separate processes. If you have any parameters (e.g. PREFIX, UNINST or the like) you want to pass to the calls, please specify them here. If you don't understand this question, just press ENTER. Typical frequently used settings: PREFIX=~/perl # non-root users (please see manual for more hints) Parameters for the 'perl Makefile.PL' command? =item make_arg Parameters for the 'make' command? Typical frequently used setting: -j3 # dual processor system (on GNU make) Your choice: =item make_install_arg Parameters for the 'make install' command? Typical frequently used setting: UNINST=1 # to always uninstall potentially conflicting files # (but do NOT use with local::lib or INSTALL_BASE) Your choice: =item make_install_make_command Do you want to use a different make command for 'make install'? Cautious people will probably prefer: su root -c make or sudo make or /path1/to/sudo -u admin_account /path2/to/make or some such. Your choice: =item mbuildpl_arg A Build.PL is run by perl in a separate process. Likewise we run './Build' and './Build install' in separate processes. If you have any parameters you want to pass to the calls, please specify them here. Typical frequently used settings: --install_base /home/xxx # different installation directory Parameters for the 'perl Build.PL' command? =item mbuild_arg Parameters for the './Build' command? Setting might be: --extra_linker_flags -L/usr/foo/lib # non-standard library location Your choice: =item mbuild_install_arg Parameters for the './Build install' command? Typical frequently used setting: --uninst 1 # uninstall conflicting files # (but do NOT use with local::lib or INSTALL_BASE) Your choice: =item mbuild_install_build_command Do you want to use a different command for './Build install'? Sudo users will probably prefer: su root -c ./Build or sudo ./Build or /path1/to/sudo -u admin_account ./Build or some such. Your choice: =item pager What is your favorite pager program? =item prefer_installer When you have Module::Build installed and a module comes with both a Makefile.PL and a Build.PL, which shall have precedence? The main two standard installer modules are the old and well established ExtUtils::MakeMaker (for short: EUMM) which uses the Makefile.PL. And the next generation installer Module::Build (MB) which works with the Build.PL (and often comes with a Makefile.PL too). If a module comes only with one of the two we will use that one but if both are supplied then a decision must be made between EUMM and MB. See also http://rt.cpan.org/Ticket/Display.html?id=29235 for a discussion about the right default. Or, as a third option you can choose RAND which will make a random decision (something regular CPAN testers will enjoy). In case you can choose between running a Makefile.PL or a Build.PL, which installer would you prefer (EUMM or MB or RAND)? =item prefs_dir CPAN.pm can store customized build environments based on regular expressions for distribution names. These are YAML files where the default options for CPAN.pm and the environment can be overridden and dialog sequences can be stored that can later be executed by an Expect.pm object. The CPAN.pm distribution comes with some prefab YAML files that cover sample distributions that can be used as blueprints to store your own prefs. Please check out the distroprefs/ directory of the CPAN.pm distribution to get a quick start into the prefs system. Directory where to store default options/environment/dialogs for building modules that need some customization? =item prerequisites_policy The CPAN module can detect when a module which you are trying to build depends on prerequisites. If this happens, it can build the prerequisites for you automatically ('follow'), ask you for confirmation ('ask'), or just ignore them ('ignore'). Choosing 'follow' also sets PERL_AUTOINSTALL and PERL_EXTUTILS_AUTOINSTALL for "--defaultdeps" if not already set. Please set your policy to one of the three values. Policy on building prerequisites (follow, ask or ignore)? =item pushy_https Boolean. Defaults to true. If this option is true, the cpan shell will use https://cpan.org/ to download stuff from the CPAN. It will fall back to http://cpan.org/ if it can't handle https for some reason (missing modules, missing programs). Whenever it falls back to the http protocol, it will issue a warning. If this option is true, the option C<urllist> will be ignored. Consequently, if you want to work with local mirrors via your own configured list of URLs, you will have to choose no below. Do you want to turn the pushy_https behaviour on? =item randomize_urllist CPAN.pm can introduce some randomness when using hosts for download that are configured in the urllist parameter. Enter a numeric value between 0 and 1 to indicate how often you want to let CPAN.pm try a random host from the urllist. A value of one specifies to always use a random host as the first try. A value of zero means no randomness at all. Anything in between specifies how often, on average, a random host should be tried first. Randomize parameter =item recommends_policy (Experimental feature!) Some CPAN modules recommend additional, optional dependencies. These should generally be installed except in resource constrained environments. When this policy is true, recommended modules will be included with required modules. Include recommended modules? =item scan_cache By default, each time the CPAN module is started, cache scanning is performed to keep the cache size in sync ('atstart'). Alternatively, scanning and cleanup can happen when CPAN exits ('atexit'). To prevent any cache cleanup, answer 'never'. Perform cache scanning ('atstart', 'atexit' or 'never')? =item shell What is your favorite shell? =item show_unparsable_versions During the 'r' command CPAN.pm finds modules without version number. When the command finishes, it prints a report about this. If you want this report to be very verbose, say yes to the following variable. Show all individual modules that have no $VERSION? =item show_upload_date The 'd' and the 'm' command normally only show you information they have in their in-memory database and thus will never connect to the internet. If you set the 'show_upload_date' variable to true, 'm' and 'd' will additionally show you the upload date of the module or distribution. Per default this feature is off because it may require a net connection to get at the upload date. Always try to show upload date with 'd' and 'm' command (yes/no)? =item show_zero_versions During the 'r' command CPAN.pm finds modules with a version number of zero. When the command finishes, it prints a report about this. If you want this report to be very verbose, say yes to the following variable. Show all individual modules that have a $VERSION of zero? =item suggests_policy (Experimental feature!) Some CPAN modules suggest additional, optional dependencies. These 'suggest' dependencies provide enhanced operation. When this policy is true, suggested modules will be included with required modules. Include suggested modules? =item tar_verbosity When CPAN.pm uses the tar command, which switch for the verbosity shall be used? Choose 'none' for quiet operation, 'v' for file name listing, 'vv' for full listing. Tar command verbosity level (none or v or vv)? =item term_is_latin The next option deals with the charset (a.k.a. character set) your terminal supports. In general, CPAN is English speaking territory, so the charset does not matter much but some CPAN have names that are outside the ASCII range. If your terminal supports UTF-8, you should say no to the next question. If it expects ISO-8859-1 (also known as LATIN1) then you should say yes. If it supports neither, your answer does not matter because you will not be able to read the names of some authors anyway. If you answer no, names will be output in UTF-8. Your terminal expects ISO-8859-1 (yes/no)? =item term_ornaments When using Term::ReadLine, you can turn ornaments on so that your input stands out against the output from CPAN.pm. Do you want to turn ornaments on? =item test_report The goal of the CPAN Testers project (http://testers.cpan.org/) is to test as many CPAN packages as possible on as many platforms as possible. This provides valuable feedback to module authors and potential users to identify bugs or platform compatibility issues and improves the overall quality and value of CPAN. One way you can contribute is to send test results for each module that you install. If you install the CPAN::Reporter module, you have the option to automatically generate and deliver test reports to CPAN Testers whenever you run tests on a CPAN package. See the CPAN::Reporter documentation for additional details and configuration settings. If your firewall blocks outgoing traffic, you may need to configure CPAN::Reporter before sending reports. Generate test reports if CPAN::Reporter is installed (yes/no)? =item perl5lib_verbosity When CPAN.pm extends @INC via PERL5LIB, it prints a list of directories added (or a summary of how many directories are added). Choose 'v' to get this message, 'none' to suppress it. Verbosity level for PERL5LIB changes (none or v)? =item prefer_external_tar Per default all untar operations are done with the perl module Archive::Tar; by setting this variable to true the external tar command is used if available; on Unix this is usually preferred because they have a reliable and fast gnutar implementation. Use the external tar program instead of Archive::Tar? =item trust_test_report_history When a distribution has already been tested by CPAN::Reporter on this machine, CPAN can skip the test phase and just rely on the test report history instead. Note that this will not apply to distributions that failed tests because of missing dependencies. Also, tests can be run regardless of the history using "force". Do you want to rely on the test report history (yes/no)? =item urllist_ping_external When automatic selection of the nearest cpan mirrors is performed, turn on the use of the external ping via Net::Ping::External. This is recommended in the case the local network has a transparent proxy. Do you want to use the external ping command when autoselecting mirrors? =item urllist_ping_verbose When automatic selection of the nearest cpan mirrors is performed, this option can be used to turn on verbosity during the selection process. Do you want to see verbosity turned on when autoselecting mirrors? =item use_prompt_default When this is true, CPAN will set PERL_MM_USE_DEFAULT to a true value. This causes ExtUtils::MakeMaker (and compatible) prompts to use default values instead of stopping to prompt you to answer questions. It also sets NONINTERACTIVE_TESTING to a true value to signal more generally that distributions should not try to interact with you. Do you want to use prompt defaults (yes/no)? =item use_sqlite CPAN::SQLite is a layer between the index files that are downloaded from the CPAN and CPAN.pm that speeds up metadata queries and reduces memory consumption of CPAN.pm considerably. Use CPAN::SQLite if available? (yes/no)? =item version_timeout This timeout prevents CPAN from hanging when trying to parse a pathologically coded $VERSION from a module. The default is 15 seconds. If you set this value to 0, no timeout will occur, but this is not recommended. Timeout for parsing module versions? =item yaml_load_code Both YAML.pm and YAML::Syck are capable of deserialising code. As this requires a string eval, which might be a security risk, you can use this option to enable or disable the deserialisation of code via CPAN::DeferredCode. (Note: This does not work under perl 5.6) Do you want to enable code deserialisation (yes/no)? =item yaml_module At the time of this writing (2009-03) there are three YAML implementations working: YAML, YAML::Syck, and YAML::XS. The latter two are faster but need a C compiler installed on your system. There may be more alternative YAML conforming modules. When I tried two other players, YAML::Tiny and YAML::Perl, they seemed not powerful enough to work with CPAN.pm. This may have changed in the meantime. Which YAML implementation would you prefer? =back =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut use vars qw( %prompts ); { my @prompts = ( auto_config => qq{ CPAN.pm requires configuration, but most of it can be done automatically. If you answer 'no' below, you will enter an interactive dialog for each configuration option instead. Would you like to configure as much as possible automatically?}, auto_pick => qq{ Would you like me to automatically choose some CPAN mirror sites for you? (This means connecting to the Internet)}, config_intro => qq{ The following questions are intended to help you with the configuration. The CPAN module needs a directory of its own to cache important index files and maybe keep a temporary mirror of CPAN files. This may be a site-wide or a personal directory. }, # cpan_home => qq{ }, cpan_home_where => qq{ First of all, I'd like to create this directory. Where? }, external_progs => qq{ The CPAN module will need a few external programs to work properly. Please correct me, if I guess the wrong path for a program. Don't panic if you do not have some of them, just press ENTER for those. To disable the use of a program, you can type a space followed by ENTER. }, proxy_intro => qq{ If you're accessing the net via proxies, you can specify them in the CPAN configuration or via environment variables. The variable in the \$CPAN::Config takes precedence. }, proxy_user => qq{ If your proxy is an authenticating proxy, you can store your username permanently. If you do not want that, just press ENTER. You will then be asked for your username in every future session. }, proxy_pass => qq{ Your password for the authenticating proxy can also be stored permanently on disk. If this violates your security policy, just press ENTER. You will then be asked for the password in every future session. }, urls_intro => qq{ Now you need to choose your CPAN mirror sites. You can let me pick mirrors for you, you can select them from a list or you can enter them by hand. }, urls_picker_intro => qq{First, pick a nearby continent and country by typing in the number(s) in front of the item(s) you want to select. You can pick several of each, separated by spaces. Then, you will be presented with a list of URLs of CPAN mirrors in the countries you selected, along with previously selected URLs. Select some of those URLs, or just keep the old list. Finally, you will be prompted for any extra URLs -- file:, ftp:, or http: -- that host a CPAN mirror. You should select more than one (just in case the first isn't available). }, password_warn => qq{ Warning: Term::ReadKey seems not to be available, your password will be echoed to the terminal! }, install_help => qq{ Warning: You do not have write permission for Perl library directories. To install modules, you need to configure a local Perl library directory or escalate your privileges. CPAN can help you by bootstrapping the local::lib module or by configuring itself to use 'sudo' (if available). You may also resolve this problem manually if you need to customize your setup. What approach do you want? (Choose 'local::lib', 'sudo' or 'manual') }, local_lib_installed => qq{ local::lib is installed. You must now add the following environment variables to your shell configuration files (or registry, if you are on Windows) and then restart your command line shell and CPAN before installing modules: }, ); die "Coding error in \@prompts declaration. Odd number of elements, above" if (@prompts % 2); %prompts = @prompts; if (scalar(keys %prompts) != scalar(@prompts)/2) { my %already; for my $item (0..$#prompts) { next if $item % 2; die "$prompts[$item] is duplicated\n" if $already{$prompts[$item]}++; } } shift @podpara; while (@podpara) { warn "Alert: cannot parse my own manpage for init dialog" unless $podpara[0] =~ s/^=item\s+//; my $name = shift @podpara; my @para; while (@podpara && $podpara[0] !~ /^=item/) { push @para, shift @podpara; } $prompts{$name} = pop @para; if (@para) { $prompts{$name . "_intro"} = join "", map { "$_\n\n" } @para; } } } sub init { my($configpm, %args) = @_; use Config; # extra args after 'o conf init' my $matcher = $args{args} && @{$args{args}} ? $args{args}[0] : ''; if ($matcher =~ /^\/(.*)\/$/) { # case /regex/ => take the first, ignore the rest $matcher = $1; shift @{$args{args}}; if (@{$args{args}}) { local $" = " "; $CPAN::Frontend->mywarn("Ignoring excessive arguments '@{$args{args}}'"); $CPAN::Frontend->mysleep(2); } } elsif (0 == length $matcher) { } elsif (0 && $matcher eq "~") { # extremely buggy, but a nice idea my @unconfigured = sort grep { not exists $CPAN::Config->{$_} or not defined $CPAN::Config->{$_} or not length $CPAN::Config->{$_} } keys %$CPAN::Config; $matcher = "\\b(".join("|", @unconfigured).")\\b"; $CPAN::Frontend->mywarn("matcher[$matcher]"); } else { # case WORD... => all arguments must be valid for my $arg (@{$args{args}}) { unless (exists $CPAN::HandleConfig::keys{$arg}) { $CPAN::Frontend->mywarn("'$arg' is not a valid configuration variable\n"); return; } } $matcher = "\\b(".join("|",@{$args{args}}).")\\b"; } CPAN->debug("matcher[$matcher]") if $CPAN::DEBUG; unless ($CPAN::VERSION) { require CPAN::Nox; } require CPAN::HandleConfig; CPAN::HandleConfig::require_myconfig_or_config(); $CPAN::Config ||= {}; local($/) = "\n"; local($\) = ""; local($|) = 1; my($ans,$default); # why so half global? # #= Files, directories # local *_real_prompt; if ( $args{autoconfig} ) { $auto_config = 1; } elsif ($matcher) { $auto_config = 0; } else { my $_conf = prompt($prompts{auto_config}, "yes"); $auto_config = ($_conf and $_conf =~ /^y/i) ? 1 : 0; } CPAN->debug("auto_config[$auto_config]") if $CPAN::DEBUG; if ( $auto_config ) { local $^W = 0; # prototype should match that of &MakeMaker::prompt my $current_second = time; my $current_second_count = 0; my $i_am_mad = 0; # silent prompting -- just quietly use default *_real_prompt = sub { return $_[1] }; } # # bootstrap local::lib or sudo # unless ( $matcher || _can_write_to_libdirs() || _using_installbase() || _using_sudo() ) { local $auto_config = 0; # We *must* ask, even under autoconfig local *_real_prompt; # We *must* show prompt my_prompt_loop(install_help => 'local::lib', $matcher, 'local::lib|sudo|manual'); } $CPAN::Config->{install_help} ||= ''; # Temporary to suppress warnings if (!$matcher or q{ build_dir build_dir_reuse cpan_home keep_source_where prefs_dir } =~ /$matcher/) { $CPAN::Frontend->myprint($prompts{config_intro}) unless $auto_config; init_cpan_home($matcher); my_dflt_prompt("keep_source_where", File::Spec->catdir($CPAN::Config->{cpan_home},"sources"), $matcher, ); my_dflt_prompt("build_dir", File::Spec->catdir($CPAN::Config->{cpan_home},"build"), $matcher ); my_yn_prompt(build_dir_reuse => 0, $matcher); my_dflt_prompt("prefs_dir", File::Spec->catdir($CPAN::Config->{cpan_home},"prefs"), $matcher ); } # #= Config: auto_commit # my_yn_prompt(auto_commit => 0, $matcher); # #= Cache size, Index expire # my_dflt_prompt(build_cache => 100, $matcher); my_dflt_prompt(index_expire => 1, $matcher); my_prompt_loop(scan_cache => 'atstart', $matcher, 'atstart|atexit|never'); my_yn_prompt(cleanup_after_install => 0, $matcher); # #= cache_metadata # my_yn_prompt(cache_metadata => 1, $matcher); my_yn_prompt(use_sqlite => 0, $matcher); # #= Do we follow PREREQ_PM? # my_prompt_loop(prerequisites_policy => 'follow', $matcher, 'follow|ask|ignore'); my_prompt_loop(build_requires_install_policy => 'yes', $matcher, 'yes|no|ask/yes|ask/no'); my_yn_prompt(recommends_policy => 1, $matcher); my_yn_prompt(suggests_policy => 0, $matcher); # #= Module::Signature # my_yn_prompt(check_sigs => 0, $matcher); # #= CPAN::Reporter # if (!$matcher or 'test_report' =~ /$matcher/) { my_yn_prompt(test_report => 0, $matcher); if ( $matcher && $CPAN::Config->{test_report} && $CPAN::META->has_inst("CPAN::Reporter") && CPAN::Reporter->can('configure') ) { my $_conf = prompt("Would you like me configure CPAN::Reporter now?", "yes"); if ($_conf =~ /^y/i) { $CPAN::Frontend->myprint("\nProceeding to configure CPAN::Reporter.\n"); CPAN::Reporter::configure(); $CPAN::Frontend->myprint("\nReturning to CPAN configuration.\n"); } } } my_yn_prompt(trust_test_report_history => 0, $matcher); # #= YAML vs. YAML::Syck # if (!$matcher or "yaml_module" =~ /$matcher/) { my_dflt_prompt(yaml_module => "YAML", $matcher); my $old_v = $CPAN::Config->{load_module_verbosity}; $CPAN::Config->{load_module_verbosity} = q[none]; if (!$auto_config && !$CPAN::META->has_inst($CPAN::Config->{yaml_module})) { $CPAN::Frontend->mywarn ("Warning (maybe harmless): '$CPAN::Config->{yaml_module}' not installed.\n"); $CPAN::Frontend->mysleep(3); } $CPAN::Config->{load_module_verbosity} = $old_v; } # #= YAML code deserialisation # my_yn_prompt(yaml_load_code => 0, $matcher); # #= External programs # my(@path) = split /$Config{'path_sep'}/, $ENV{'PATH'}; $CPAN::Frontend->myprint($prompts{external_progs}) if !$matcher && !$auto_config; _init_external_progs($matcher, { path => \@path, progs => [ qw/make bzip2 gzip tar unzip gpg patch applypatch/ ], shortcut => 0 }); _init_external_progs($matcher, { path => \@path, progs => [ qw/wget curl lynx ncftpget ncftp ftp/ ], shortcut => 1 }); { my $path = $CPAN::Config->{'pager'} || $ENV{PAGER} || find_exe("less",\@path) || find_exe("more",\@path) || ($^O eq 'MacOS' ? $ENV{EDITOR} : 0 ) || "more"; my_dflt_prompt(pager => $path, $matcher); } { my $path = $CPAN::Config->{'shell'}; if ($path && File::Spec->file_name_is_absolute($path)) { $CPAN::Frontend->mywarn("Warning: configured $path does not exist\n") unless -e $path; $path = ""; } $path ||= $ENV{SHELL}; $path ||= $ENV{COMSPEC} if $^O eq "MSWin32"; if ($^O eq 'MacOS') { $CPAN::Config->{'shell'} = 'not_here'; } else { $path ||= 'sh', $path =~ s,\\,/,g if $^O eq 'os2'; # Cosmetic only my_dflt_prompt(shell => $path, $matcher); } } { my $tar = $CPAN::Config->{tar}; my $prefer_external_tar = $CPAN::Config->{prefer_external_tar}; # XXX not yet supported unless (defined $prefer_external_tar) { if ($^O =~ /(MSWin32|solaris)/) { # both have a record of broken tars $prefer_external_tar = 0; } elsif ($tar) { $prefer_external_tar = 1; } else { $prefer_external_tar = 0; } } my_yn_prompt(prefer_external_tar => $prefer_external_tar, $matcher); } # # verbosity # my_prompt_loop(tar_verbosity => 'none', $matcher, 'none|v|vv'); my_prompt_loop(load_module_verbosity => 'none', $matcher, 'none|v'); my_prompt_loop(perl5lib_verbosity => 'none', $matcher, 'none|v'); my_yn_prompt(inhibit_startup_message => 0, $matcher); # #= Installer, arguments to make etc. # my_prompt_loop(prefer_installer => 'MB', $matcher, 'MB|EUMM|RAND'); if (!$matcher or 'makepl_arg make_arg' =~ /$matcher/) { my_dflt_prompt(makepl_arg => "", $matcher); my_dflt_prompt(make_arg => "", $matcher); if ( $CPAN::Config->{makepl_arg} =~ /LIBS=|INC=/ ) { $CPAN::Frontend->mywarn( "Warning: Using LIBS or INC in makepl_arg will likely break distributions\n" . "that specify their own LIBS or INC options in Makefile.PL.\n" ); } } require CPAN::HandleConfig; if (exists $CPAN::HandleConfig::keys{make_install_make_command}) { # as long as Windows needs $self->_build_command, we cannot # support sudo on windows :-) my $default = $CPAN::Config->{make} || ""; if ( $default && $CPAN::Config->{install_help} eq 'sudo' ) { if ( find_exe('sudo') ) { $default = "sudo $default"; delete $CPAN::Config->{make_install_make_command} unless $CPAN::Config->{make_install_make_command} =~ /sudo/; } else { $CPAN::Frontend->mywarnonce("Could not find 'sudo' in PATH\n"); } } my_dflt_prompt(make_install_make_command => $default, $matcher); } my_dflt_prompt(make_install_arg => $CPAN::Config->{make_arg} || "", $matcher); my_dflt_prompt(mbuildpl_arg => "", $matcher); my_dflt_prompt(mbuild_arg => "", $matcher); if (exists $CPAN::HandleConfig::keys{mbuild_install_build_command} and $^O ne "MSWin32") { # as long as Windows needs $self->_build_command, we cannot # support sudo on windows :-) my $default = $^O eq 'VMS' ? '@Build.com' : "./Build"; if ( $CPAN::Config->{install_help} eq 'sudo' ) { if ( find_exe('sudo') ) { $default = "sudo $default"; delete $CPAN::Config->{mbuild_install_build_command} unless $CPAN::Config->{mbuild_install_build_command} =~ /sudo/; } else { $CPAN::Frontend->mywarnonce("Could not find 'sudo' in PATH\n"); } } my_dflt_prompt(mbuild_install_build_command => $default, $matcher); } my_dflt_prompt(mbuild_install_arg => "", $matcher); for my $o (qw( allow_installing_outdated_dists allow_installing_module_downgrades )) { my_prompt_loop($o => 'ask/no', $matcher, 'yes|no|ask/yes|ask/no'); } # #== use_prompt_default # my_yn_prompt(use_prompt_default => 0, $matcher); # #= Alarm period # my_dflt_prompt(inactivity_timeout => 0, $matcher); my_dflt_prompt(version_timeout => 15, $matcher); # #== halt_on_failure # my_yn_prompt(halt_on_failure => 0, $matcher); # #= Proxies # my @proxy_vars = qw/ftp_proxy http_proxy no_proxy/; my @proxy_user_vars = qw/proxy_user proxy_pass/; if (!$matcher or "@proxy_vars @proxy_user_vars" =~ /$matcher/) { $CPAN::Frontend->myprint($prompts{proxy_intro}) unless $auto_config; for (@proxy_vars) { $prompts{$_} = "Your $_?"; my_dflt_prompt($_ => $ENV{$_}||"", $matcher); } if ($CPAN::Config->{ftp_proxy} || $CPAN::Config->{http_proxy}) { $default = $CPAN::Config->{proxy_user} || $CPAN::LWP::UserAgent::USER || ""; $CPAN::Frontend->myprint($prompts{proxy_user}) unless $auto_config; if ($CPAN::Config->{proxy_user} = prompt("Your proxy user id?",$default)) { $CPAN::Frontend->myprint($prompts{proxy_pass}) unless $auto_config; if ($CPAN::META->has_inst("Term::ReadKey")) { Term::ReadKey::ReadMode("noecho"); } else { $CPAN::Frontend->myprint($prompts{password_warn}) unless $auto_config; } $CPAN::Config->{proxy_pass} = prompt_no_strip("Your proxy password?"); if ($CPAN::META->has_inst("Term::ReadKey")) { Term::ReadKey::ReadMode("restore"); } $CPAN::Frontend->myprint("\n\n") unless $auto_config; } } } # #= how plugins work # # XXX MISSING: my_array_prompt to be used with plugins. We did something like this near # git log -p fd68f8f5e33f4cecea4fdb7abc5ee19c12f138f0..test-notest-test-dependency # Need to do similar steps for plugin_list. As long as we do not support it here, people # must use the cpan shell prompt to write something like # o conf plugin_list push CPAN::Plugin::Specfile=dir,/tmp/foo-20141013,... # o conf commit # #= how FTP works # my_yn_prompt(ftp_passive => 1, $matcher); # #= how cwd works # my_prompt_loop(getcwd => 'cwd', $matcher, 'cwd|getcwd|fastcwd|getdcwd|backtickcwd'); # #= the CPAN shell itself (prompt, color) # my_yn_prompt(commandnumber_in_prompt => 1, $matcher); my_yn_prompt(term_ornaments => 1, $matcher); if ("colorize_output colorize_print colorize_warn colorize_debug" =~ $matcher) { my_yn_prompt(colorize_output => 0, $matcher); if ($CPAN::Config->{colorize_output}) { if ($CPAN::META->has_inst("Term::ANSIColor")) { my $T="gYw"; $CPAN::Frontend->myprint( " on_ on_y ". " on_ma on_\n") unless $auto_config; $CPAN::Frontend->myprint( " on_black on_red green ellow ". "on_blue genta on_cyan white\n") unless $auto_config; for my $FG ("", "bold", map {$_,"bold $_"} "black","red","green", "yellow","blue", "magenta", "cyan","white") { $CPAN::Frontend->myprint(sprintf( "%12s ", $FG)) unless $auto_config; for my $BG ("",map {"on_$_"} qw(black red green yellow blue magenta cyan white)) { $CPAN::Frontend->myprint( $FG||$BG ? Term::ANSIColor::colored(" $T ","$FG $BG") : " $T ") unless $auto_config; } $CPAN::Frontend->myprint( "\n" ) unless $auto_config; } $CPAN::Frontend->myprint( "\n" ) unless $auto_config; } for my $tuple ( ["colorize_print", "bold blue on_white"], ["colorize_warn", "bold red on_white"], ["colorize_debug", "black on_cyan"], ) { my_dflt_prompt($tuple->[0] => $tuple->[1], $matcher); if ($CPAN::META->has_inst("Term::ANSIColor")) { eval { Term::ANSIColor::color($CPAN::Config->{$tuple->[0]})}; if ($@) { $CPAN::Config->{$tuple->[0]} = $tuple->[1]; $CPAN::Frontend->mywarn($@."setting to default '$tuple->[1]'\n"); } } } } } # #== term_is_latin # my_yn_prompt(term_is_latin => 1, $matcher); # #== save history in file 'histfile' # if (!$matcher or 'histfile histsize' =~ /$matcher/) { $CPAN::Frontend->myprint($prompts{histfile_intro}) unless $auto_config; defined($default = $CPAN::Config->{histfile}) or $default = File::Spec->catfile($CPAN::Config->{cpan_home},"histfile"); my_dflt_prompt(histfile => $default, $matcher); if ($CPAN::Config->{histfile}) { defined($default = $CPAN::Config->{histsize}) or $default = 100; my_dflt_prompt(histsize => $default, $matcher); } } # #== do an ls on the m or the d command # my_yn_prompt(show_upload_date => 0, $matcher); # #== verbosity at the end of the r command # if (!$matcher or 'show_unparsable_versions' =~ /$matcher/ or 'show_zero_versions' =~ /$matcher/ ) { my_yn_prompt(show_unparsable_versions => 0, $matcher); my_yn_prompt(show_zero_versions => 0, $matcher); } # #= MIRRORED.BY and conf_sites() # # Let's assume they want to use the internet and make them turn it # off if they really don't. my_yn_prompt("connect_to_internet_ok" => 1, $matcher); my_yn_prompt("pushy_https" => 1, $matcher); # Allow matching but don't show during manual config if ($matcher) { if ("urllist_ping_external" =~ $matcher) { my_yn_prompt(urllist_ping_external => 0, $matcher); } if ("urllist_ping_verbose" =~ $matcher) { my_yn_prompt(urllist_ping_verbose => 0, $matcher); } if ("randomize_urllist" =~ $matcher) { my_dflt_prompt(randomize_urllist => 0, $matcher); } if ("ftpstats_size" =~ $matcher) { my_dflt_prompt(ftpstats_size => 99, $matcher); } if ("ftpstats_period" =~ $matcher) { my_dflt_prompt(ftpstats_period => 14, $matcher); } } $CPAN::Config->{urllist} ||= []; if ($auto_config) { if(@{ $CPAN::Config->{urllist} }) { $CPAN::Frontend->myprint( "Your 'urllist' is already configured. Type 'o conf init urllist' to change it.\n" ); } else { # Hint: as of 2021-11: to get http, use http://www.cpan.org/ $CPAN::Config->{urllist} = [ 'https://cpan.org/' ]; $CPAN::Frontend->myprint( "We initialized your 'urllist' to @{$CPAN::Config->{urllist}}. Type 'o conf init urllist' to change it.\n" ); } } elsif (!$matcher || "urllist" =~ $matcher) { _do_pick_mirrors(); } if ($auto_config) { $CPAN::Frontend->myprint( "\nAutoconfiguration complete.\n" ); $auto_config = 0; # reset } # bootstrap local::lib now if requested if ( $CPAN::Config->{install_help} eq 'local::lib' ) { if ( ! @{ $CPAN::Config->{urllist} } ) { $CPAN::Frontend->myprint( "\nALERT: Skipping local::lib bootstrap because 'urllist' is not configured.\n" ); } elsif (! $CPAN::Config->{make} ) { $CPAN::Frontend->mywarn( "\nALERT: Skipping local::lib bootstrap because 'make' is not configured.\n" ); _beg_for_make(); # repetitive, but we don't want users to miss it } else { $CPAN::Frontend->myprint("\nAttempting to bootstrap local::lib...\n"); $CPAN::Frontend->myprint("\nWriting $configpm for bootstrap...\n"); delete $CPAN::Config->{install_help}; # temporary only CPAN::HandleConfig->commit; my($dist, $locallib); $locallib = CPAN::Shell->expand('Module', 'local::lib'); if ( $locallib and $dist = $locallib->distribution ) { # this is a hack to force bootstrapping $dist->{prefs}{pl}{commandline} = "$^X Makefile.PL --bootstrap"; # Set @INC for this process so we find things as they bootstrap require lib; lib->import(_local_lib_inc_path()); eval { $dist->install }; } if ( ! $dist || (my $err = $@) ) { $err ||= 'Could not locate local::lib in the CPAN index'; $CPAN::Frontend->mywarn("Error bootstrapping local::lib: $@\n"); $CPAN::Frontend->myprint("From the CPAN Shell, you might try 'look local::lib' and \n" . "run 'perl Makefile --bootstrap' and see if that is successful. Then\n" . "restart your CPAN client\n" ); } else { _local_lib_config(); } } } # install_help is temporary for configuration and not saved delete $CPAN::Config->{install_help}; $CPAN::Frontend->myprint("\n"); if ($matcher && !$CPAN::Config->{auto_commit}) { $CPAN::Frontend->myprint("Please remember to call 'o conf commit' to ". "make the config permanent!\n"); } else { CPAN::HandleConfig->commit; } if (! $matcher) { $CPAN::Frontend->myprint( "\nYou can re-run configuration any time with 'o conf init' in the CPAN shell\n" ); } } sub _local_lib_config { # Set environment stuff for this process require local::lib; # Tell user about environment vars to set $CPAN::Frontend->myprint($prompts{local_lib_installed}); local $ENV{SHELL} = $CPAN::Config->{shell} || $ENV{SHELL}; my $shellvars = local::lib->environment_vars_string_for(_local_lib_path()); $CPAN::Frontend->myprint($shellvars); # Set %ENV after getting string above my %env = local::lib->build_environment_vars_for(_local_lib_path(), 1); while ( my ($k, $v) = each %env ) { $ENV{$k} = $v; } # Offer to mangle the shell config my $munged_rc; if ( my $rc = _find_shell_config() ) { local $auto_config = 0; # We *must* ask, even under autoconfig local *_real_prompt; # We *must* show prompt my $_conf = prompt( "\nWould you like me to append that to $rc now?", "yes" ); if ($_conf =~ /^y/i) { open my $fh, ">>", $rc; print {$fh} "\n$shellvars"; close $fh; $munged_rc++; } } # Warn at exit time if ($munged_rc) { push @{$CPAN::META->_exit_messages}, << "HERE"; *** Remember to restart your shell before running cpan again *** HERE } else { push @{$CPAN::META->_exit_messages}, << "HERE"; *** Remember to add these environment variables to your shell config and restart your shell before running cpan again *** $shellvars HERE } } { my %shell_rc_map = ( map { $_ => ".${_}rc" } qw/ bash tcsh csh /, map { $_ => ".profile" } qw/dash ash sh/, zsh => ".zshenv", ); sub _find_shell_config { my $shell = File::Basename::basename($CPAN::Config->{shell}); if ( my $rc = $shell_rc_map{$shell} ) { my $path = File::Spec->catfile($ENV{HOME}, $rc); return $path if -w $path; } } } sub _local_lib_inc_path { return File::Spec->catdir(_local_lib_path(), qw/lib perl5/); } sub _local_lib_path { return File::Spec->catdir(_local_lib_home(), 'perl5'); } # Adapted from resolve_home_path() in local::lib -- this is where # local::lib thinks the user's home is { my $local_lib_home; sub _local_lib_home { $local_lib_home ||= File::Spec->rel2abs( do { if ($CPAN::META->has_usable("File::HomeDir") && File::HomeDir->VERSION >= 0.65) { File::HomeDir->my_home; } elsif (defined $ENV{HOME}) { $ENV{HOME}; } else { (getpwuid $<)[7] || "~"; } }); } } sub _do_pick_mirrors { local *_real_prompt; *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt; $CPAN::Frontend->myprint($prompts{urls_intro}); # Only prompt for auto-pick if Net::Ping is new enough to do timings my $_conf = 'n'; if ( $CPAN::META->has_usable("Net::Ping") && CPAN::Version->vgt(Net::Ping->VERSION, '2.13')) { $_conf = prompt($prompts{auto_pick}, "yes"); } else { prompt("Autoselection disabled due to Net::Ping missing or insufficient. Please press ENTER"); } my @old_list = @{ $CPAN::Config->{urllist} }; if ( $_conf =~ /^y/i ) { conf_sites( auto_pick => 1 ) or bring_your_own(); } else { _print_urllist('Current') if @old_list; my $msg = scalar @old_list ? "\nWould you like to edit the urllist or pick new mirrors from a list?" : "\nWould you like to pick from the CPAN mirror list?" ; my $_conf = prompt($msg, "yes"); if ( $_conf =~ /^y/i ) { conf_sites(); } bring_your_own(); } _print_urllist('New'); } sub _init_external_progs { my($matcher,$args) = @_; my $PATH = $args->{path}; my @external_progs = @{ $args->{progs} }; my $shortcut = $args->{shortcut}; my $showed_make_warning; if (!$matcher or "@external_progs" =~ /$matcher/) { my $old_warn = $^W; local $^W if $^O eq 'MacOS'; local $^W = $old_warn; my $progname; for $progname (@external_progs) { next if $matcher && $progname !~ /$matcher/; if ($^O eq 'MacOS') { $CPAN::Config->{$progname} = 'not_here'; next; } my $progcall = $progname; unless ($matcher) { # we really don't need ncftp if we have ncftpget, but # if they chose this dialog via matcher, they shall have it next if $progname eq "ncftp" && $CPAN::Config->{ncftpget} gt " "; } my $path = $CPAN::Config->{$progname} || $Config::Config{$progname} || ""; if (File::Spec->file_name_is_absolute($path)) { # testing existence is not good enough, some have these exe # extensions # warn "Warning: configured $path does not exist\n" unless -e $path; # $path = ""; } elsif ($path =~ /^\s+$/) { # preserve disabled programs } else { $path = ''; } unless ($path) { # e.g. make -> nmake $progcall = $Config::Config{$progname} if $Config::Config{$progname}; } $path ||= find_exe($progcall,$PATH); unless ($path) { # not -e $path, because find_exe already checked that local $"=";"; $CPAN::Frontend->mywarn("Warning: $progcall not found in PATH[@$PATH]\n") unless $auto_config; _beg_for_make(), $showed_make_warning++ if $progname eq "make"; } $prompts{$progname} = "Where is your $progname program?"; $path = my_dflt_prompt($progname,$path,$matcher,1); # 1 => no strip spaces my $disabling = $path =~ m/^\s*$/; # don't let them disable or misconfigure make without warning if ( $progname eq "make" && ( $disabling || ! _check_found($path) ) ) { if ( $disabling && $showed_make_warning ) { next; } else { _beg_for_make() unless $showed_make_warning++; undef $CPAN::Config->{$progname}; $CPAN::Frontend->mywarn("Press SPACE and ENTER to disable make (NOT RECOMMENDED)\n"); redo; } } elsif ( $disabling ) { next; } elsif ( _check_found( $CPAN::Config->{$progname} ) ) { last if $shortcut && !$matcher; } else { undef $CPAN::Config->{$progname}; $CPAN::Frontend->mywarn("Press SPACE and ENTER to disable $progname\n"); redo; } } } } sub _check_found { my ($prog) = @_; if ( ! -f $prog ) { $CPAN::Frontend->mywarn("Warning: '$prog' does not exist\n") unless $auto_config; return; } elsif ( ! -x $prog ) { $CPAN::Frontend->mywarn("Warning: '$prog' is not executable\n") unless $auto_config; return; } return 1; } sub _beg_for_make { $CPAN::Frontend->mywarn(<<"HERE"); ALERT: 'make' is an essential tool for building perl Modules. Please make sure you have 'make' (or some equivalent) working. HERE if ($^O eq "MSWin32") { $CPAN::Frontend->mywarn(<<"HERE"); Windows users may want to follow this procedure when back in the CPAN shell: look YVES/scripts/alien_nmake.pl perl alien_nmake.pl This will install nmake on your system which can be used as a 'make' substitute. HERE } $CPAN::Frontend->mywarn(<<"HERE"); You can then retry the 'make' configuration step with o conf init make HERE } sub init_cpan_home { my($matcher) = @_; if (!$matcher or 'cpan_home' =~ /$matcher/) { my $cpan_home = $CPAN::Config->{cpan_home} || CPAN::HandleConfig::cpan_home(); if (-d $cpan_home) { $CPAN::Frontend->myprint( "\nI see you already have a directory\n" . "\n$cpan_home\n" . "Shall we use it as the general CPAN build and cache directory?\n\n" ) unless $auto_config; } else { # no cpan-home, must prompt and get one $CPAN::Frontend->myprint($prompts{cpan_home_where}) unless $auto_config; } my $default = $cpan_home; my $loop = 0; my($last_ans,$ans); $CPAN::Frontend->myprint(" <cpan_home>\n") unless $auto_config; PROMPT: while ($ans = prompt("CPAN build and cache directory?",$default)) { if (File::Spec->file_name_is_absolute($ans)) { my @cpan_home = split /[\/\\]/, $ans; DIR: for my $dir (@cpan_home) { if ($dir =~ /^~/ and (!$last_ans or $ans ne $last_ans)) { $CPAN::Frontend ->mywarn("Warning: a tilde in the path will be ". "taken as a literal tilde. Please ". "confirm again if you want to keep it\n"); $last_ans = $default = $ans; next PROMPT; } } } else { require Cwd; my $cwd = Cwd::cwd(); my $absans = File::Spec->catdir($cwd,$ans); $CPAN::Frontend->mywarn("The path '$ans' is not an ". "absolute path. Please specify ". "an absolute path\n"); $default = $absans; next PROMPT; } eval { File::Path::mkpath($ans); }; # dies if it can't if ($@) { $CPAN::Frontend->mywarn("Couldn't create directory $ans.\n". "Please retry.\n"); next PROMPT; } if (-d $ans && -w _) { last PROMPT; } else { $CPAN::Frontend->mywarn("Couldn't find directory $ans\n". "or directory is not writable. Please retry.\n"); if (++$loop > 5) { $CPAN::Frontend->mydie("Giving up"); } } } $CPAN::Config->{cpan_home} = $ans; } } sub my_dflt_prompt { my ($item, $dflt, $m, $no_strip) = @_; my $default = $CPAN::Config->{$item} || $dflt; if (!$auto_config && (!$m || $item =~ /$m/)) { if (my $intro = $prompts{$item . "_intro"}) { $CPAN::Frontend->myprint($intro); } $CPAN::Frontend->myprint(" <$item>\n"); $CPAN::Config->{$item} = $no_strip ? prompt_no_strip($prompts{$item}, $default) : prompt( $prompts{$item}, $default); } else { $CPAN::Config->{$item} = $default; } return $CPAN::Config->{$item}; } sub my_yn_prompt { my ($item, $dflt, $m) = @_; my $default; defined($default = $CPAN::Config->{$item}) or $default = $dflt; if (!$auto_config && (!$m || $item =~ /$m/)) { if (my $intro = $prompts{$item . "_intro"}) { $CPAN::Frontend->myprint($intro); } $CPAN::Frontend->myprint(" <$item>\n"); my $ans = prompt($prompts{$item}, $default ? 'yes' : 'no'); $CPAN::Config->{$item} = ($ans =~ /^[y1]/i ? 1 : 0); } else { $CPAN::Config->{$item} = $default; } } sub my_prompt_loop { my ($item, $dflt, $m, $ok) = @_; my $default = $CPAN::Config->{$item} || $dflt; my $ans; if (!$auto_config && (!$m || $item =~ /$m/)) { my $intro = $prompts{$item . "_intro"}; $CPAN::Frontend->myprint($intro) if defined $intro; $CPAN::Frontend->myprint(" <$item>\n"); do { $ans = prompt($prompts{$item}, $default); } until $ans =~ /$ok/; $CPAN::Config->{$item} = $ans; } else { $CPAN::Config->{$item} = $default; } } # Here's the logic about the MIRRORED.BY file. There are a number of scenarios: # (1) We have a cached MIRRORED.BY file # (1a) We're auto-picking # - Refresh it automatically if it's old # (1b) Otherwise, ask if using cached is ok. If old, default to no. # - If cached is not ok, get it from the Internet. If it succeeds we use # the new file. Otherwise, we use the old file. # (2) We don't have a copy at all # (2a) If we are allowed to connect, we try to get a new copy. If it succeeds, # we use it, otherwise, we warn about failure # (2b) If we aren't allowed to connect, sub conf_sites { my %args = @_; # auto pick implies using the internet $CPAN::Config->{connect_to_internet_ok} = 1 if $args{auto_pick}; my $m = 'MIRRORED.BY'; my $mby = File::Spec->catfile($CPAN::Config->{keep_source_where},$m); File::Path::mkpath(File::Basename::dirname($mby)); # Why are we using MIRRORED.BY from the current directory? # Is this for testing? -- dagolden, 2009-11-05 if (-f $mby && -f $m && -M $m < -M $mby) { require File::Copy; File::Copy::copy($m,$mby) or die "Could not update $mby: $!"; } local $^T = time; # if we have a cached copy is not older than 60 days, we either # use it or refresh it or fall back to it if the refresh failed. if ($mby && -f $mby && -s _ > 0 ) { my $very_old = (-M $mby > 60); my $mtime = localtime((stat _)[9]); # if auto_pick, refresh anything old automatically if ( $args{auto_pick} ) { if ( $very_old ) { $CPAN::Frontend->myprint(qq{Trying to refresh your mirror list\n}); eval { CPAN::FTP->localize($m,$mby,3,1) } or $CPAN::Frontend->myprint(qq{Refresh failed. Using the old cached copy instead.\n}); $CPAN::Frontend->myprint("\n"); } } else { my $prompt = qq{Found a cached mirror list as of $mtime If you'd like to just use the cached copy, answer 'yes', below. If you'd like an updated copy of the mirror list, answer 'no' and I'll get a fresh one from the Internet. Shall I use the cached mirror list?}; my $ans = prompt($prompt, $very_old ? "no" : "yes"); if ($ans =~ /^n/i) { $CPAN::Frontend->myprint(qq{Trying to refresh your mirror list\n}); # you asked for it from the Internet $CPAN::Config->{connect_to_internet_ok} = 1; eval { CPAN::FTP->localize($m,$mby,3,1) } or $CPAN::Frontend->myprint(qq{Refresh failed. Using the old cached copy instead.\n}); $CPAN::Frontend->myprint("\n"); } } } # else there is no cached copy and we must fetch or fail else { # If they haven't agree to connect to the internet, ask again if ( ! $CPAN::Config->{connect_to_internet_ok} ) { my $prompt = q{You are missing a copy of the CPAN mirror list. May I connect to the Internet to get it?}; my $ans = prompt($prompt, "yes"); if ($ans =~ /^y/i) { $CPAN::Config->{connect_to_internet_ok} = 1; } } # Now get it from the Internet or complain if ( $CPAN::Config->{connect_to_internet_ok} ) { $CPAN::Frontend->myprint(qq{Trying to fetch a mirror list from the Internet\n}); eval { CPAN::FTP->localize($m,$mby,3,1) } or $CPAN::Frontend->mywarn(<<'HERE'); We failed to get a copy of the mirror list from the Internet. You will need to provide CPAN mirror URLs yourself. HERE $CPAN::Frontend->myprint("\n"); } else { $CPAN::Frontend->mywarn(<<'HERE'); You will need to provide CPAN mirror URLs yourself or set 'o conf connect_to_internet_ok 1' and try again. HERE } } # if we finally have a good local MIRRORED.BY, get on with picking if (-f $mby && -s _ > 0){ $CPAN::Config->{urllist} = $args{auto_pick} ? auto_mirrored_by($mby) : choose_mirrored_by($mby); return 1; } return; } sub find_exe { my($exe,$path) = @_; $path ||= [split /$Config{'path_sep'}/, $ENV{'PATH'}]; my($dir); #warn "in find_exe exe[$exe] path[@$path]"; for $dir (@$path) { my $abs = File::Spec->catfile($dir,$exe); if (($abs = MM->maybe_command($abs))) { return $abs; } } } sub picklist { my($items,$prompt,$default,$require_nonempty,$empty_warning)=@_; CPAN->debug("picklist('$items','$prompt','$default','$require_nonempty',". "'$empty_warning')") if $CPAN::DEBUG; $default ||= ''; my $pos = 0; my @nums; SELECTION: while (1) { # display, at most, 15 items at a time my $limit = $#{ $items } - $pos; $limit = 15 if $limit > 15; # show the next $limit items, get the new position $pos = display_some($items, $limit, $pos, $default); $pos = 0 if $pos >= @$items; my $num = prompt($prompt,$default); @nums = split (' ', $num); { my %seen; @nums = grep { !$seen{$_}++ } @nums; } my $i = scalar @$items; unrangify(\@nums); if (0 == @nums) { # cannot allow nothing because nothing means paging! # return; } elsif (grep (/\D/ || $_ < 1 || $_ > $i, @nums)) { $CPAN::Frontend->mywarn("invalid items entered, try again\n"); if ("@nums" =~ /\D/) { $CPAN::Frontend->mywarn("(we are expecting only numbers between 1 and $i)\n"); } next SELECTION; } if ($require_nonempty && !@nums) { $CPAN::Frontend->mywarn("$empty_warning\n"); } # a blank line continues... unless (@nums){ $CPAN::Frontend->mysleep(0.1); # prevent hot spinning process on the next bug next SELECTION; } last; } for (@nums) { $_-- } @{$items}[@nums]; } sub unrangify ($) { my($nums) = $_[0]; my @nums2 = (); while (@{$nums||[]}) { my $n = shift @$nums; if ($n =~ /^(\d+)-(\d+)$/) { my @range = $1 .. $2; # warn "range[@range]"; push @nums2, @range; } else { push @nums2, $n; } } push @$nums, @nums2; } sub display_some { my ($items, $limit, $pos, $default) = @_; $pos ||= 0; my @displayable = @$items[$pos .. ($pos + $limit)]; for my $item (@displayable) { $CPAN::Frontend->myprint(sprintf "(%d) %s\n", ++$pos, $item); } my $hit_what = $default ? "SPACE ENTER" : "ENTER"; $CPAN::Frontend->myprint(sprintf("%d more items, hit %s to show them\n", (@$items - $pos), $hit_what, )) if $pos < @$items; return $pos; } sub auto_mirrored_by { my $local = shift or return; local $|=1; $CPAN::Frontend->myprint("Looking for CPAN mirrors near you (please be patient)\n"); my $mirrors = CPAN::Mirrors->new($local); my $cnt = 0; my $callback_was_active = 0; my @best = $mirrors->best_mirrors( how_many => 3, callback => sub { $callback_was_active++; $CPAN::Frontend->myprint("."); if ($cnt++>60) { $cnt=0; $CPAN::Frontend->myprint("\n"); } }, $CPAN::Config->{urllist_ping_external} ? (external_ping => 1) : (), $CPAN::Config->{urllist_ping_verbose} ? (verbose => 1) : (), ); my $urllist = [ map { $_->http } grep { $_ && ref $_ && $_->can('http') } @best ]; push @$urllist, grep { /^file:/ } @{$CPAN::Config->{urllist}}; $CPAN::Frontend->myprint(" done!\n\n") if $callback_was_active; return $urllist } sub choose_mirrored_by { my $local = shift or return; my ($default); my $mirrors = CPAN::Mirrors->new($local); my @previous_urls = @{$CPAN::Config->{urllist}}; $CPAN::Frontend->myprint($prompts{urls_picker_intro}); my (@cont, $cont, %cont, @countries, @urls, %seen); my $no_previous_warn = "Sorry! since you don't have any existing picks, you must make a\n" . "geographic selection."; my $offer_cont = [sort $mirrors->continents]; if (@previous_urls) { push @$offer_cont, "(edit previous picks)"; $default = @$offer_cont; } else { # cannot allow nothing because nothing means paging! # push @$offer_cont, "(none of the above)"; } @cont = picklist($offer_cont, "Select your continent (or several nearby continents)", $default, ! @previous_urls, $no_previous_warn); # cannot allow nothing because nothing means paging! # return unless @cont; foreach $cont (@cont) { my @c = sort $mirrors->countries($cont); @cont{@c} = map ($cont, 0..$#c); @c = map ("$_ ($cont)", @c) if @cont > 1; push (@countries, @c); } if (@previous_urls && @countries) { push @countries, "(edit previous picks)"; $default = @countries; } if (@countries) { @countries = picklist (\@countries, "Select your country (or several nearby countries)", $default, ! @previous_urls, $no_previous_warn); %seen = map (($_ => 1), @previous_urls); # hmmm, should take list of defaults from CPAN::Config->{'urllist'}... foreach my $country (@countries) { next if $country =~ /edit previous picks/; (my $bare_country = $country) =~ s/ \(.*\)//; my @u; for my $m ( $mirrors->mirrors($bare_country) ) { push @u, $m->ftp if $m->ftp; push @u, $m->http if $m->http; } @u = grep (! $seen{$_}, @u); @u = map ("$_ ($bare_country)", @u) if @countries > 1; push (@urls, sort @u); } } push (@urls, map ("$_ (previous pick)", @previous_urls)); my $prompt = "Select as many URLs as you like (by number), put them on one line, separated by blanks, hyphenated ranges allowed e.g. '1 4 5' or '7 1-4 8'"; if (@previous_urls) { $default = join (' ', ((scalar @urls) - (scalar @previous_urls) + 1) .. (scalar @urls)); $prompt .= "\n(or just hit ENTER to keep your previous picks)"; } @urls = picklist (\@urls, $prompt, $default); foreach (@urls) { s/ \(.*\)//; } return [ @urls ]; } sub bring_your_own { my $urllist = [ @{$CPAN::Config->{urllist}} ]; my %seen = map (($_ => 1), @$urllist); my($ans,@urls); my $eacnt = 0; # empty answers $CPAN::Frontend->myprint(<<'HERE'); Now you can enter your own CPAN URLs by hand. A local CPAN mirror can be listed using a 'file:' URL like 'file:///path/to/cpan/' HERE do { my $prompt = "Enter another URL or ENTER to quit:"; unless (%seen) { $prompt = qq{CPAN.pm needs at least one URL where it can fetch CPAN files from. Please enter your CPAN site:}; } $ans = prompt ($prompt, ""); if ($ans) { $ans =~ s|/?\z|/|; # has to end with one slash # XXX This manipulation is odd. Shouldn't we check that $ans is # a directory before converting to file:///? And we need /// below, # too, don't we? -- dagolden, 2009-11-05 $ans = "file:$ans" unless $ans =~ /:/; # without a scheme is a file: if ($ans =~ /^\w+:\/./) { push @urls, $ans unless $seen{$ans}++; } else { $CPAN::Frontend-> myprint(sprintf(qq{"%s" doesn\'t look like an URL at first sight. I\'ll ignore it for now. You can add it to your %s later if you\'re sure it\'s right.\n}, $ans, $INC{'CPAN/MyConfig.pm'} || $INC{'CPAN/Config.pm'} || "configuration file", )); } } else { if (++$eacnt >= 5) { $CPAN::Frontend-> mywarn("Giving up.\n"); $CPAN::Frontend->mysleep(5); return; } } } while $ans || !%seen; @$urllist = CPAN::_uniq(@$urllist, @urls); $CPAN::Config->{urllist} = $urllist; } sub _print_urllist { my ($which) = @_; $CPAN::Frontend->myprint("$which urllist\n"); for ( @{$CPAN::Config->{urllist} || []} ) { $CPAN::Frontend->myprint(" $_\n") }; } sub _can_write_to_libdirs { return -w $Config{installprivlib} && -w $Config{installarchlib} && -w $Config{installsitelib} && -w $Config{installsitearch} } sub _using_installbase { return 1 if $ENV{PERL_MM_OPT} && $ENV{PERL_MM_OPT} =~ /install_base/i; return 1 if grep { ($CPAN::Config->{$_}||q{}) =~ /install_base/i } qw(makepl_arg make_install_arg mbuildpl_arg mbuild_install_arg); return; } sub _using_sudo { return 1 if grep { ($CPAN::Config->{$_}||q{}) =~ /sudo/ } qw(make_install_make_command mbuild_install_build_command); return; } sub _strip_spaces { $_[0] =~ s/^\s+//; # no leading spaces $_[0] =~ s/\s+\z//; # no trailing spaces } sub prompt ($;$) { unless (defined &_real_prompt) { *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt; } my $ans = _real_prompt(@_); _strip_spaces($ans); $CPAN::Frontend->myprint("\n") unless $auto_config; return $ans; } sub prompt_no_strip ($;$) { unless (defined &_real_prompt) { *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt; } return _real_prompt(@_); } 1; PK�������!�o������perl5/CPAN/CacheMgr.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::CacheMgr; use strict; use CPAN::InfoObj; @CPAN::CacheMgr::ISA = qw(CPAN::InfoObj CPAN); use Cwd qw(chdir); use File::Find; use vars qw( $VERSION ); $VERSION = "5.5002"; package CPAN::CacheMgr; use strict; #-> sub CPAN::CacheMgr::as_string ; sub as_string { eval { require Data::Dumper }; if ($@) { return shift->SUPER::as_string; } else { return Data::Dumper::Dumper(shift); } } #-> sub CPAN::CacheMgr::cachesize ; sub cachesize { shift->{DU}; } #-> sub CPAN::CacheMgr::tidyup ; sub tidyup { my($self) = @_; return unless $CPAN::META->{LOCK}; return unless -d $self->{ID}; my @toremove = grep { $self->{SIZE}{$_}==0 } @{$self->{FIFO}}; for my $current (0..$#toremove) { my $toremove = $toremove[$current]; $CPAN::Frontend->myprint(sprintf( "DEL(%d/%d): %s \n", $current+1, scalar @toremove, $toremove, ) ); return if $CPAN::Signal; $self->_clean_cache($toremove); return if $CPAN::Signal; } $self->{FIFO} = []; } #-> sub CPAN::CacheMgr::dir ; sub dir { shift->{ID}; } #-> sub CPAN::CacheMgr::entries ; sub entries { my($self,$dir) = @_; return unless defined $dir; $self->debug("reading dir[$dir]") if $CPAN::DEBUG; $dir ||= $self->{ID}; my($cwd) = CPAN::anycwd(); chdir $dir or Carp::croak("Can't chdir to $dir: $!"); my $dh = DirHandle->new(File::Spec->curdir) or Carp::croak("Couldn't opendir $dir: $!"); my(@entries); for ($dh->read) { next if $_ eq "." || $_ eq ".."; if (-f $_) { push @entries, File::Spec->catfile($dir,$_); } elsif (-d _) { push @entries, File::Spec->catdir($dir,$_); } else { $CPAN::Frontend->mywarn("Warning: weird direntry in $dir: $_\n"); } } chdir $cwd or Carp::croak("Can't chdir to $cwd: $!"); sort { -M $a <=> -M $b} @entries; } #-> sub CPAN::CacheMgr::disk_usage ; sub disk_usage { my($self,$dir,$fast) = @_; return if exists $self->{SIZE}{$dir}; return if $CPAN::Signal; my($Du) = 0; if (-e $dir) { if (-d $dir) { unless (-x $dir) { unless (chmod 0755, $dir) { $CPAN::Frontend->mywarn("I have neither the -x permission nor the ". "permission to change the permission; cannot ". "estimate disk usage of '$dir'\n"); $CPAN::Frontend->mysleep(5); return; } } } elsif (-f $dir) { # nothing to say, no matter what the permissions } } else { $CPAN::Frontend->mywarn("File or directory '$dir' has gone, ignoring\n"); return; } if ($fast) { $Du = 0; # placeholder } else { find( sub { $File::Find::prune++ if $CPAN::Signal; return if -l $_; if ($^O eq 'MacOS') { require Mac::Files; my $cat = Mac::Files::FSpGetCatInfo($_); $Du += $cat->ioFlLgLen() + $cat->ioFlRLgLen() if $cat; } else { if (-d _) { unless (-x _) { unless (chmod 0755, $_) { $CPAN::Frontend->mywarn("I have neither the -x permission nor ". "the permission to change the permission; ". "can only partially estimate disk usage ". "of '$_'\n"); $CPAN::Frontend->mysleep(5); return; } } } else { $Du += (-s _); } } }, $dir ); } return if $CPAN::Signal; $self->{SIZE}{$dir} = $Du/1024/1024; unshift @{$self->{FIFO}}, $dir; $self->debug("measured $dir is $Du") if $CPAN::DEBUG; $self->{DU} += $Du/1024/1024; $self->{DU}; } #-> sub CPAN::CacheMgr::_clean_cache ; sub _clean_cache { my($self,$dir) = @_; return unless -e $dir; unless (File::Spec->canonpath(File::Basename::dirname($dir)) eq File::Spec->canonpath($CPAN::Config->{build_dir})) { $CPAN::Frontend->mywarn("Directory '$dir' not below $CPAN::Config->{build_dir}, ". "will not remove\n"); $CPAN::Frontend->mysleep(5); return; } $self->debug("have to rmtree $dir, will free $self->{SIZE}{$dir}") if $CPAN::DEBUG; File::Path::rmtree($dir); my $id_deleted = 0; if ($dir !~ /\.yml$/ && -f "$dir.yml") { my $yaml_module = CPAN::_yaml_module(); if ($CPAN::META->has_inst($yaml_module)) { my($peek_yaml) = eval { CPAN->_yaml_loadfile("$dir.yml"); }; if ($@) { $CPAN::Frontend->mywarn("(parse error on '$dir.yml' removing anyway)"); unlink "$dir.yml" or $CPAN::Frontend->mywarn("(Could not unlink '$dir.yml': $!)"); return; } elsif (my $id = $peek_yaml->[0]{distribution}{ID}) { $CPAN::META->delete("CPAN::Distribution", $id); # XXX we should restore the state NOW, otherwise this # distro does not exist until we read an index. BUG ALERT(?) # $CPAN::Frontend->mywarn (" +++\n"); $id_deleted++; } } unlink "$dir.yml"; # may fail unless ($id_deleted) { CPAN->debug("no distro found associated with '$dir'"); } } $self->{DU} -= $self->{SIZE}{$dir}; delete $self->{SIZE}{$dir}; } #-> sub CPAN::CacheMgr::new ; sub new { my($class,$phase) = @_; $phase ||= "atstart"; my $time = time; my($debug,$t2); $debug = ""; my $self = { ID => $CPAN::Config->{build_dir}, MAX => $CPAN::Config->{'build_cache'}, SCAN => $CPAN::Config->{'scan_cache'} || 'atstart', DU => 0 }; $CPAN::Frontend->mydie("Unknown scan_cache argument: $self->{SCAN}") unless $self->{SCAN} =~ /never|atstart|atexit/; File::Path::mkpath($self->{ID}); my $dh = DirHandle->new($self->{ID}); bless $self, $class; $self->scan_cache($phase); $t2 = time; $debug .= "timing of CacheMgr->new: ".($t2 - $time); $time = $t2; CPAN->debug($debug) if $CPAN::DEBUG; $self; } #-> sub CPAN::CacheMgr::scan_cache ; sub scan_cache { my ($self, $phase) = @_; $phase = '' unless defined $phase; return unless $phase eq $self->{SCAN}; return unless $CPAN::META->{LOCK}; $CPAN::Frontend->myprint( sprintf("Scanning cache %s for sizes\n", $self->{ID})); my $e; my @entries = $self->entries($self->{ID}); my $i = 0; my $painted = 0; for $e (@entries) { my $symbol = "."; if ($self->{DU} > $self->{MAX}) { $symbol = "-"; $self->disk_usage($e,1); } else { $self->disk_usage($e); } $i++; while (($painted/76) < ($i/@entries)) { $CPAN::Frontend->myprint($symbol); $painted++; } return if $CPAN::Signal; } $CPAN::Frontend->myprint("DONE\n"); $self->tidyup; } 1; PK�������!�CvW��vW����perl5/CPAN/Module.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Module; use strict; @CPAN::Module::ISA = qw(CPAN::InfoObj); use vars qw( $VERSION ); $VERSION = "5.5003"; BEGIN { # alarm() is not implemented in perl 5.6.x and earlier under Windows *ALARM_IMPLEMENTED = sub () { $] >= 5.007 || $^O !~ /MSWin/ }; } # Accessors #-> sub CPAN::Module::userid sub userid { my $self = shift; my $ro = $self->ro; return unless $ro; return $ro->{userid} || $ro->{CPAN_USERID}; } #-> sub CPAN::Module::description sub description { my $self = shift; my $ro = $self->ro or return ""; $ro->{description} } #-> sub CPAN::Module::distribution sub distribution { my($self) = @_; CPAN::Shell->expand("Distribution",$self->cpan_file); } #-> sub CPAN::Module::_is_representative_module sub _is_representative_module { my($self) = @_; return $self->{_is_representative_module} if defined $self->{_is_representative_module}; my $pm = $self->cpan_file or return $self->{_is_representative_module} = 0; $pm =~ s|.+/||; $pm =~ s{\.(?:tar\.(bz2|gz|Z)|t(?:gz|bz)|zip)$}{}i; # see base_id $pm =~ s|-\d+\.\d+.+$||; $pm =~ s|-[\d\.]+$||; $pm =~ s/-/::/g; $self->{_is_representative_module} = $pm eq $self->{ID} ? 1 : 0; # warn "DEBUG: $pm eq $self->{ID} => $self->{_is_representative_module}"; $self->{_is_representative_module}; } #-> sub CPAN::Module::undelay sub undelay { my $self = shift; delete $self->{later}; if ( my $dist = CPAN::Shell->expand("Distribution", $self->cpan_file) ) { $dist->undelay; } } # mark as dirty/clean #-> sub CPAN::Module::color_cmd_tmps ; sub color_cmd_tmps { my($self) = shift; my($depth) = shift || 0; my($color) = shift || 0; my($ancestors) = shift || []; # a module needs to recurse to its cpan_file return if exists $self->{incommandcolor} && $color==1 && $self->{incommandcolor}==$color; return if $color==0 && !$self->{incommandcolor}; if ($color>=1) { if ( $self->uptodate ) { $self->{incommandcolor} = $color; return; } elsif (my $have_version = $self->available_version) { # maybe what we have is good enough if (@$ancestors) { my $who_asked_for_me = $ancestors->[-1]; my $obj = CPAN::Shell->expandany($who_asked_for_me); if (0) { } elsif ($obj->isa("CPAN::Bundle")) { # bundles cannot specify a minimum version return; } elsif ($obj->isa("CPAN::Distribution")) { if (my $prereq_pm = $obj->prereq_pm) { for my $k (keys %$prereq_pm) { if (my $want_version = $prereq_pm->{$k}{$self->id}) { if (CPAN::Version->vcmp($have_version,$want_version) >= 0) { $self->{incommandcolor} = $color; return; } } } } } } } } else { $self->{incommandcolor} = $color; # set me before recursion, # so we can break it } if ($depth>=$CPAN::MAX_RECURSION) { my $e = CPAN::Exception::RecursiveDependency->new($ancestors); if ($e->is_resolvable) { return $self->{incommandcolor}=2; } else { die $e; } } # warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1; if ( my $dist = CPAN::Shell->expand("Distribution", $self->cpan_file) ) { $dist->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]); } # unreached code? # if ($color==0) { # delete $self->{badtestcnt}; # } $self->{incommandcolor} = $color; } #-> sub CPAN::Module::as_glimpse ; sub as_glimpse { my($self) = @_; my(@m); my $class = ref($self); $class =~ s/^CPAN:://; my $color_on = ""; my $color_off = ""; if ( $CPAN::Shell::COLOR_REGISTERED && $CPAN::META->has_inst("Term::ANSIColor") && $self->description ) { $color_on = Term::ANSIColor::color("green"); $color_off = Term::ANSIColor::color("reset"); } my $uptodateness = " "; unless ($class eq "Bundle") { my $u = $self->uptodate; $uptodateness = $u ? "=" : "<" if defined $u; }; my $id = do { my $d = $self->distribution; $d ? $d -> pretty_id : $self->cpan_userid; }; push @m, sprintf("%-7s %1s %s%-22s%s (%s)\n", $class, $uptodateness, $color_on, $self->id, $color_off, $id, ); join "", @m; } #-> sub CPAN::Module::dslip_status sub dslip_status { my($self) = @_; my($stat); # development status @{$stat->{D}}{qw,i c a b R M S,} = qw,idea pre-alpha alpha beta released mature standard,; # support level @{$stat->{S}}{qw,m d u n a,} = qw,mailing-list developer comp.lang.perl.* none abandoned,; # language @{$stat->{L}}{qw,p c + o h,} = qw,perl C C++ other hybrid,; # interface @{$stat->{I}}{qw,f r O p h n,} = qw,functions references+ties object-oriented pragma hybrid none,; # public licence @{$stat->{P}}{qw,p g l b a 2 o d r n,} = qw,Standard-Perl GPL LGPL BSD Artistic Artistic_2 open-source distribution_allowed restricted_distribution no_licence,; for my $x (qw(d s l i p)) { $stat->{$x}{' '} = 'unknown'; $stat->{$x}{'?'} = 'unknown'; } my $ro = $self->ro; return +{} unless $ro && $ro->{statd}; return { D => $ro->{statd}, S => $ro->{stats}, L => $ro->{statl}, I => $ro->{stati}, P => $ro->{statp}, DV => $stat->{D}{$ro->{statd}}, SV => $stat->{S}{$ro->{stats}}, LV => $stat->{L}{$ro->{statl}}, IV => $stat->{I}{$ro->{stati}}, PV => $stat->{P}{$ro->{statp}}, }; } #-> sub CPAN::Module::as_string ; sub as_string { my($self) = @_; my(@m); CPAN->debug("$self entering as_string") if $CPAN::DEBUG; my $class = ref($self); $class =~ s/^CPAN:://; local($^W) = 0; push @m, $class, " id = $self->{ID}\n"; my $sprintf = " %-12s %s\n"; push @m, sprintf($sprintf, 'DESCRIPTION', $self->description) if $self->description; my $sprintf2 = " %-12s %s (%s)\n"; my($userid); $userid = $self->userid; if ( $userid ) { my $author; if ($author = CPAN::Shell->expand('Author',$userid)) { my $email = ""; my $m; # old perls if ($m = $author->email) { $email = " <$m>"; } push @m, sprintf( $sprintf2, 'CPAN_USERID', $userid, $author->fullname . $email ); } } push @m, sprintf($sprintf, 'CPAN_VERSION', $self->cpan_version) if $self->cpan_version; if (my $cpan_file = $self->cpan_file) { push @m, sprintf($sprintf, 'CPAN_FILE', $cpan_file); if (my $dist = CPAN::Shell->expand("Distribution",$cpan_file)) { my $upload_date = $dist->upload_date; if ($upload_date) { push @m, sprintf($sprintf, 'UPLOAD_DATE', $upload_date); } } } my $sprintf3 = " %-12s %1s%1s%1s%1s%1s (%s,%s,%s,%s,%s)\n"; my $dslip = $self->dslip_status; push @m, sprintf( $sprintf3, 'DSLIP_STATUS', @{$dslip}{qw(D S L I P DV SV LV IV PV)}, ) if $dslip->{D}; my $local_file = $self->inst_file; unless ($self->{MANPAGE}) { my $manpage; if ($local_file) { $manpage = $self->manpage_headline($local_file); } else { # If we have already untarred it, we should look there my $dist = $CPAN::META->instance('CPAN::Distribution', $self->cpan_file); # warn "dist[$dist]"; # mff=manifest file; mfh=manifest handle my($mff,$mfh); if ( $dist->{build_dir} and (-f ($mff = File::Spec->catfile($dist->{build_dir}, "MANIFEST"))) and $mfh = FileHandle->new($mff) ) { CPAN->debug("mff[$mff]") if $CPAN::DEBUG; my $lfre = $self->id; # local file RE $lfre =~ s/::/./g; $lfre .= "\\.pm\$"; my($lfl); # local file file local $/ = "\n"; my(@mflines) = <$mfh>; for (@mflines) { s/^\s+//; s/\s.*//s; } while (length($lfre)>5 and !$lfl) { ($lfl) = grep /$lfre/, @mflines; CPAN->debug("lfl[$lfl]lfre[$lfre]") if $CPAN::DEBUG; $lfre =~ s/.+?\.//; } $lfl =~ s/\s.*//; # remove comments $lfl =~ s/\s+//g; # chomp would maybe be too system-specific my $lfl_abs = File::Spec->catfile($dist->{build_dir},$lfl); # warn "lfl_abs[$lfl_abs]"; if (-f $lfl_abs) { $manpage = $self->manpage_headline($lfl_abs); } } } $self->{MANPAGE} = $manpage if $manpage; } my($item); for $item (qw/MANPAGE/) { push @m, sprintf($sprintf, $item, $self->{$item}) if exists $self->{$item}; } for $item (qw/CONTAINS/) { push @m, sprintf($sprintf, $item, join(" ",@{$self->{$item}})) if exists $self->{$item} && @{$self->{$item}}; } push @m, sprintf($sprintf, 'INST_FILE', $local_file || "(not installed)"); push @m, sprintf($sprintf, 'INST_VERSION', $self->inst_version) if $local_file; if (%{$CPAN::META->{is_tested}||{}}) { # XXX needs to be methodified somehow my $available_file = $self->available_file; if ($available_file && $available_file ne $local_file) { push @m, sprintf($sprintf, 'AVAILABLE_FILE', $available_file); push @m, sprintf($sprintf, 'AVAILABLE_VERSION', $self->available_version); } } join "", @m, "\n"; } #-> sub CPAN::Module::manpage_headline sub manpage_headline { my($self,$local_file) = @_; my(@local_file) = $local_file; $local_file =~ s/\.pm(?!\n)\Z/.pod/; push @local_file, $local_file; my(@result,$locf); for $locf (@local_file) { next unless -f $locf; my $fh = FileHandle->new($locf) or $Carp::Frontend->mydie("Couldn't open $locf: $!"); my $inpod = 0; local $/ = "\n"; while (<$fh>) { $inpod = m/^=(?!head1\s+NAME\s*$)/ ? 0 : m/^=head1\s+NAME\s*$/ ? 1 : $inpod; next unless $inpod; next if /^=/; next if /^\s+$/; chomp; push @result, $_; } close $fh; last if @result; } for (@result) { s/^\s+//; s/\s+$//; } join " ", @result; } #-> sub CPAN::Module::cpan_file ; # Note: also inherited by CPAN::Bundle sub cpan_file { my $self = shift; # CPAN->debug(sprintf "id[%s]", $self->id) if $CPAN::DEBUG; unless ($self->ro) { CPAN::Index->reload; } my $ro = $self->ro; if ($ro && defined $ro->{CPAN_FILE}) { return $ro->{CPAN_FILE}; } else { my $userid = $self->userid; if ( $userid ) { if ($CPAN::META->exists("CPAN::Author",$userid)) { my $author = $CPAN::META->instance("CPAN::Author", $userid); my $fullname = $author->fullname; my $email = $author->email; unless (defined $fullname && defined $email) { return sprintf("Contact Author %s", $userid, ); } return "Contact Author $fullname <$email>"; } else { return "Contact Author $userid (Email address not available)"; } } else { return "N/A"; } } } #-> sub CPAN::Module::cpan_version ; sub cpan_version { my $self = shift; my $ro = $self->ro; unless ($ro) { # Can happen with modules that are not on CPAN $ro = {}; } $ro->{CPAN_VERSION} = 'undef' unless defined $ro->{CPAN_VERSION}; $ro->{CPAN_VERSION}; } #-> sub CPAN::Module::force ; sub force { my($self) = @_; $self->{force_update} = 1; } #-> sub CPAN::Module::fforce ; sub fforce { my($self) = @_; $self->{force_update} = 2; } #-> sub CPAN::Module::notest ; sub notest { my($self) = @_; # $CPAN::Frontend->mywarn("XDEBUG: set notest for Module"); $self->{notest}++; } #-> sub CPAN::Module::rematein ; sub rematein { my($self,$meth) = @_; $CPAN::Frontend->myprint(sprintf("Running %s for module '%s'\n", $meth, $self->id)); my $cpan_file = $self->cpan_file; if ($cpan_file eq "N/A" || $cpan_file =~ /^Contact Author/) { $CPAN::Frontend->mywarn(sprintf qq{ The module %s isn\'t available on CPAN. Either the module has not yet been uploaded to CPAN, or it is temporary unavailable. Please contact the author to find out more about the status. Try 'i %s'. }, $self->id, $self->id, ); return; } my $pack = $CPAN::META->instance('CPAN::Distribution',$cpan_file); $pack->called_for($self->id); if (exists $self->{force_update}) { if ($self->{force_update} == 2) { $pack->fforce($meth); } else { $pack->force($meth); } } $pack->notest($meth) if exists $self->{notest} && $self->{notest}; $pack->{reqtype} ||= ""; CPAN->debug("dist-reqtype[$pack->{reqtype}]". "self-reqtype[$self->{reqtype}]") if $CPAN::DEBUG; if ($pack->{reqtype}) { if ($pack->{reqtype} eq "b" && $self->{reqtype} =~ /^[rc]$/) { $pack->{reqtype} = $self->{reqtype}; if ( exists $pack->{install} && ( UNIVERSAL::can($pack->{install},"failed") ? $pack->{install}->failed : $pack->{install} =~ /^NO/ ) ) { delete $pack->{install}; $CPAN::Frontend->mywarn ("Promoting $pack->{ID} from 'build_requires' to 'requires'"); } } } else { $pack->{reqtype} = $self->{reqtype}; } my $success = eval { $pack->$meth(); }; my $err = $@; $pack->unforce if $pack->can("unforce") && exists $self->{force_update}; $pack->unnotest if $pack->can("unnotest") && exists $self->{notest}; delete $self->{force_update}; delete $self->{notest}; if ($err) { die $err; } return $success; } #-> sub CPAN::Module::perldoc ; sub perldoc { shift->rematein('perldoc') } #-> sub CPAN::Module::readme ; sub readme { shift->rematein('readme') } #-> sub CPAN::Module::look ; sub look { shift->rematein('look') } #-> sub CPAN::Module::cvs_import ; sub cvs_import { shift->rematein('cvs_import') } #-> sub CPAN::Module::get ; sub get { shift->rematein('get',@_) } #-> sub CPAN::Module::make ; sub make { shift->rematein('make') } #-> sub CPAN::Module::test ; sub test { my $self = shift; # $self->{badtestcnt} ||= 0; $self->rematein('test',@_); } #-> sub CPAN::Module::deprecated_in_core ; sub deprecated_in_core { my ($self) = @_; return unless $CPAN::META->has_inst('Module::CoreList') && Module::CoreList->can('is_deprecated'); return Module::CoreList::is_deprecated($self->{ID}); } #-> sub CPAN::Module::inst_deprecated; # Indicates whether the *installed* version of the module is a deprecated *and* # installed as part of the Perl core library path sub inst_deprecated { my ($self) = @_; my $inst_file = $self->inst_file or return; return $self->deprecated_in_core && $self->_in_priv_or_arch($inst_file); } #-> sub CPAN::Module::uptodate ; sub uptodate { my ($self) = @_; local ($_); my $inst = $self->inst_version or return 0; my $cpan = $self->cpan_version; return 0 if CPAN::Version->vgt($cpan,$inst) || $self->inst_deprecated; CPAN->debug (join ("", "returning uptodate. ", "cpan[$cpan]inst[$inst]", )) if $CPAN::DEBUG; return 1; } # returns true if installed in privlib or archlib sub _in_priv_or_arch { my($self,$inst_file) = @_; foreach my $pair ( [qw(sitearchexp archlibexp)], [qw(sitelibexp privlibexp)] ) { my ($site, $priv) = @Config::Config{@$pair}; if ($^O eq 'VMS') { for my $d ($site, $priv) { $d = VMS::Filespec::unixify($d) }; } s!/*$!!g foreach $site, $priv; next if $site eq $priv; if ($priv eq substr($inst_file,0,length($priv))) { return 1; } } return 0; } #-> sub CPAN::Module::install ; sub install { my($self) = @_; my($doit) = 0; if ($self->uptodate && not exists $self->{force_update} ) { $CPAN::Frontend->myprint(sprintf("%s is up to date (%s).\n", $self->id, $self->inst_version, )); } else { $doit = 1; } my $ro = $self->ro; if ($ro && $ro->{stats} && $ro->{stats} eq "a") { $CPAN::Frontend->mywarn(qq{ \n\n\n ***WARNING*** The module $self->{ID} has no active maintainer (CPAN support level flag 'abandoned').\n\n\n }); $CPAN::Frontend->mysleep(5); } return $doit ? $self->rematein('install') : 1; } #-> sub CPAN::Module::clean ; sub clean { shift->rematein('clean') } #-> sub CPAN::Module::inst_file ; sub inst_file { my($self) = @_; $self->_file_in_path([@INC]); } #-> sub CPAN::Module::available_file ; sub available_file { my($self) = @_; my $sep = $Config::Config{path_sep}; my $perllib = $ENV{PERL5LIB}; $perllib = $ENV{PERLLIB} unless defined $perllib; my @perllib = split(/$sep/,$perllib) if defined $perllib; my @cpan_perl5inc; if ($CPAN::Perl5lib_tempfile) { my $yaml = CPAN->_yaml_loadfile($CPAN::Perl5lib_tempfile); @cpan_perl5inc = @{$yaml->[0]{inc} || []}; } $self->_file_in_path([@cpan_perl5inc,@perllib,@INC]); } #-> sub CPAN::Module::file_in_path ; sub _file_in_path { my($self,$path) = @_; my($dir,@packpath); @packpath = split /::/, $self->{ID}; $packpath[-1] .= ".pm"; if (@packpath == 1 && $packpath[0] eq "readline.pm") { unshift @packpath, "Term", "ReadLine"; # historical reasons } foreach $dir (@$path) { my $pmfile = File::Spec->catfile($dir,@packpath); if (-f $pmfile) { return $pmfile; } } return; } #-> sub CPAN::Module::xs_file ; sub xs_file { my($self) = @_; my($dir,@packpath); @packpath = split /::/, $self->{ID}; push @packpath, $packpath[-1]; $packpath[-1] .= "." . $Config::Config{'dlext'}; foreach $dir (@INC) { my $xsfile = File::Spec->catfile($dir,'auto',@packpath); if (-f $xsfile) { return $xsfile; } } return; } #-> sub CPAN::Module::inst_version ; sub inst_version { my($self) = @_; my $parsefile = $self->inst_file or return; my $have = $self->parse_version($parsefile); $have; } #-> sub CPAN::Module::inst_version ; sub available_version { my($self) = @_; my $parsefile = $self->available_file or return; my $have = $self->parse_version($parsefile); $have; } #-> sub CPAN::Module::parse_version ; sub parse_version { my($self,$parsefile) = @_; if (ALARM_IMPLEMENTED) { my $timeout = (exists($CPAN::Config{'version_timeout'})) ? $CPAN::Config{'version_timeout'} : 15; alarm($timeout); } my $have = eval { local $SIG{ALRM} = sub { die "alarm\n" }; MM->parse_version($parsefile); }; if ($@) { $CPAN::Frontend->mywarn("Error while parsing version number in file '$parsefile'\n"); } alarm(0) if ALARM_IMPLEMENTED; my $leastsanity = eval { defined $have && length $have; }; $have = "undef" unless $leastsanity; $have =~ s/^ //; # since the %vd hack these two lines here are needed $have =~ s/ $//; # trailing whitespace happens all the time $have = CPAN::Version->readable($have); $have =~ s/\s*//g; # stringify to float around floating point issues $have; # no stringify needed, \s* above matches always } #-> sub CPAN::Module::reports sub reports { my($self) = @_; $self->distribution->reports; } 1; PK�������!�C �� ����perl5/CPAN/Plugin.pmnu�6$��������package CPAN::Plugin; use strict; use warnings; our $VERSION = '0.97'; require CPAN; ###################################################################### sub new { # ; my ($class, %params) = @_; my $self = +{ (ref $class ? (%$class) : ()), %params, }; $self = bless $self, ref $class ? ref $class : $class; unless (ref $class) { local $_; no warnings 'once'; $CPAN::META->use_inst ($_) for $self->plugin_requires; } $self; } ###################################################################### sub plugin_requires { # ; } ###################################################################### sub distribution_object { # ; my ($self) = @_; $self->{distribution_object}; } ###################################################################### sub distribution { # ; my ($self) = @_; my $distribution = $self->distribution_object->id; CPAN::Shell->expand("Distribution",$distribution) or $self->frontend->mydie("Unknowns distribution '$distribution'\n"); } ###################################################################### sub distribution_info { # ; my ($self) = @_; CPAN::DistnameInfo->new ($self->distribution->id); } ###################################################################### sub build_dir { # ; my ($self) = @_; my $build_dir = $self->distribution->{build_dir} or $self->frontend->mydie("Distribution has not been built yet, cannot proceed"); } ###################################################################### sub is_xs { # my ($self) = @_; my @xs = glob File::Spec->catfile ($self->build_dir, '*.xs'); # quick try unless (@xs) { require ExtUtils::Manifest; my $manifest_file = File::Spec->catfile ($self->build_dir, "MANIFEST"); my $manifest = ExtUtils::Manifest::maniread($manifest_file); @xs = grep /\.xs$/, keys %$manifest; } scalar @xs; } ###################################################################### package CPAN::Plugin; 1; __END__ =pod =head1 NAME CPAN::Plugin - Base class for CPAN shell extensions =head1 SYNOPSIS package CPAN::Plugin::Flurb; use parent 'CPAN::Plugin'; sub post_test { my ($self, $distribution_object) = @_; $self = $self->new (distribution_object => $distribution_object); ...; } =head1 DESCRIPTION =head2 Alpha Status The plugin system in the CPAN shell was introduced in version 2.07 and is still considered experimental. =head2 How Plugins work? See L<CPAN/"Plugin support">. =head1 METHODS =head2 plugin_requires returns list of packages given plugin requires for functionality. This list is evaluated using C<< CPAN->use_inst >> method. =head2 distribution_object Get current distribution object. =head2 distribution =head2 distribution_info =head2 build_dir Simple delegatees for misc parameters derived from distribution =head2 is_xs Predicate to detect whether package contains XS. =head1 AUTHOR Branislav Zahradnik <barney@cpan.org> =cut PK�������!�iۨD������perl5/CPAN/Distrostatus.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Distrostatus; use overload '""' => "as_string", fallback => 1; use vars qw($something_has_failed_at); use vars qw( $VERSION ); $VERSION = "5.5"; sub new { my($class,$arg) = @_; my $failed = substr($arg,0,2) eq "NO"; if ($failed) { $something_has_failed_at = $CPAN::CurrentCommandId; } bless { TEXT => $arg, FAILED => $failed, COMMANDID => $CPAN::CurrentCommandId, TIME => time, }, $class; } sub something_has_just_failed () { defined $something_has_failed_at && $something_has_failed_at == $CPAN::CurrentCommandId; } sub commandid { shift->{COMMANDID} } sub failed { shift->{FAILED} } sub text { my($self,$set) = @_; if (defined $set) { $self->{TEXT} = $set; } $self->{TEXT}; } sub as_string { my($self) = @_; $self->text; } 1; PK�������!�!+����perl5/CPAN/Shell.pmnu�6$��������package CPAN::Shell; use strict; # -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: use vars qw( $ADVANCED_QUERY $AUTOLOAD $COLOR_REGISTERED $Help $autoload_recursion $reload @ISA @relo $VERSION ); @relo = ( "CPAN.pm", "CPAN/Author.pm", "CPAN/CacheMgr.pm", "CPAN/Complete.pm", "CPAN/Debug.pm", "CPAN/DeferredCode.pm", "CPAN/Distribution.pm", "CPAN/Distroprefs.pm", "CPAN/Distrostatus.pm", "CPAN/Exception/RecursiveDependency.pm", "CPAN/Exception/yaml_not_installed.pm", "CPAN/FirstTime.pm", "CPAN/FTP.pm", "CPAN/FTP/netrc.pm", "CPAN/HandleConfig.pm", "CPAN/Index.pm", "CPAN/InfoObj.pm", "CPAN/Kwalify.pm", "CPAN/LWP/UserAgent.pm", "CPAN/Module.pm", "CPAN/Prompt.pm", "CPAN/Queue.pm", "CPAN/Reporter/Config.pm", "CPAN/Reporter/History.pm", "CPAN/Reporter/PrereqCheck.pm", "CPAN/Reporter.pm", "CPAN/Shell.pm", "CPAN/SQLite.pm", "CPAN/Tarzip.pm", "CPAN/Version.pm", ); $VERSION = "5.5009"; # record the initial timestamp for reload. $reload = { map {$INC{$_} ? ($_,(stat $INC{$_})[9]) : ()} @relo }; @CPAN::Shell::ISA = qw(CPAN::Debug); use Cwd qw(chdir); use Carp (); $COLOR_REGISTERED ||= 0; $Help = { '?' => \"help", '!' => "eval the rest of the line as perl", a => "whois author", autobundle => "write inventory into a bundle file", b => "info about bundle", bye => \"quit", clean => "clean up a distribution's build directory", # cvs_import d => "info about a distribution", # dump exit => \"quit", failed => "list all failed actions within current session", fforce => "redo a command from scratch", force => "redo a command", get => "download a distribution", h => \"help", help => "overview over commands; 'help ...' explains specific commands", hosts => "statistics about recently used hosts", i => "info about authors/bundles/distributions/modules", install => "install a distribution", install_tested => "install all distributions tested OK", is_tested => "list all distributions tested OK", look => "open a subshell in a distribution's directory", ls => "list distributions matching a fileglob", m => "info about a module", make => "make/build a distribution", mkmyconfig => "write current config into a CPAN/MyConfig.pm file", notest => "run a (usually install) command but leave out the test phase", o => "'o conf ...' for config stuff; 'o debug ...' for debugging", perldoc => "try to get a manpage for a module", q => \"quit", quit => "leave the cpan shell", r => "review upgradable modules", readme => "display the README of a distro with a pager", recent => "show recent uploads to the CPAN", # recompile reload => "'reload cpan' or 'reload index'", report => "test a distribution and send a test report to cpantesters", reports => "info about reported tests from cpantesters", # scripts # smoke test => "test a distribution", u => "display uninstalled modules", upgrade => "combine 'r' command with immediate installation", }; { $autoload_recursion ||= 0; #-> sub CPAN::Shell::AUTOLOAD ; sub AUTOLOAD { ## no critic $autoload_recursion++; my($l) = $AUTOLOAD; my $class = shift(@_); # warn "autoload[$l] class[$class]"; $l =~ s/.*:://; if ($CPAN::Signal) { warn "Refusing to autoload '$l' while signal pending"; $autoload_recursion--; return; } if ($autoload_recursion > 1) { my $fullcommand = join " ", map { "'$_'" } $l, @_; warn "Refusing to autoload $fullcommand in recursion\n"; $autoload_recursion--; return; } if ($l =~ /^w/) { # XXX needs to be reconsidered if ($CPAN::META->has_inst('CPAN::WAIT')) { CPAN::WAIT->$l(@_); } else { $CPAN::Frontend->mywarn(qq{ Commands starting with "w" require CPAN::WAIT to be installed. Please consider installing CPAN::WAIT to use the fulltext index. For this you just need to type install CPAN::WAIT }); } } else { $CPAN::Frontend->mywarn(qq{Unknown shell command '$l'. }. qq{Type ? for help. }); } $autoload_recursion--; } } #-> sub CPAN::Shell::h ; sub h { my($class,$about) = @_; if (defined $about) { my $help; if (exists $Help->{$about}) { if (ref $Help->{$about}) { # aliases $about = ${$Help->{$about}}; } $help = $Help->{$about}; } else { $help = "No help available"; } $CPAN::Frontend->myprint("$about\: $help\n"); } else { my $filler = " " x (80 - 28 - length($CPAN::VERSION)); $CPAN::Frontend->myprint(qq{ Display Information $filler (ver $CPAN::VERSION) command argument description a,b,d,m WORD or /REGEXP/ about authors, bundles, distributions, modules i WORD or /REGEXP/ about any of the above ls AUTHOR or GLOB about files in the author's directory (with WORD being a module, bundle or author name or a distribution name of the form AUTHOR/DISTRIBUTION) Download, Test, Make, Install... get download clean make clean make make (implies get) look open subshell in dist directory test make test (implies make) readme display these README files install make install (implies test) perldoc display POD documentation Upgrade installed modules r WORDs or /REGEXP/ or NONE report updates for some/matching/all upgrade WORDs or /REGEXP/ or NONE upgrade some/matching/all modules Pragmas force CMD try hard to do command fforce CMD try harder notest CMD skip testing Other h,? display this menu ! perl-code eval a perl command o conf [opt] set and query options q quit the cpan shell reload cpan load CPAN.pm again reload index load newer indices autobundle Snapshot recent latest CPAN uploads}); } } *help = \&h; #-> sub CPAN::Shell::a ; sub a { my($self,@arg) = @_; # authors are always UPPERCASE for (@arg) { $_ = uc $_ unless /=/; } $CPAN::Frontend->myprint($self->format_result('Author',@arg)); } #-> sub CPAN::Shell::globls ; sub globls { my($self,$s,$pragmas) = @_; # ls is really very different, but we had it once as an ordinary # command in the Shell (up to rev. 321) and we could not handle # force well then my(@accept,@preexpand); if ($s =~ /[\*\?\/]/) { if ($CPAN::META->has_inst("Text::Glob")) { if (my($au,$pathglob) = $s =~ m|(.*?)/(.*)|) { my $rau = Text::Glob::glob_to_regex(uc $au); CPAN::Shell->debug("au[$au]pathglob[$pathglob]rau[$rau]") if $CPAN::DEBUG; push @preexpand, map { $_->id . "/" . $pathglob } CPAN::Shell->expand_by_method('CPAN::Author',['id'],"/$rau/"); } else { my $rau = Text::Glob::glob_to_regex(uc $s); push @preexpand, map { $_->id } CPAN::Shell->expand_by_method('CPAN::Author', ['id'], "/$rau/"); } } else { $CPAN::Frontend->mydie("Text::Glob not installed, cannot proceed"); } } else { push @preexpand, uc $s; } for (@preexpand) { unless (/^[A-Z0-9\-]+(\/|$)/i) { $CPAN::Frontend->mywarn("ls command rejects argument $_: not an author\n"); next; } push @accept, $_; } my $silent = @accept>1; my $last_alpha = ""; my @results; for my $a (@accept) { my($author,$pathglob); if ($a =~ m|(.*?)/(.*)|) { my $a2 = $1; $pathglob = $2; $author = CPAN::Shell->expand_by_method('CPAN::Author', ['id'], $a2) or $CPAN::Frontend->mydie("No author found for $a2\n"); } else { $author = CPAN::Shell->expand_by_method('CPAN::Author', ['id'], $a) or $CPAN::Frontend->mydie("No author found for $a\n"); } if ($silent) { my $alpha = substr $author->id, 0, 1; my $ad; if ($alpha eq $last_alpha) { $ad = ""; } else { $ad = "[$alpha]"; $last_alpha = $alpha; } $CPAN::Frontend->myprint($ad); } for my $pragma (@$pragmas) { if ($author->can($pragma)) { $author->$pragma(); } } CPAN->debug("author[$author]pathglob[$pathglob]silent[$silent]") if $CPAN::DEBUG; push @results, $author->ls($pathglob,$silent); # silent if # more than one # author for my $pragma (@$pragmas) { my $unpragma = "un$pragma"; if ($author->can($unpragma)) { $author->$unpragma(); } } } @results; } #-> sub CPAN::Shell::local_bundles ; sub local_bundles { my($self,@which) = @_; my($incdir,$bdir,$dh); foreach $incdir ($CPAN::Config->{'cpan_home'},@INC) { my @bbase = "Bundle"; while (my $bbase = shift @bbase) { $bdir = File::Spec->catdir($incdir,split /::/, $bbase); CPAN->debug("bdir[$bdir]\@bbase[@bbase]") if $CPAN::DEBUG; if ($dh = DirHandle->new($bdir)) { # may fail my($entry); for $entry ($dh->read) { next if $entry =~ /^\./; next unless $entry =~ /^\w+(\.pm)?(?!\n)\Z/; if (-d File::Spec->catdir($bdir,$entry)) { push @bbase, "$bbase\::$entry"; } else { next unless $entry =~ s/\.pm(?!\n)\Z//; $CPAN::META->instance('CPAN::Bundle',"$bbase\::$entry"); } } } } } } #-> sub CPAN::Shell::b ; sub b { my($self,@which) = @_; CPAN->debug("which[@which]") if $CPAN::DEBUG; $self->local_bundles; $CPAN::Frontend->myprint($self->format_result('Bundle',@which)); } #-> sub CPAN::Shell::d ; sub d { $CPAN::Frontend->myprint(shift->format_result('Distribution',@_));} #-> sub CPAN::Shell::m ; sub m { # emacs confused here }; sub mimimimimi { # emacs in sync here my $self = shift; my @m = @_; for (@m) { if (m|(?:\w+/)*\w+\.pm$|) { # same regexp in expandany s/.pm$//; s|/|::|g; } } $CPAN::Frontend->myprint($self->format_result('Module',@m)); } #-> sub CPAN::Shell::i ; sub i { my($self) = shift; my(@args) = @_; @args = '/./' unless @args; my(@result); for my $type (qw/Bundle Distribution Module/) { push @result, $self->expand($type,@args); } # Authors are always uppercase. push @result, $self->expand("Author", map { uc $_ } @args); my $result = @result == 1 ? $result[0]->as_string : @result == 0 ? "No objects found of any type for argument @args\n" : join("", (map {$_->as_glimpse} @result), scalar @result, " items found\n", ); $CPAN::Frontend->myprint($result); } #-> sub CPAN::Shell::o ; # CPAN::Shell::o and CPAN::HandleConfig::edit are closely related. 'o # conf' calls through to CPAN::HandleConfig::edit. 'o conf' should # probably have been called 'set' and 'o debug' maybe 'set debug' or # 'debug'; 'o conf ARGS' calls ->edit in CPAN/HandleConfig.pm sub o { my($self,$o_type,@o_what) = @_; $o_type ||= ""; CPAN->debug("o_type[$o_type] o_what[".join(" | ",@o_what)."]\n"); if ($o_type eq 'conf') { my($cfilter); ($cfilter) = $o_what[0] =~ m|^/(.*)/$| if @o_what; if (!@o_what or $cfilter) { # print all things, "o conf" $cfilter ||= ""; my $qrfilter = eval 'qr/$cfilter/'; if ($@) { $CPAN::Frontend->mydie("Cannot parse commandline: $@"); } my($k,$v); my $configpm = CPAN::HandleConfig->require_myconfig_or_config; $CPAN::Frontend->myprint("\$CPAN::Config options from $configpm\:\n"); for $k (sort keys %CPAN::HandleConfig::can) { next unless $k =~ /$qrfilter/; $v = $CPAN::HandleConfig::can{$k}; $CPAN::Frontend->myprint(sprintf " %-18s [%s]\n", $k, $v); } $CPAN::Frontend->myprint("\n"); for $k (sort keys %CPAN::HandleConfig::keys) { next unless $k =~ /$qrfilter/; CPAN::HandleConfig->prettyprint($k); } $CPAN::Frontend->myprint("\n"); } else { if (CPAN::HandleConfig->edit(@o_what)) { } else { $CPAN::Frontend->myprint(qq{Type 'o conf' to view all configuration }. qq{items\n\n}); } } } elsif ($o_type eq 'debug') { my(%valid); @o_what = () if defined $o_what[0] && $o_what[0] =~ /help/i; if (@o_what) { while (@o_what) { my($what) = shift @o_what; if ($what =~ s/^-// && exists $CPAN::DEBUG{$what}) { $CPAN::DEBUG &= $CPAN::DEBUG ^ $CPAN::DEBUG{$what}; next; } if ( exists $CPAN::DEBUG{$what} ) { $CPAN::DEBUG |= $CPAN::DEBUG{$what}; } elsif ($what =~ /^\d/) { $CPAN::DEBUG = $what; } elsif (lc $what eq 'all') { my($max) = 0; for (values %CPAN::DEBUG) { $max += $_; } $CPAN::DEBUG = $max; } else { my($known) = 0; for (keys %CPAN::DEBUG) { next unless lc($_) eq lc($what); $CPAN::DEBUG |= $CPAN::DEBUG{$_}; $known = 1; } $CPAN::Frontend->myprint("unknown argument [$what]\n") unless $known; } } } else { my $raw = "Valid options for debug are ". join(", ",sort(keys %CPAN::DEBUG), 'all'). qq{ or a number. Completion works on the options. }. qq{Case is ignored.}; require Text::Wrap; $CPAN::Frontend->myprint(Text::Wrap::fill("","",$raw)); $CPAN::Frontend->myprint("\n\n"); } if ($CPAN::DEBUG) { $CPAN::Frontend->myprint("Options set for debugging ($CPAN::DEBUG):\n"); my($k,$v); for $k (sort {$CPAN::DEBUG{$a} <=> $CPAN::DEBUG{$b}} keys %CPAN::DEBUG) { $v = $CPAN::DEBUG{$k}; $CPAN::Frontend->myprint(sprintf " %-14s(%s)\n", $k, $v) if $v & $CPAN::DEBUG; } } else { $CPAN::Frontend->myprint("Debugging turned off completely.\n"); } } else { $CPAN::Frontend->myprint(qq{ Known options: conf set or get configuration variables debug set or get debugging options }); } } # CPAN::Shell::paintdots_onreload sub paintdots_onreload { my($ref) = shift; sub { if ( $_[0] =~ /[Ss]ubroutine ([\w:]+) redefined/ ) { my($subr) = $1; ++$$ref; local($|) = 1; # $CPAN::Frontend->myprint(".($subr)"); $CPAN::Frontend->myprint("."); if ($subr =~ /\bshell\b/i) { # warn "debug[$_[0]]"; # It would be nice if we could detect that a # subroutine has actually changed, but for now we # practically always set the GOTOSHELL global $CPAN::GOTOSHELL=1; } return; } warn @_; }; } #-> sub CPAN::Shell::hosts ; sub hosts { my($self) = @_; my $fullstats = CPAN::FTP->_ftp_statistics(); my $history = $fullstats->{history} || []; my %S; # statistics while (my $last = pop @$history) { my $attempts = $last->{attempts} or next; my $start; if (@$attempts) { $start = $attempts->[-1]{start}; if ($#$attempts > 0) { for my $i (0..$#$attempts-1) { my $url = $attempts->[$i]{url} or next; $S{no}{$url}++; } } } else { $start = $last->{start}; } next unless $last->{thesiteurl}; # C-C? bad filenames? $S{start} = $start; $S{end} ||= $last->{end}; my $dltime = $last->{end} - $start; my $dlsize = $last->{filesize} || 0; my $url = ref $last->{thesiteurl} ? $last->{thesiteurl}->text : $last->{thesiteurl}; my $s = $S{ok}{$url} ||= {}; $s->{n}++; $s->{dlsize} ||= 0; $s->{dlsize} += $dlsize/1024; $s->{dltime} ||= 0; $s->{dltime} += $dltime; } my $res; for my $url (sort keys %{$S{ok}}) { next if $S{ok}{$url}{dltime} == 0; # div by zero push @{$res->{ok}}, [@{$S{ok}{$url}}{qw(n dlsize dltime)}, $S{ok}{$url}{dlsize}/$S{ok}{$url}{dltime}, $url, ]; } for my $url (sort keys %{$S{no}}) { push @{$res->{no}}, [$S{no}{$url}, $url, ]; } my $R = ""; # report if ($S{start} && $S{end}) { $R .= sprintf "Log starts: %s\n", $S{start} ? scalar(localtime $S{start}) : "unknown"; $R .= sprintf "Log ends : %s\n", $S{end} ? scalar(localtime $S{end}) : "unknown"; } if ($res->{ok} && @{$res->{ok}}) { $R .= sprintf "\nSuccessful downloads: N kB secs kB/s url\n"; my $i = 20; for (sort { $b->[3] <=> $a->[3] } @{$res->{ok}}) { $R .= sprintf "%4d %8d %5d %9.1f %s\n", @$_; last if --$i<=0; } } if ($res->{no} && @{$res->{no}}) { $R .= sprintf "\nUnsuccessful downloads:\n"; my $i = 20; for (sort { $b->[0] <=> $a->[0] } @{$res->{no}}) { $R .= sprintf "%4d %s\n", @$_; last if --$i<=0; } } $CPAN::Frontend->myprint($R); } # here is where 'reload cpan' is done #-> sub CPAN::Shell::reload ; sub reload { my($self,$command,@arg) = @_; $command ||= ""; $self->debug("self[$self]command[$command]arg[@arg]") if $CPAN::DEBUG; if ($command =~ /^cpan$/i) { my $redef = 0; chdir "$CPAN::iCwd" if $CPAN::iCwd; # may fail my $failed; MFILE: for my $f (@relo) { next unless exists $INC{$f}; my $p = $f; $p =~ s/\.pm$//; $p =~ s|/|::|g; $CPAN::Frontend->myprint("($p"); local($SIG{__WARN__}) = paintdots_onreload(\$redef); $self->_reload_this($f) or $failed++; my $v = eval "$p\::->VERSION"; $CPAN::Frontend->myprint("v$v)"); } $CPAN::Frontend->myprint("\n$redef subroutines redefined\n"); if ($failed) { my $errors = $failed == 1 ? "error" : "errors"; $CPAN::Frontend->mywarn("\n$failed $errors during reload. You better quit ". "this session.\n"); } } elsif ($command =~ /^index$/i) { CPAN::Index->force_reload; } else { $CPAN::Frontend->myprint(qq{cpan re-evals the CPAN modules index re-reads the index files\n}); } } # reload means only load again what we have loaded before #-> sub CPAN::Shell::_reload_this ; sub _reload_this { my($self,$f,$args) = @_; CPAN->debug("f[$f]") if $CPAN::DEBUG; return 1 unless $INC{$f}; # we never loaded this, so we do not # reload but say OK my $pwd = CPAN::anycwd(); CPAN->debug("pwd[$pwd]") if $CPAN::DEBUG; my($file); for my $inc (@INC) { $file = File::Spec->catfile($inc,split /\//, $f); last if -f $file; $file = ""; } CPAN->debug("file[$file]") if $CPAN::DEBUG; my @inc = @INC; unless ($file && -f $file) { # this thingy is not in the INC path, maybe CPAN/MyConfig.pm? $file = $INC{$f}; unless (CPAN->has_inst("File::Basename")) { @inc = File::Basename::dirname($file); } else { # do we ever need this? @inc = substr($file,0,-length($f)-1); # bring in back to me! } } CPAN->debug("file[$file]inc[@inc]") if $CPAN::DEBUG; unless (-f $file) { $CPAN::Frontend->mywarn("Found no file to reload for '$f'\n"); return; } my $mtime = (stat $file)[9]; $reload->{$f} ||= -1; my $must_reload = $mtime != $reload->{$f}; $args ||= {}; $must_reload ||= $args->{reloforce}; # o conf defaults needs this if ($must_reload) { my $fh = FileHandle->new($file) or $CPAN::Frontend->mydie("Could not open $file: $!"); my $content; { local($/); local $^W = 1; $content = <$fh>; } CPAN->debug(sprintf("reload file[%s] content[%s...]",$file,substr($content,0,128))) if $CPAN::DEBUG; my $includefile; if ($includefile = $INC{$f} and -e $includefile) { $f = $includefile; } delete $INC{$f}; local @INC = @inc; eval "require '$f'"; if ($@) { warn $@; return; } $reload->{$f} = $mtime; } else { $CPAN::Frontend->myprint("__unchanged__"); } return 1; } #-> sub CPAN::Shell::mkmyconfig ; sub mkmyconfig { my($self) = @_; if ( my $configpm = $INC{'CPAN/MyConfig.pm'} ) { $CPAN::Frontend->myprint( "CPAN::MyConfig already exists as $configpm.\n" . "Running configuration again...\n" ); require CPAN::FirstTime; CPAN::FirstTime::init($configpm); } else { # force some missing values to be filled in with defaults delete $CPAN::Config->{$_} for qw/build_dir cpan_home keep_source_where histfile/; CPAN::HandleConfig->load( make_myconfig => 1 ); } } #-> sub CPAN::Shell::_binary_extensions ; sub _binary_extensions { my($self) = shift @_; my(@result,$module,%seen,%need,$headerdone); for $module ($self->expand('Module','/./')) { my $file = $module->cpan_file; next if $file eq "N/A"; next if $file =~ /^Contact Author/; my $dist = $CPAN::META->instance('CPAN::Distribution',$file); next if $dist->isa_perl; next unless $module->xs_file; local($|) = 1; $CPAN::Frontend->myprint("."); push @result, $module; } # print join " | ", @result; $CPAN::Frontend->myprint("\n"); return @result; } #-> sub CPAN::Shell::recompile ; sub recompile { my($self) = shift @_; my($module,@module,$cpan_file,%dist); @module = $self->_binary_extensions(); for $module (@module) { # we force now and compile later, so we # don't do it twice $cpan_file = $module->cpan_file; my $pack = $CPAN::META->instance('CPAN::Distribution',$cpan_file); $pack->force; $dist{$cpan_file}++; } for $cpan_file (sort keys %dist) { $CPAN::Frontend->myprint(" CPAN: Recompiling $cpan_file\n\n"); my $pack = $CPAN::META->instance('CPAN::Distribution',$cpan_file); $pack->install; $CPAN::Signal = 0; # it's tempting to reset Signal, so we can # stop a package from recompiling, # e.g. IO-1.12 when we have perl5.003_10 } } #-> sub CPAN::Shell::scripts ; sub scripts { my($self, $arg) = @_; $CPAN::Frontend->mywarn(">>>> experimental command, currently unsupported <<<<\n\n"); for my $req (qw( HTML::LinkExtor Sort::Versions List::Util )) { unless ($CPAN::META->has_inst($req)) { $CPAN::Frontend->mywarn(" $req not available\n"); } } my $p = HTML::LinkExtor->new(); my $indexfile = "/home/ftp/pub/PAUSE/scripts/new/index.html"; unless (-f $indexfile) { $CPAN::Frontend->mydie("found no indexfile[$indexfile]\n"); } $p->parse_file($indexfile); my @hrefs; my $qrarg; if ($arg =~ s|^/(.+)/$|$1|) { $qrarg = eval 'qr/$arg/'; # hide construct from 5.004 } for my $l ($p->links) { my $tag = shift @$l; next unless $tag eq "a"; my %att = @$l; my $href = $att{href}; next unless $href =~ s|^\.\./authors/id/./../||; if ($arg) { if ($qrarg) { if ($href =~ $qrarg) { push @hrefs, $href; } } else { if ($href =~ /\Q$arg\E/) { push @hrefs, $href; } } } else { push @hrefs, $href; } } # now filter for the latest version if there is more than one of a name my %stems; for (sort @hrefs) { my $href = $_; s/-v?\d.*//; my $stem = $_; $stems{$stem} ||= []; push @{$stems{$stem}}, $href; } for (sort keys %stems) { my $highest; if (@{$stems{$_}} > 1) { $highest = List::Util::reduce { Sort::Versions::versioncmp($a,$b) > 0 ? $a : $b } @{$stems{$_}}; } else { $highest = $stems{$_}[0]; } $CPAN::Frontend->myprint("$highest\n"); } } sub _guess_manpage { my($self,$d,$contains,$dist) = @_; $dist =~ s/-/::/g; my $module; if (exists $contains->{$dist}) { $module = $dist; } elsif (1 == keys %$contains) { ($module) = keys %$contains; } my $manpage; if ($module) { my $m = $self->expand("Module",$module); $m->as_string; # called for side-effects, shame $manpage = $m->{MANPAGE}; } else { $manpage = "unknown"; } return $manpage; } #-> sub CPAN::Shell::_specfile ; sub _specfile { die "CPAN::Shell::_specfile() has been moved to CPAN::Plugin::Specfile::post_test()"; } #-> sub CPAN::Shell::report ; sub report { my($self,@args) = @_; unless ($CPAN::META->has_inst("CPAN::Reporter")) { $CPAN::Frontend->mydie("CPAN::Reporter not installed; cannot continue"); } local $CPAN::Config->{test_report} = 1; $self->force("test",@args); # force is there so that the test be # re-run (as documented) } # compare with is_tested #-> sub CPAN::Shell::install_tested sub install_tested { my($self,@some) = @_; $CPAN::Frontend->mywarn("install_tested() must not be called with arguments.\n"), return if @some; CPAN::Index->reload; for my $b (reverse $CPAN::META->_list_sorted_descending_is_tested) { my $yaml = "$b.yml"; unless (-f $yaml) { $CPAN::Frontend->mywarn("No YAML file for $b available, skipping\n"); next; } my $yaml_content = CPAN->_yaml_loadfile($yaml); my $id = $yaml_content->[0]{distribution}{ID}; unless ($id) { $CPAN::Frontend->mywarn("No ID found in '$yaml', skipping\n"); next; } my $do = CPAN::Shell->expandany($id); unless ($do) { $CPAN::Frontend->mywarn("Could not expand ID '$id', skipping\n"); next; } unless ($do->{build_dir}) { $CPAN::Frontend->mywarn("Distro '$id' has no build_dir, skipping\n"); next; } unless ($do->{build_dir} eq $b) { $CPAN::Frontend->mywarn("Distro '$id' has build_dir '$do->{build_dir}' but expected '$b', skipping\n"); next; } push @some, $do; } $CPAN::Frontend->mywarn("No tested distributions found.\n"), return unless @some; @some = grep { $_->{make_test} && ! $_->{make_test}->failed } @some; $CPAN::Frontend->mywarn("No distributions tested with this build of perl found.\n"), return unless @some; # @some = grep { not $_->uptodate } @some; # $CPAN::Frontend->mywarn("No non-uptodate distributions tested with this build of perl found.\n"), # return unless @some; CPAN->debug("some[@some]"); for my $d (@some) { my $id = $d->can("pretty_id") ? $d->pretty_id : $d->id; $CPAN::Frontend->myprint("install_tested: Running for $id\n"); $CPAN::Frontend->mysleep(1); $self->install($d); } } #-> sub CPAN::Shell::upgrade ; sub upgrade { my($self,@args) = @_; $self->install($self->r(@args)); } #-> sub CPAN::Shell::_u_r_common ; sub _u_r_common { my($self) = shift @_; my($what) = shift @_; CPAN->debug("self[$self] what[$what] args[@_]") if $CPAN::DEBUG; Carp::croak "Usage: \$obj->_u_r_common(a|r|u)" unless $what && $what =~ /^[aru]$/; my(@args) = @_; @args = '/./' unless @args; my(@result,$module,%seen,%need,$headerdone, $version_undefs,$version_zeroes, @version_undefs,@version_zeroes); $version_undefs = $version_zeroes = 0; my $sprintf = "%s%-25s%s %9s %9s %s\n"; my @expand = $self->expand('Module',@args); if ($CPAN::DEBUG) { # Looks like noise to me, was very useful for debugging # for metadata cache my $expand = scalar @expand; $CPAN::Frontend->myprint(sprintf "%d matches in the database, time[%d]\n", $expand, time); } my @sexpand; if ($] < 5.008) { # hard to believe that the more complex sorting can lead to # stack curruptions on older perl @sexpand = sort {$a->id cmp $b->id} @expand; } else { @sexpand = map { $_->[1] } sort { $b->[0] <=> $a->[0] || $a->[1]{ID} cmp $b->[1]{ID}, } map { [$_->_is_representative_module, $_ ] } @expand; } if ($CPAN::DEBUG) { $CPAN::Frontend->myprint(sprintf "sorted at time[%d]\n", time); sleep 1; } MODULE: for $module (@sexpand) { my $file = $module->cpan_file; next MODULE unless defined $file; # ?? $file =~ s!^./../!!; my($latest) = $module->cpan_version; my($inst_file) = $module->inst_file; CPAN->debug("file[$file]latest[$latest]") if $CPAN::DEBUG; my($have); return if $CPAN::Signal; my($next_MODULE); eval { # version.pm involved! if ($inst_file) { if ($what eq "a") { $have = $module->inst_version; } elsif ($what eq "r") { $have = $module->inst_version; local($^W) = 0; if ($have eq "undef") { $version_undefs++; push @version_undefs, $module->as_glimpse; } elsif (CPAN::Version->vcmp($have,0)==0) { $version_zeroes++; push @version_zeroes, $module->as_glimpse; } ++$next_MODULE unless CPAN::Version->vgt($latest, $have); # to be pedantic we should probably say: # && !($have eq "undef" && $latest ne "undef" && $latest gt ""); # to catch the case where CPAN has a version 0 and we have a version undef } elsif ($what eq "u") { ++$next_MODULE; } } else { if ($what eq "a") { ++$next_MODULE; } elsif ($what eq "r") { ++$next_MODULE; } elsif ($what eq "u") { $have = "-"; } } }; next MODULE if $next_MODULE; if ($@) { $CPAN::Frontend->mywarn (sprintf("Error while comparing cpan/installed versions of '%s': INST_FILE: %s INST_VERSION: %s %s CPAN_VERSION: %s %s ", $module->id, $inst_file || "", (defined $have ? $have : "[UNDEFINED]"), (ref $have ? ref $have : ""), $latest, (ref $latest ? ref $latest : ""), )); next MODULE; } return if $CPAN::Signal; # this is sometimes lengthy $seen{$file} ||= 0; if ($what eq "a") { push @result, sprintf "%s %s\n", $module->id, $have; } elsif ($what eq "r") { push @result, $module->id; next MODULE if $seen{$file}++; } elsif ($what eq "u") { push @result, $module->id; next MODULE if $seen{$file}++; next MODULE if $file =~ /^Contact/; } unless ($headerdone++) { $CPAN::Frontend->myprint("\n"); $CPAN::Frontend->myprint(sprintf( $sprintf, "", "Package namespace", "", "installed", "latest", "in CPAN file" )); } my $color_on = ""; my $color_off = ""; if ( $COLOR_REGISTERED && $CPAN::META->has_inst("Term::ANSIColor") && $module->description ) { $color_on = Term::ANSIColor::color("green"); $color_off = Term::ANSIColor::color("reset"); } $CPAN::Frontend->myprint(sprintf $sprintf, $color_on, $module->id, $color_off, $have, $latest, $file); $need{$module->id}++; } unless (%need) { if (!@expand || $what eq "u") { $CPAN::Frontend->myprint("No modules found for @args\n"); } elsif ($what eq "r") { $CPAN::Frontend->myprint("All modules are up to date for @args\n"); } } if ($what eq "r") { if ($version_zeroes) { my $s_has = $version_zeroes > 1 ? "s have" : " has"; $CPAN::Frontend->myprint(qq{$version_zeroes installed module$s_has }. qq{a version number of 0\n}); if ($CPAN::Config->{show_zero_versions}) { local $" = "\t"; $CPAN::Frontend->myprint(qq{ they are\n\t@version_zeroes\n}); $CPAN::Frontend->myprint(qq{(use 'o conf show_zero_versions 0' }. qq{to hide them)\n}); } else { $CPAN::Frontend->myprint(qq{(use 'o conf show_zero_versions 1' }. qq{to show them)\n}); } } if ($version_undefs) { my $s_has = $version_undefs > 1 ? "s have" : " has"; $CPAN::Frontend->myprint(qq{$version_undefs installed module$s_has no }. qq{parsable version number\n}); if ($CPAN::Config->{show_unparsable_versions}) { local $" = "\t"; $CPAN::Frontend->myprint(qq{ they are\n\t@version_undefs\n}); $CPAN::Frontend->myprint(qq{(use 'o conf show_unparsable_versions 0' }. qq{to hide them)\n}); } else { $CPAN::Frontend->myprint(qq{(use 'o conf show_unparsable_versions 1' }. qq{to show them)\n}); } } } @result; } #-> sub CPAN::Shell::r ; sub r { shift->_u_r_common("r",@_); } #-> sub CPAN::Shell::u ; sub u { shift->_u_r_common("u",@_); } #-> sub CPAN::Shell::failed ; sub failed { my($self,$only_id,$silent) = @_; my @failed = $self->find_failed($only_id); my $scope; if ($only_id) { $scope = "this command"; } elsif ($CPAN::Index::HAVE_REANIMATED) { $scope = "this or a previous session"; # it might be nice to have a section for previous session and # a second for this } else { $scope = "this session"; } if (@failed) { my $print; my $debug = 0; if ($debug) { $print = join "", map { sprintf "%5d %-45s: %s %s\n", @$_ } sort { $a->[0] <=> $b->[0] } @failed; } else { $print = join "", map { sprintf " %-45s: %s %s\n", @$_[1..3] } sort { $a->[0] <=> $b->[0] || $a->[4] <=> $b->[4] } @failed; } $CPAN::Frontend->myprint("Failed during $scope:\n$print"); } elsif (!$only_id || !$silent) { $CPAN::Frontend->myprint("Nothing failed in $scope\n"); } } sub find_failed { my($self,$only_id) = @_; my @failed; DIST: for my $d (sort { $a->id cmp $b->id } $CPAN::META->all_objects("CPAN::Distribution")) { my $failed = ""; NAY: for my $nosayer ( # order matters! "unwrapped", "writemakefile", "signature_verify", "make", "make_test", "install", "make_clean", ) { next unless exists $d->{$nosayer}; next unless defined $d->{$nosayer}; next unless ( UNIVERSAL::can($d->{$nosayer},"failed") ? $d->{$nosayer}->failed : $d->{$nosayer} =~ /^NO/ ); next NAY if $only_id && $only_id != ( UNIVERSAL::can($d->{$nosayer},"commandid") ? $d->{$nosayer}->commandid : $CPAN::CurrentCommandId ); $failed = $nosayer; last; } next DIST unless $failed; my $id = $d->id; $id =~ s|^./../||; ### XXX need to flag optional modules as '(optional)' if they are # from recommends/suggests -- i.e. *show* failure, but make it clear # it was failure of optional module -- xdg, 2012-04-01 $id = "(optional) $id" if ! $d->{mandatory}; #$print .= sprintf( # " %-45s: %s %s\n", push @failed, ( UNIVERSAL::can($d->{$failed},"failed") ? [ $d->{$failed}->commandid, $id, $failed, $d->{$failed}->text, $d->{$failed}{TIME}||0, !! $d->{mandatory}, ] : [ 1, $id, $failed, $d->{$failed}, 0, !! $d->{mandatory}, ] ); } return @failed; } sub mandatory_dist_failed { my ($self) = @_; return grep { $_->[5] } $self->find_failed($CPAN::CurrentCommandID); } # XXX intentionally undocumented because completely bogus, unportable, # useless, etc. #-> sub CPAN::Shell::status ; sub status { my($self) = @_; require Devel::Size; my $ps = FileHandle->new; open $ps, "/proc/$$/status"; my $vm = 0; while (<$ps>) { next unless /VmSize:\s+(\d+)/; $vm = $1; last; } $CPAN::Frontend->mywarn(sprintf( "%-27s %6d\n%-27s %6d\n", "vm", $vm, "CPAN::META", Devel::Size::total_size($CPAN::META)/1024, )); for my $k (sort keys %$CPAN::META) { next unless substr($k,0,4) eq "read"; warn sprintf " %-26s %6d\n", $k, Devel::Size::total_size($CPAN::META->{$k})/1024; for my $k2 (sort keys %{$CPAN::META->{$k}}) { warn sprintf " %-25s %6d (keys: %6d)\n", $k2, Devel::Size::total_size($CPAN::META->{$k}{$k2})/1024, scalar keys %{$CPAN::META->{$k}{$k2}}; } } } # compare with install_tested #-> sub CPAN::Shell::is_tested sub is_tested { my($self) = @_; CPAN::Index->reload; for my $b (reverse $CPAN::META->_list_sorted_descending_is_tested) { my $time; if ($CPAN::META->{is_tested}{$b}) { $time = scalar(localtime $CPAN::META->{is_tested}{$b}); } else { $time = scalar localtime; $time =~ s/\S/?/g; } $CPAN::Frontend->myprint(sprintf "%s %s\n", $time, $b); } } #-> sub CPAN::Shell::autobundle ; sub autobundle { my($self) = shift; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; my(@bundle) = $self->_u_r_common("a",@_); my($todir) = File::Spec->catdir($CPAN::Config->{'cpan_home'},"Bundle"); File::Path::mkpath($todir); unless (-d $todir) { $CPAN::Frontend->myprint("Couldn't mkdir $todir for some reason\n"); return; } my($y,$m,$d) = (localtime)[5,4,3]; $y+=1900; $m++; my($c) = 0; my($me) = sprintf "Snapshot_%04d_%02d_%02d_%02d", $y, $m, $d, $c; my($to) = File::Spec->catfile($todir,"$me.pm"); while (-f $to) { $me = sprintf "Snapshot_%04d_%02d_%02d_%02d", $y, $m, $d, ++$c; $to = File::Spec->catfile($todir,"$me.pm"); } my($fh) = FileHandle->new(">$to") or Carp::croak "Can't open >$to: $!"; $fh->print( "package Bundle::$me;\n\n", "\$","VERSION = '0.01';\n\n", # hide from perl-reversion "1;\n\n", "__END__\n\n", "=head1 NAME\n\n", "Bundle::$me - Snapshot of installation on ", $Config::Config{'myhostname'}, " on ", scalar(localtime), "\n\n=head1 SYNOPSIS\n\n", "perl -MCPAN -e 'install Bundle::$me'\n\n", "=head1 CONTENTS\n\n", join("\n", @bundle), "\n\n=head1 CONFIGURATION\n\n", Config->myconfig, "\n\n=head1 AUTHOR\n\n", "This Bundle has been generated automatically ", "by the autobundle routine in CPAN.pm.\n", ); $fh->close; $CPAN::Frontend->myprint("\nWrote bundle file $to\n\n"); return $to; } #-> sub CPAN::Shell::expandany ; sub expandany { my($self,$s) = @_; CPAN->debug("s[$s]") if $CPAN::DEBUG; my $module_as_path = ""; if ($s =~ m|(?:\w+/)*\w+\.pm$|) { # same regexp in sub m $module_as_path = $s; $module_as_path =~ s/.pm$//; $module_as_path =~ s|/|::|g; } if ($module_as_path) { if ($module_as_path =~ m|^Bundle::|) { $self->local_bundles; return $self->expand('Bundle',$module_as_path); } else { return $self->expand('Module',$module_as_path) if $CPAN::META->exists('CPAN::Module',$module_as_path); } } elsif ($s =~ m|/| or substr($s,-1,1) eq ".") { # looks like a file or a directory $s = CPAN::Distribution->normalize($s); return $CPAN::META->instance('CPAN::Distribution',$s); # Distributions spring into existence, not expand } elsif ($s =~ m|^Bundle::|) { $self->local_bundles; # scanning so late for bundles seems # both attractive and crumpy: always # current state but easy to forget # somewhere return $self->expand('Bundle',$s); } else { return $self->expand('Module',$s) if $CPAN::META->exists('CPAN::Module',$s); } return; } #-> sub CPAN::Shell::expand ; sub expand { my $self = shift; my($type,@args) = @_; CPAN->debug("type[$type]args[@args]") if $CPAN::DEBUG; my $class = "CPAN::$type"; my $methods = ['id']; for my $meth (qw(name)) { next unless $class->can($meth); push @$methods, $meth; } $self->expand_by_method($class,$methods,@args); } #-> sub CPAN::Shell::expand_by_method ; sub expand_by_method { my $self = shift; my($class,$methods,@args) = @_; my($arg,@m); for $arg (@args) { my($regex,$command); if ($arg =~ m|^/(.*)/$|) { $regex = $1; # FIXME: there seem to be some ='s in the author data, which trigger # a failure here. This needs to be contemplated. # } elsif ($arg =~ m/=/) { # $command = 1; } my $obj; CPAN->debug(sprintf "class[%s]regex[%s]command[%s]", $class, defined $regex ? $regex : "UNDEFINED", defined $command ? $command : "UNDEFINED", ) if $CPAN::DEBUG; if (defined $regex) { if (CPAN::_sqlite_running()) { CPAN::Index->reload; $CPAN::SQLite->search($class, $regex); } for $obj ( $CPAN::META->all_objects($class) ) { unless ($obj && UNIVERSAL::can($obj,"id") && $obj->id) { # BUG, we got an empty object somewhere require Data::Dumper; CPAN->debug(sprintf( "Bug in CPAN: Empty id on obj[%s][%s]", $obj, Data::Dumper::Dumper($obj) )) if $CPAN::DEBUG; next; } for my $method (@$methods) { my $match = eval {$obj->$method() =~ /$regex/i}; if ($@) { my($err) = $@ =~ /^(.+) at .+? line \d+\.$/; $err ||= $@; # if we were too restrictive above $CPAN::Frontend->mydie("$err\n"); } elsif ($match) { push @m, $obj; last; } } } } elsif ($command) { die "equal sign in command disabled (immature interface), ". "you can set ! \$CPAN::Shell::ADVANCED_QUERY=1 to enable it. But please note, this is HIGHLY EXPERIMENTAL code that may go away anytime.\n" unless $ADVANCED_QUERY; my($method,$criterion) = $arg =~ /(.+?)=(.+)/; my($matchcrit) = $criterion =~ m/^~(.+)/; for my $self ( sort {$a->id cmp $b->id} $CPAN::META->all_objects($class) ) { my $lhs = $self->$method() or next; # () for 5.00503 if ($matchcrit) { push @m, $self if $lhs =~ m/$matchcrit/; } else { push @m, $self if $lhs eq $criterion; } } } else { my($xarg) = $arg; if ( $class eq 'CPAN::Bundle' ) { $xarg =~ s/^(Bundle::)?(.*)/Bundle::$2/; } elsif ($class eq "CPAN::Distribution") { $xarg = CPAN::Distribution->normalize($arg); } else { $xarg =~ s/:+/::/g; } if ($CPAN::META->exists($class,$xarg)) { $obj = $CPAN::META->instance($class,$xarg); } elsif ($CPAN::META->exists($class,$arg)) { $obj = $CPAN::META->instance($class,$arg); } else { next; } push @m, $obj; } } @m = sort {$a->id cmp $b->id} @m; if ( $CPAN::DEBUG ) { my $wantarray = wantarray; my $join_m = join ",", map {$_->id} @m; # $self->debug("wantarray[$wantarray]join_m[$join_m]"); my $count = scalar @m; $self->debug("class[$class]wantarray[$wantarray]count m[$count]"); } return wantarray ? @m : $m[0]; } #-> sub CPAN::Shell::format_result ; sub format_result { my($self) = shift; my($type,@args) = @_; @args = '/./' unless @args; my(@result) = $self->expand($type,@args); my $result = @result == 1 ? $result[0]->as_string : @result == 0 ? "No objects of type $type found for argument @args\n" : join("", (map {$_->as_glimpse} @result), scalar @result, " items found\n", ); $result; } #-> sub CPAN::Shell::report_fh ; { my $installation_report_fh; my $previously_noticed = 0; sub report_fh { return $installation_report_fh if $installation_report_fh; if ($CPAN::META->has_usable("File::Temp")) { $installation_report_fh = File::Temp->new( dir => File::Spec->tmpdir, template => 'cpan_install_XXXX', suffix => '.txt', unlink => 0, ); } unless ( $installation_report_fh ) { warn("Couldn't open installation report file; " . "no report file will be generated." ) unless $previously_noticed++; } } } # The only reason for this method is currently to have a reliable # debugging utility that reveals which output is going through which # channel. No, I don't like the colors ;-) # to turn colordebugging on, write # cpan> o conf colorize_output 1 #-> sub CPAN::Shell::colorize_output ; { my $print_ornamented_have_warned = 0; sub colorize_output { my $colorize_output = $CPAN::Config->{colorize_output}; if ($colorize_output && $^O eq 'MSWin32' && !$CPAN::META->has_inst("Win32::Console::ANSI")) { unless ($print_ornamented_have_warned++) { # no myprint/mywarn within myprint/mywarn! warn "Colorize_output is set to true but Win32::Console::ANSI is not installed. To activate colorized output, please install Win32::Console::ANSI.\n\n"; } $colorize_output = 0; } if ($colorize_output && !$CPAN::META->has_inst("Term::ANSIColor")) { unless ($print_ornamented_have_warned++) { # no myprint/mywarn within myprint/mywarn! warn "Colorize_output is set to true but Term::ANSIColor is not installed. To activate colorized output, please install Term::ANSIColor.\n\n"; } $colorize_output = 0; } return $colorize_output; } } #-> sub CPAN::Shell::print_ornamented ; sub print_ornamented { my($self,$what,$ornament) = @_; return unless defined $what; local $| = 1; # Flush immediately if ( $CPAN::Be_Silent ) { # WARNING: variable Be_Silent is poisoned and must be eliminated. print {report_fh()} $what; return; } my $swhat = "$what"; # stringify if it is an object if ($CPAN::Config->{term_is_latin}) { # note: deprecated, need to switch to $LANG and $LC_* # courtesy jhi: $swhat =~ s{([\xC0-\xDF])([\x80-\xBF])}{chr(ord($1)<<6&0xC0|ord($2)&0x3F)}eg; #}; } if ($self->colorize_output) { if ( $CPAN::DEBUG && $swhat =~ /^Debug\(/ ) { # if you want to have this configurable, please file a bug report $ornament = $CPAN::Config->{colorize_debug} || "black on_cyan"; } my $color_on = eval { Term::ANSIColor::color($ornament) } || ""; if ($@) { print "Term::ANSIColor rejects color[$ornament]: $@\n Please choose a different color (Hint: try 'o conf init /color/')\n"; } # GGOLDBACH/Test-GreaterVersion-0.008 broke without this # $trailer construct. We want the newline be the last thing if # there is a newline at the end ensuring that the next line is # empty for other players my $trailer = ""; $trailer = $1 if $swhat =~ s/([\r\n]+)\z//; print $color_on, $swhat, Term::ANSIColor::color("reset"), $trailer; } else { print $swhat; } } #-> sub CPAN::Shell::myprint ; # where is myprint/mywarn/Frontend/etc. documented? Where to use what? # I think, we send everything to STDOUT and use print for normal/good # news and warn for news that need more attention. Yes, this is our # working contract for now. sub myprint { my($self,$what) = @_; $self->print_ornamented($what, $CPAN::Config->{colorize_print}||'bold blue on_white', ); } my %already_printed; #-> sub CPAN::Shell::mywarnonce ; sub myprintonce { my($self,$what) = @_; $self->myprint($what) unless $already_printed{$what}++; } sub optprint { my($self,$category,$what) = @_; my $vname = $category . "_verbosity"; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; if (!$CPAN::Config->{$vname} || $CPAN::Config->{$vname} =~ /^v/ ) { $CPAN::Frontend->myprint($what); } } #-> sub CPAN::Shell::myexit ; sub myexit { my($self,$what) = @_; $self->myprint($what); exit; } #-> sub CPAN::Shell::mywarn ; sub mywarn { my($self,$what) = @_; $self->print_ornamented($what, $CPAN::Config->{colorize_warn}||'bold red on_white'); } my %already_warned; #-> sub CPAN::Shell::mywarnonce ; sub mywarnonce { my($self,$what) = @_; $self->mywarn($what) unless $already_warned{$what}++; } # only to be used for shell commands #-> sub CPAN::Shell::mydie ; sub mydie { my($self,$what) = @_; $self->mywarn($what); # If it is the shell, we want the following die to be silent, # but if it is not the shell, we would need a 'die $what'. We need # to take care that only shell commands use mydie. Is this # possible? die "\n"; } # sub CPAN::Shell::colorable_makemaker_prompt ; sub colorable_makemaker_prompt { my($foo,$bar,$ornament) = @_; $ornament ||= "colorize_print"; if (CPAN::Shell->colorize_output) { my $ornament = $CPAN::Config->{$ornament}||'bold blue on_white'; my $color_on = eval { Term::ANSIColor::color($ornament); } || ""; print $color_on; } my $ans = ExtUtils::MakeMaker::prompt($foo,$bar); if (CPAN::Shell->colorize_output) { print Term::ANSIColor::color('reset'); } return $ans; } # use this only for unrecoverable errors! #-> sub CPAN::Shell::unrecoverable_error ; sub unrecoverable_error { my($self,$what) = @_; my @lines = split /\n/, $what; my $longest = 0; for my $l (@lines) { $longest = length $l if length $l > $longest; } $longest = 62 if $longest > 62; for my $l (@lines) { if ($l =~ /^\s*$/) { $l = "\n"; next; } $l = "==> $l"; if (length $l < 66) { $l = pack "A66 A*", $l, "<=="; } $l .= "\n"; } unshift @lines, "\n"; $self->mydie(join "", @lines); } #-> sub CPAN::Shell::mysleep ; sub mysleep { return if $ENV{AUTOMATED_TESTING} || ! -t STDOUT; my($self, $sleep) = @_; if (CPAN->has_inst("Time::HiRes")) { Time::HiRes::sleep($sleep); } else { sleep($sleep < 1 ? 1 : int($sleep + 0.5)); } } #-> sub CPAN::Shell::setup_output ; sub setup_output { return if -t STDOUT; my $odef = select STDERR; $| = 1; select STDOUT; $| = 1; select $odef; } #-> sub CPAN::Shell::rematein ; # RE-adme||MA-ke||TE-st||IN-stall : nearly everything runs through here sub rematein { my $self = shift; # this variable was global and disturbed programmers, so localize: local $CPAN::Distrostatus::something_has_failed_at; my($meth,@some) = @_; my @pragma; while($meth =~ /^(ff?orce|notest)$/) { push @pragma, $meth; $meth = shift @some or $CPAN::Frontend->mydie("Pragma $pragma[-1] used without method: ". "cannot continue"); } setup_output(); CPAN->debug("pragma[@pragma]meth[$meth]some[@some]") if $CPAN::DEBUG; # Here is the place to set "test_count" on all involved parties to # 0. We then can pass this counter on to the involved # distributions and those can refuse to test if test_count > X. In # the first stab at it we could use a 1 for "X". # But when do I reset the distributions to start with 0 again? # Jost suggested to have a random or cycling interaction ID that # we pass through. But the ID is something that is just left lying # around in addition to the counter, so I'd prefer to set the # counter to 0 now, and repeat at the end of the loop. But what # about dependencies? They appear later and are not reset, they # enter the queue but not its copy. How do they get a sensible # test_count? # With configure_requires, "get" is vulnerable in recursion. my $needs_recursion_protection = "get|make|test|install"; # construct the queue my($s,@s,@qcopy); STHING: foreach $s (@some) { my $obj; if (ref $s) { CPAN->debug("s is an object[$s]") if $CPAN::DEBUG; $obj = $s; } elsif ($s =~ m|[\$\@\%]|) { # looks like a perl variable } elsif ($s =~ m|^/|) { # looks like a regexp if (substr($s,-1,1) eq ".") { $obj = CPAN::Shell->expandany($s); } else { my @obj; CLASS: for my $class (qw(Distribution Bundle Module)) { if (@obj = $self->expand($class,$s)) { last CLASS; } } if (@obj) { if (1==@obj) { $obj = $obj[0]; } else { $CPAN::Frontend->mywarn("Sorry, $meth with a regular expression is ". "only supported when unambiguous.\nRejecting argument '$s'\n"); $CPAN::Frontend->mysleep(2); next STHING; } } } } elsif ($meth eq "ls") { $self->globls($s,\@pragma); next STHING; } else { CPAN->debug("calling expandany [$s]") if $CPAN::DEBUG; $obj = CPAN::Shell->expandany($s); } if (0) { } elsif (ref $obj) { if ($meth =~ /^($needs_recursion_protection)$/) { # it would be silly to check for recursion for look or dump # (we are in CPAN::Shell::rematein) CPAN->debug("Testing against recursion") if $CPAN::DEBUG; eval { $obj->color_cmd_tmps(0,1); }; if ($@) { if (ref $@ and $@->isa("CPAN::Exception::RecursiveDependency")) { $CPAN::Frontend->mywarn($@); } else { if (0) { require Carp; Carp::confess(sprintf "DEBUG: \$\@[%s]ref[%s]", $@, ref $@); } die; } } } CPAN::Queue->queue_item(qmod => $obj->id, reqtype => "c", optional => ''); push @qcopy, $obj; } elsif ($CPAN::META->exists('CPAN::Author',uc($s))) { $obj = $CPAN::META->instance('CPAN::Author',uc($s)); if ($meth =~ /^(dump|ls|reports)$/) { $obj->$meth(); } else { $CPAN::Frontend->mywarn( join "", "Don't be silly, you can't $meth ", $obj->fullname, " ;-)\n" ); $CPAN::Frontend->mysleep(2); } } elsif ($s =~ m|[\$\@\%]| && $meth eq "dump") { CPAN::InfoObj->dump($s); } else { $CPAN::Frontend ->mywarn(qq{Warning: Cannot $meth $s, }. qq{don't know what it is. Try the command i /$s/ to find objects with matching identifiers. }); $CPAN::Frontend->mysleep(2); } } # queuerunner (please be warned: when I started to change the # queue to hold objects instead of names, I made one or two # mistakes and never found which. I reverted back instead) QITEM: while (my $q = CPAN::Queue->first) { my $obj; my $s = $q->as_string; my $reqtype = $q->reqtype || ""; my $optional = $q->optional || ""; $obj = CPAN::Shell->expandany($s); unless ($obj) { # don't know how this can happen, maybe we should panic, # but maybe we get a solution from the first user who hits # this unfortunate exception? $CPAN::Frontend->mywarn("Warning: Could not expand string '$s' ". "to an object. Skipping.\n"); $CPAN::Frontend->mysleep(5); CPAN::Queue->delete_first($s); next QITEM; } $obj->{reqtype} ||= ""; my $type = ref $obj; if ( $type eq 'CPAN::Distribution' || $type eq 'CPAN::Bundle' ) { $obj->{mandatory} ||= ! $optional; # once mandatory, always mandatory } elsif ( $type eq 'CPAN::Module' ) { $obj->{mandatory} ||= ! $optional; # once mandatory, always mandatory if (my $d = $obj->distribution) { $d->{mandatory} ||= ! $optional; # once mandatory, always mandatory } elsif ($optional) { # the queue object does not know who was recommending/suggesting us:( # So we only vaguely write "optional". $CPAN::Frontend->mywarn("Warning: optional module '$s' ". "not known. Skipping.\n"); CPAN::Queue->delete_first($s); next QITEM; } } { # force debugging because CPAN::SQLite somehow delivers us # an empty object; # local $CPAN::DEBUG = 1024; # Shell; probably fixed now CPAN->debug("s[$s]obj-reqtype[$obj->{reqtype}]". "q-reqtype[$reqtype]") if $CPAN::DEBUG; } if ($obj->{reqtype}) { if ($obj->{reqtype} eq "b" && $reqtype =~ /^[rc]$/) { $obj->{reqtype} = $reqtype; if ( exists $obj->{install} && ( UNIVERSAL::can($obj->{install},"failed") ? $obj->{install}->failed : $obj->{install} =~ /^NO/ ) ) { delete $obj->{install}; $CPAN::Frontend->mywarn ("Promoting $obj->{ID} from 'build_requires' to 'requires'"); } } } else { $obj->{reqtype} = $reqtype; } for my $pragma (@pragma) { if ($pragma && $obj->can($pragma)) { $obj->$pragma($meth); } } if (UNIVERSAL::can($obj, 'called_for')) { $obj->called_for($s) unless $obj->called_for; } CPAN->debug(qq{pragma[@pragma]meth[$meth]}. qq{ID[$obj->{ID}]}) if $CPAN::DEBUG; push @qcopy, $obj; if ($meth =~ /^(report)$/) { # they came here with a pragma? $self->$meth($obj); } elsif (! UNIVERSAL::can($obj,$meth)) { # Must never happen my $serialized = ""; if (0) { } elsif ($CPAN::META->has_inst("YAML::Syck")) { $serialized = YAML::Syck::Dump($obj); } elsif ($CPAN::META->has_inst("YAML")) { $serialized = YAML::Dump($obj); } elsif ($CPAN::META->has_inst("Data::Dumper")) { $serialized = Data::Dumper::Dumper($obj); } else { require overload; $serialized = overload::StrVal($obj); } CPAN->debug("Going to panic. meth[$meth]s[$s]") if $CPAN::DEBUG; $CPAN::Frontend->mydie("Panic: obj[$serialized] cannot meth[$meth]"); } else { my $upgraded_meth = $meth; if ( $meth eq "make" and $obj->{reqtype} eq "b" ) { # rt 86915 $upgraded_meth = "test"; } if ($obj->$upgraded_meth()) { CPAN::Queue->delete($s); CPAN->debug("Succeeded and deleted from queue. pragma[@pragma]meth[$meth][s][$s]") if $CPAN::DEBUG; } else { CPAN->debug("Failed. pragma[@pragma]meth[$meth]s[$s]") if $CPAN::DEBUG; } } $obj->undelay; for my $pragma (@pragma) { my $unpragma = "un$pragma"; if ($obj->can($unpragma)) { $obj->$unpragma(); } } # if any failures occurred and the current object is mandatory, we # still don't know if *it* failed or if it was another (optional) # module, so we have to check that explicitly (and expensively) if ( $CPAN::Config->{halt_on_failure} && $obj->{mandatory} && CPAN::Distrostatus::something_has_just_failed() && $self->mandatory_dist_failed() ) { $CPAN::Frontend->mywarn("Stopping: '$meth' failed for '$s'.\n"); CPAN::Queue->nullify_queue; last QITEM; } CPAN::Queue->delete_first($s); } if ($meth =~ /^($needs_recursion_protection)$/) { for my $obj (@qcopy) { $obj->color_cmd_tmps(0,0); } } } #-> sub CPAN::Shell::recent ; sub recent { my($self) = @_; if ($CPAN::META->has_inst("XML::LibXML")) { my $url = $CPAN::Defaultrecent; $CPAN::Frontend->myprint("Fetching '$url'\n"); unless ($CPAN::META->has_usable("LWP")) { $CPAN::Frontend->mydie("LWP not installed; cannot continue"); } CPAN::LWP::UserAgent->config; my $Ua; eval { $Ua = CPAN::LWP::UserAgent->new; }; if ($@) { $CPAN::Frontend->mydie("CPAN::LWP::UserAgent->new dies with $@\n"); } my $resp = $Ua->get($url); unless ($resp->is_success) { $CPAN::Frontend->mydie(sprintf "Could not download '%s': %s\n", $url, $resp->code); } $CPAN::Frontend->myprint("DONE\n\n"); my $xml = XML::LibXML->new->parse_string($resp->content); if (0) { my $s = $xml->serialize(2); $s =~ s/\n\s*\n/\n/g; $CPAN::Frontend->myprint($s); return; } my @distros; if ($url =~ /winnipeg/) { my $pubdate = $xml->findvalue("/rss/channel/pubDate"); $CPAN::Frontend->myprint(" pubDate: $pubdate\n\n"); for my $eitem ($xml->findnodes("/rss/channel/item")) { my $distro = $eitem->findvalue("enclosure/\@url"); $distro =~ s|.*?/authors/id/./../||; my $size = $eitem->findvalue("enclosure/\@length"); my $desc = $eitem->findvalue("description"); $desc =~ s/.+? - //; $CPAN::Frontend->myprint("$distro [$size b]\n $desc\n"); push @distros, $distro; } } elsif ($url =~ /search.*uploads.rdf/) { # xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" # xmlns="http://purl.org/rss/1.0/" # xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" # xmlns:dc="http://purl.org/dc/elements/1.1/" # xmlns:syn="http://purl.org/rss/1.0/modules/syndication/" # xmlns:admin="http://webns.net/mvcb/" my $dc_date = $xml->findvalue("//*[local-name(.) = 'RDF']/*[local-name(.) = 'channel']/*[local-name(.) = 'date']"); $CPAN::Frontend->myprint(" dc:date: $dc_date\n\n"); my $finish_eitem = 0; local $SIG{INT} = sub { $finish_eitem = 1 }; EITEM: for my $eitem ($xml->findnodes("//*[local-name(.) = 'RDF']/*[local-name(.) = 'item']")) { my $distro = $eitem->findvalue("\@rdf:about"); $distro =~ s|.*~||; # remove up to the tilde before the name $distro =~ s|/$||; # remove trailing slash $distro =~ s|([^/]+)|\U$1\E|; # upcase the name my $author = uc $1 or die "distro[$distro] without author, cannot continue"; my $desc = $eitem->findvalue("*[local-name(.) = 'description']"); my $i = 0; SUBDIRTEST: while () { last SUBDIRTEST if ++$i >= 6; # half a dozen must do! if (my @ret = $self->globls("$distro*")) { @ret = grep {$_->[2] !~ /meta/} @ret; @ret = grep {length $_->[2]} @ret; if (@ret) { $distro = "$author/$ret[0][2]"; last SUBDIRTEST; } } $distro =~ s|/|/*/|; # allow it to reside in a subdirectory } next EITEM if $distro =~ m|\*|; # did not find the thing $CPAN::Frontend->myprint("____$desc\n"); push @distros, $distro; last EITEM if $finish_eitem; } } return \@distros; } else { # deprecated old version $CPAN::Frontend->mydie("no XML::LibXML installed, cannot continue\n"); } } #-> sub CPAN::Shell::smoke ; sub smoke { my($self) = @_; my $distros = $self->recent; DISTRO: for my $distro (@$distros) { next if $distro =~ m|/Bundle-|; # XXX crude heuristic to skip bundles $CPAN::Frontend->myprint(sprintf "Downloading and testing '$distro'\n"); { my $skip = 0; local $SIG{INT} = sub { $skip = 1 }; for (0..9) { $CPAN::Frontend->myprint(sprintf "\r%2d (Hit ^C to skip)", 10-$_); sleep 1; if ($skip) { $CPAN::Frontend->myprint(" skipped\n"); next DISTRO; } } } $CPAN::Frontend->myprint("\r \n"); # leave the dirty line with a newline $self->test($distro); } } { # set up the dispatching methods no strict "refs"; for my $command (qw( clean cvs_import dump force fforce get install look ls make notest perldoc readme reports test )) { *$command = sub { shift->rematein($command, @_); }; } } 1; PK�������!�䍽��������perl5/CPAN/DeferredCode.pmnu�6$��������package CPAN::DeferredCode; use strict; use vars qw/$VERSION/; use overload fallback => 1, map { ($_ => 'run') } qw/ bool "" 0+ /; $VERSION = "5.50"; sub run { $_[0]->(); } 1; PK�������!�B3������perl5/CPAN/Queue.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- use strict; package CPAN::Queue::Item; # CPAN::Queue::Item::new ; sub new { my($class,@attr) = @_; my $self = bless { @attr }, $class; return $self; } sub as_string { my($self) = @_; $self->{qmod}; } # r => requires, b => build_requires, c => commandline sub reqtype { my($self) = @_; $self->{reqtype}; } sub optional { my($self) = @_; $self->{optional}; } package CPAN::Queue; # One use of the queue is to determine if we should or shouldn't # announce the availability of a new CPAN module # Now we try to use it for dependency tracking. For that to happen # we need to draw a dependency tree and do the leaves first. This can # easily be reached by running CPAN.pm recursively, but we don't want # to waste memory and run into deep recursion. So what we can do is # this: # CPAN::Queue is the package where the queue is maintained. Dependencies # often have high priority and must be brought to the head of the queue, # possibly by jumping the queue if they are already there. My first code # attempt tried to be extremely correct. Whenever a module needed # immediate treatment, I either unshifted it to the front of the queue, # or, if it was already in the queue, I spliced and let it bypass the # others. This became a too correct model that made it impossible to put # an item more than once into the queue. Why would you need that? Well, # you need temporary duplicates as the manager of the queue is a loop # that # # (1) looks at the first item in the queue without shifting it off # # (2) cares for the item # # (3) removes the item from the queue, *even if its agenda failed and # even if the item isn't the first in the queue anymore* (that way # protecting against never ending queues) # # So if an item has prerequisites, the installation fails now, but we # want to retry later. That's easy if we have it twice in the queue. # # I also expect insane dependency situations where an item gets more # than two lives in the queue. Simplest example is triggered by 'install # Foo Foo Foo'. People make this kind of mistakes and I don't want to # get in the way. I wanted the queue manager to be a dumb servant, not # one that knows everything. # # Who would I tell in this model that the user wants to be asked before # processing? I can't attach that information to the module object, # because not modules are installed but distributions. So I'd have to # tell the distribution object that it should ask the user before # processing. Where would the question be triggered then? Most probably # in CPAN::Distribution::rematein. use vars qw{ @All $VERSION }; $VERSION = "5.5003"; # CPAN::Queue::queue_item ; sub queue_item { my($class,@attr) = @_; my $item = "$class\::Item"->new(@attr); $class->qpush($item); return 1; } # CPAN::Queue::qpush ; sub qpush { my($class,$obj) = @_; push @All, $obj; CPAN->debug(sprintf("in new All[%s]", join("",map {sprintf " %s\[%s][%s]\n",$_->{qmod},$_->{reqtype},$_->{optional}} @All), )) if $CPAN::DEBUG; } # CPAN::Queue::first ; sub first { my $obj = $All[0]; $obj; } # CPAN::Queue::delete_first ; sub delete_first { my($class,$what) = @_; my $i; for my $i (0..$#All) { if ( $All[$i]->{qmod} eq $what ) { splice @All, $i, 1; last; } } CPAN->debug(sprintf("after delete_first mod[%s] All[%s]", $what, join("",map {sprintf " %s\[%s][%s]\n",$_->{qmod},$_->{reqtype},$_->{optional}} @All) )) if $CPAN::DEBUG; } # CPAN::Queue::jumpqueue ; sub jumpqueue { my $class = shift; my @what = @_; CPAN->debug(sprintf("before jumpqueue All[%s] what[%s]", join("",map {sprintf " %s\[%s][%s]\n",$_->{qmod},$_->{reqtype},$_->{optional}} @All), join("",map {sprintf " %s\[%s][%s]\n",$_->{qmod},$_->{reqtype},$_->{optional}} @what), )) if $CPAN::DEBUG; unless (defined $what[0]{reqtype}) { # apparently it was not the Shell that sent us this enquiry, # treat it as commandline $what[0]{reqtype} = "c"; } my $inherit_reqtype = $what[0]{reqtype} =~ /^(c|r)$/ ? "r" : "b"; WHAT: for my $what_tuple (@what) { my($qmod,$reqtype,$optional) = @$what_tuple{qw(qmod reqtype optional)}; if ($reqtype eq "r" && $inherit_reqtype eq "b" ) { $reqtype = "b"; } my $jumped = 0; for (my $i=0; $i<$#All;$i++) { #prevent deep recursion if ($All[$i]{qmod} eq $qmod) { $jumped++; } } # high jumped values are normal for popular modules when # dealing with large bundles: XML::Simple, # namespace::autoclean, UNIVERSAL::require CPAN->debug("qmod[$qmod]jumped[$jumped]") if $CPAN::DEBUG; my $obj = "$class\::Item"->new( qmod => $qmod, reqtype => $reqtype, optional => !! $optional, ); unshift @All, $obj; } CPAN->debug(sprintf("after jumpqueue All[%s]", join("",map {sprintf " %s\[%s][%s]\n",$_->{qmod},$_->{reqtype},$_->{optional}} @All) )) if $CPAN::DEBUG; } # CPAN::Queue::exists ; sub exists { my($self,$what) = @_; my @all = map { $_->{qmod} } @All; my $exists = grep { $_->{qmod} eq $what } @All; # warn "in exists what[$what] all[@all] exists[$exists]"; $exists; } # CPAN::Queue::delete ; sub delete { my($self,$mod) = @_; @All = grep { $_->{qmod} ne $mod } @All; CPAN->debug(sprintf("after delete mod[%s] All[%s]", $mod, join("",map {sprintf " %s\[%s][%s]\n",$_->{qmod},$_->{reqtype},$_->{optional}} @All) )) if $CPAN::DEBUG; } # CPAN::Queue::nullify_queue ; sub nullify_queue { @All = (); } # CPAN::Queue::size ; sub size { return scalar @All; } sub reqtype_of { my($self,$mod) = @_; my $best = ""; for my $item (grep { $_->{qmod} eq $mod } @All) { my $c = $item->{reqtype}; if ($c eq "c") { $best = $c; last; } elsif ($c eq "r") { $best = $c; } elsif ($c eq "b") { if ($best eq "") { $best = $c; } } else { die "Panic: in reqtype_of: reqtype[$c] seen, should never happen"; } } return $best; } sub iterator { my $i = 0; return sub { until ($All[$i] || $i > $#All) { $i++; } return if $i > $#All; return $All[$i++] }; } 1; __END__ =head1 NAME CPAN::Queue - internal queue support for CPAN.pm =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK�������!�naX67��7����perl5/CPAN/Prompt.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: package CPAN::Prompt; use overload '""' => "as_string"; use vars qw($prompt); use vars qw( $VERSION ); $VERSION = "5.5"; $prompt = "cpan> "; $CPAN::CurrentCommandId ||= 0; sub new { bless {}, shift; } sub as_string { my $word = "cpan"; unless ($CPAN::META->{LOCK}) { $word = "nolock_cpan"; } if ($CPAN::Config->{commandnumber_in_prompt}) { sprintf "$word\[%d]> ", $CPAN::CurrentCommandId; } else { "$word> "; } } 1; PK�������!�bJG��JG����perl5/CPAN/Mirrors.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: =head1 NAME CPAN::Mirrors - Get CPAN mirror information and select a fast one =head1 SYNOPSIS use CPAN::Mirrors; my $mirrors = CPAN::Mirrors->new( $mirrored_by_file ); my $seen = {}; my $best_continent = $mirrors->find_best_continents( { seen => $seen } ); my @mirrors = $mirrors->get_mirrors_by_continents( $best_continent ); my $callback = sub { my( $m ) = @_; printf "%s = %s\n", $m->hostname, $m->rtt }; $mirrors->get_mirrors_timings( \@mirrors, $seen, $callback, %args ); @mirrors = sort { $a->rtt <=> $b->rtt } @mirrors; print "Best mirrors are ", map( { $_->rtt } @mirrors[0..3] ), "\n"; =head1 DESCRIPTION =over =cut package CPAN::Mirrors; use strict; use vars qw($VERSION $urllist $silent); $VERSION = "2.27"; use Carp; use FileHandle; use Fcntl ":flock"; use Net::Ping (); use CPAN::Version; =item new( LOCAL_FILE_NAME ) Create a new CPAN::Mirrors object from LOCAL_FILE_NAME. This file should look like that in http://www.cpan.org/MIRRORED.BY . =cut sub new { my ($class, $file) = @_; croak "CPAN::Mirrors->new requires a filename" unless defined $file; croak "The file [$file] was not found" unless -e $file; my $self = bless { mirrors => [], geography => {}, }, $class; $self->parse_mirrored_by( $file ); return $self; } sub parse_mirrored_by { my ($self, $file) = @_; my $handle = FileHandle->new; $handle->open($file) or croak "Couldn't open $file: $!"; flock $handle, LOCK_SH; $self->_parse($file,$handle); flock $handle, LOCK_UN; $handle->close; } =item continents() Return a list of continents based on those defined in F<MIRRORED.BY>. =cut sub continents { my ($self) = @_; return sort keys %{$self->{geography} || {}}; } =item countries( [CONTINENTS] ) Return a list of countries based on those defined in F<MIRRORED.BY>. It only returns countries for the continents you specify (as defined in C<continents>). If you don't specify any continents, it returns all of the countries listed in F<MIRRORED.BY>. =cut sub countries { my ($self, @continents) = @_; @continents = $self->continents unless @continents; my @countries; for my $c (@continents) { push @countries, sort keys %{ $self->{geography}{$c} || {} }; } return @countries; } =item mirrors( [COUNTRIES] ) Return a list of mirrors based on those defined in F<MIRRORED.BY>. It only returns mirrors for the countries you specify (as defined in C<countries>). If you don't specify any countries, it returns all of the mirrors listed in F<MIRRORED.BY>. =cut sub mirrors { my ($self, @countries) = @_; return @{$self->{mirrors}} unless @countries; my %wanted = map { $_ => 1 } @countries; my @found; for my $m (@{$self->{mirrors}}) { push @found, $m if exists $wanted{$m->country}; } return @found; } =item get_mirrors_by_countries( [COUNTRIES] ) A more sensible synonym for mirrors. =cut sub get_mirrors_by_countries { &mirrors } =item get_mirrors_by_continents( [CONTINENTS] ) Return a list of mirrors for all of continents you specify. If you don't specify any continents, it returns all of the mirrors. You can specify a single continent or an array reference of continents. =cut sub get_mirrors_by_continents { my ($self, $continents ) = @_; $continents = [ $continents ] unless ref $continents; eval { $self->mirrors( $self->get_countries_by_continents( @$continents ) ); }; } =item get_countries_by_continents( [CONTINENTS] ) A more sensible synonym for countries. =cut sub get_countries_by_continents { &countries } =item default_mirror Returns the default mirror, http://www.cpan.org/ . This mirror uses dynamic DNS to give a close mirror. =cut sub default_mirror { CPAN::Mirrored::By->new({ http => 'http://www.cpan.org/'}); } =item best_mirrors C<best_mirrors> checks for the best mirrors based on the list of continents you pass, or, without that, all continents, as defined by C<CPAN::Mirrored::By>. It pings each mirror, up to the value of C<how_many>. In list context, it returns up to C<how_many> mirrors. In scalar context, it returns the single best mirror. Arguments how_many - the number of mirrors to return. Default: 1 callback - a callback for find_best_continents verbose - true or false on all the whining and moaning. Default: false continents - an array ref of the continents to check external_ping - if true, use external ping via Net::Ping::External. Default: false If you don't specify the continents, C<best_mirrors> calls C<find_best_continents> to get the list of continents to check. If you don't have L<Net::Ping> v2.13 or later, needed for timings, this returns the default mirror. C<external_ping> should be set and then C<Net::Ping::External> needs to be installed, if the local network has a transparent proxy. =cut sub best_mirrors { my ($self, %args) = @_; my $how_many = $args{how_many} || 1; my $callback = $args{callback}; my $verbose = defined $args{verbose} ? $args{verbose} : 0; my $continents = $args{continents} || []; $continents = [$continents] unless ref $continents; $args{external_ping} = 0 unless defined $args{external_ping}; my $external_ping = $args{external_ping}; # Old Net::Ping did not do timings at all my $min_version = '2.13'; unless( CPAN::Version->vgt(Net::Ping->VERSION, $min_version) ) { carp sprintf "Net::Ping version is %s (< %s). Returning %s", Net::Ping->VERSION, $min_version, $self->default_mirror; return $self->default_mirror; } my $seen = {}; if ( ! @$continents ) { print "Searching for the best continent ...\n" if $verbose; my @best_continents = $self->find_best_continents( seen => $seen, verbose => $verbose, callback => $callback, external_ping => $external_ping, ); # Only add enough continents to find enough mirrors my $count = 0; for my $continent ( @best_continents ) { push @$continents, $continent; $count += $self->mirrors( $self->countries($continent) ); last if $count >= $how_many; } } return $self->default_mirror unless @$continents; print "Scanning " . join(", ", @$continents) . " ...\n" if $verbose; my $trial_mirrors = $self->get_n_random_mirrors_by_continents( 3 * $how_many, $continents->[0] ); my $timings = $self->get_mirrors_timings( $trial_mirrors, $seen, $callback, %args, ); return $self->default_mirror unless @$timings; $how_many = @$timings if $how_many > @$timings; return wantarray ? @{$timings}[0 .. $how_many-1] : $timings->[0]; } =item get_n_random_mirrors_by_continents( N, [CONTINENTS] ) Returns up to N random mirrors for the specified continents. Specify the continents as an array reference. =cut sub get_n_random_mirrors_by_continents { my( $self, $n, $continents ) = @_; $n ||= 3; $continents = [ $continents ] unless ref $continents; if ( $n <= 0 ) { return wantarray ? () : []; } my @long_list = $self->get_mirrors_by_continents( $continents ); if ( $n eq '*' or $n > @long_list ) { return wantarray ? @long_list : \@long_list; } @long_list = map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, rand]} @long_list; splice @long_list, $n; # truncate \@long_list; } =item get_mirrors_timings( MIRROR_LIST, SEEN, CALLBACK, %ARGS ); Pings the listed mirrors and returns a list of mirrors sorted in ascending ping times. C<MIRROR_LIST> is an anonymous array of C<CPAN::Mirrored::By> objects to ping. The optional argument C<SEEN> is a hash reference used to track the mirrors you've already pinged. The optional argument C<CALLBACK> is a subroutine reference to call after each ping. It gets the C<CPAN::Mirrored::By> object after each ping. =cut sub get_mirrors_timings { my( $self, $mirror_list, $seen, $callback, %args ) = @_; $seen = {} unless defined $seen; croak "The mirror list argument must be an array reference" unless ref $mirror_list eq ref []; croak "The seen argument must be a hash reference" unless ref $seen eq ref {}; croak "callback must be a subroutine" if( defined $callback and ref $callback ne ref sub {} ); my $timings = []; for my $m ( @$mirror_list ) { $seen->{$m->hostname} = $m; next unless eval{ $m->http }; if( $self->_try_a_ping( $seen, $m, ) ) { my $ping = $m->ping(%args); next unless defined $ping; # printf "m %s ping %s\n", $m, $ping; push @$timings, $m; $callback->( $m ) if $callback; } else { push @$timings, $seen->{$m->hostname} if defined $seen->{$m->hostname}->rtt; } } my @best = sort { if( defined $a->rtt and defined $b->rtt ) { $a->rtt <=> $b->rtt } elsif( defined $a->rtt and ! defined $b->rtt ) { return -1; } elsif( ! defined $a->rtt and defined $b->rtt ) { return 1; } elsif( ! defined $a->rtt and ! defined $b->rtt ) { return 0; } } @$timings; return wantarray ? @best : \@best; } =item find_best_continents( HASH_REF ); C<find_best_continents> goes through each continent and pings C<N> random mirrors on that continent. It then orders the continents by ascending median ping time. In list context, it returns the ordered list of continent. In scalar context, it returns the same list as an anonymous array. Arguments: n - the number of hosts to ping for each continent. Default: 3 seen - a hashref of cached hostname ping times verbose - true or false for noisy or quiet. Default: false callback - a subroutine to run after each ping. ping_cache_limit - how long, in seconds, to reuse previous ping times. Default: 1 day The C<seen> hash has hostnames as keys and anonymous arrays as values. The anonymous array is a triplet of a C<CPAN::Mirrored::By> object, a ping time, and the epoch time for the measurement. The callback subroutine gets the C<CPAN::Mirrored::By> object, the ping time, and measurement time (the same things in the C<seen> hashref) as arguments. C<find_best_continents> doesn't care what the callback does and ignores the return value. With a low value for C<N>, a single mirror might skew the results enough to choose a worse continent. If you have that problem, try a larger value. =cut sub find_best_continents { my ($self, %args) = @_; $args{n} ||= 3; $args{verbose} = 0 unless defined $args{verbose}; $args{seen} = {} unless defined $args{seen}; croak "The seen argument must be a hash reference" unless ref $args{seen} eq ref {}; $args{ping_cache_limit} = 24 * 60 * 60 unless defined $args{ping_cache_limit}; croak "callback must be a subroutine" if( defined $args{callback} and ref $args{callback} ne ref sub {} ); my %medians; CONT: for my $c ( $self->continents ) { my @mirrors = $self->mirrors( $self->countries($c) ); printf "Testing %s (%d mirrors)\n", $c, scalar @mirrors if $args{verbose}; next CONT unless @mirrors; my $n = (@mirrors < $args{n}) ? @mirrors : $args{n}; my @tests; my $tries = 0; RANDOM: while ( @mirrors && @tests < $n && $tries++ < 15 ) { my $m = splice( @mirrors, int(rand(@mirrors)), 1 ); if( $self->_try_a_ping( $args{seen}, $m, $args{ping_cache_limit} )) { $self->get_mirrors_timings( [ $m ], $args{seen}, $args{callback}, %args, ); next RANDOM unless defined $args{seen}{$m->hostname}->rtt; } printf "(%s -> %0.2f ms)", $m->hostname, join ' ', 1000 * $args{seen}{$m->hostname}->rtt if $args{verbose}; push @tests, $args{seen}{$m->hostname}->rtt; } my $median = $self->_get_median_ping_time( \@tests, $args{verbose} ); $medians{$c} = $median if defined $median; } my @best_cont = sort { $medians{$a} <=> $medians{$b} } keys %medians; if ( $args{verbose} ) { print "Median result by continent:\n"; if ( @best_cont ) { for my $c ( @best_cont ) { printf( " %7.2f ms %s\n", $medians{$c}*1000, $c ); } } else { print " **** No results found ****\n" } } return wantarray ? @best_cont : $best_cont[0]; } # retry if sub _try_a_ping { my ($self, $seen, $mirror, $ping_cache_limit ) = @_; ( ! exists $seen->{$mirror->hostname} or ! defined $seen->{$mirror->hostname}->rtt or ! defined $ping_cache_limit or time - $seen->{$mirror->hostname}->ping_time > $ping_cache_limit ) } sub _get_median_ping_time { my ($self, $tests, $verbose ) = @_; my @sorted = sort { $a <=> $b } @$tests; my $median = do { if ( @sorted == 0 ) { undef } elsif ( @sorted == 1 ) { $sorted[0] } elsif ( @sorted % 2 ) { $sorted[ int(@sorted / 2) ] } else { my $mid_high = int(@sorted/2); ($sorted[$mid_high-1] + $sorted[$mid_high])/2; } }; if ($verbose){ if ($median) { printf " => median time: %.2f ms\n", $median * 1000 } else { printf " => **** no median time ****\n"; } } return $median; } # Adapted from Parse::CPAN::MirroredBy by Adam Kennedy sub _parse { my ($self, $file, $handle) = @_; my $output = $self->{mirrors}; my $geo = $self->{geography}; local $/ = "\012"; my $line = 0; my $mirror = undef; while ( 1 ) { # Next line my $string = <$handle>; last if ! defined $string; $line = $line + 1; # Remove the useless lines chomp( $string ); next if $string =~ /^\s*$/; next if $string =~ /^\s*#/; # Hostname or property? if ( $string =~ /^\s/ ) { # Property unless ( $string =~ /^\s+(\w+)\s+=\s+\"(.*)\"$/ ) { croak("Invalid property on line $line"); } my ($prop, $value) = ($1,$2); $mirror ||= {}; if ( $prop eq 'dst_location' ) { my (@location,$continent,$country); @location = (split /\s*,\s*/, $value) and ($continent, $country) = @location[-1,-2]; $continent =~ s/\s\(.*//; $continent =~ s/\W+$//; # if Jarkko doesn't know latitude/longitude $geo->{$continent}{$country} = 1 if $continent && $country; $mirror->{continent} = $continent || "unknown"; $mirror->{country} = $country || "unknown"; } elsif ( $prop eq 'dst_http' ) { $mirror->{http} = $value; } elsif ( $prop eq 'dst_ftp' ) { $mirror->{ftp} = $value; } elsif ( $prop eq 'dst_rsync' ) { $mirror->{rsync} = $value; } else { $prop =~ s/^dst_//; $mirror->{$prop} = $value; } } else { # Hostname unless ( $string =~ /^([\w\.-]+)\:\s*$/ ) { croak("Invalid host name on line $line"); } my $current = $mirror; $mirror = { hostname => "$1" }; if ( $current ) { push @$output, CPAN::Mirrored::By->new($current); } } } if ( $mirror ) { push @$output, CPAN::Mirrored::By->new($mirror); } return; } #--------------------------------------------------------------------------# package CPAN::Mirrored::By; use strict; use Net::Ping (); sub new { my($self,$arg) = @_; $arg ||= {}; bless $arg, $self; } sub hostname { shift->{hostname} } sub continent { shift->{continent} } sub country { shift->{country} } sub http { shift->{http} || '' } sub ftp { shift->{ftp} || '' } sub rsync { shift->{rsync} || '' } sub rtt { shift->{rtt} } sub ping_time { shift->{ping_time} } sub url { my $self = shift; return $self->{http} || $self->{ftp}; } sub ping { my($self, %args) = @_; my $external_ping = $args{external_ping}; if ($external_ping) { eval { require Net::Ping::External } or die "Net::Ping::External required to use external ping command"; } my $ping = Net::Ping->new( $external_ping ? 'external' : $^O eq 'VMS' ? 'icmp' : 'tcp', 1 ); my ($proto) = $self->url =~ m{^([^:]+)}; my $port = $proto eq 'http' ? 80 : 21; return unless $port; if ( $ping->can('port_number') ) { $ping->port_number($port); } else { $ping->{'port_num'} = $port; } $ping->hires(1) if $ping->can('hires'); my ($alive,$rtt) = eval { $ping->ping($self->hostname); }; my $verbose = $args{verbose}; if ($verbose && !$alive) { printf "(host %s not alive)", $self->hostname; } $self->{rtt} = $alive ? $rtt : undef; $self->{ping_time} = time; $self->rtt; } 1; =back =head1 AUTHOR Andreas Koenig C<< <andk@cpan.org> >>, David Golden C<< <dagolden@cpan.org> >>, brian d foy C<< <bdfoy@cpan.org> >> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<http://www.perl.com/perl/misc/Artistic.html> =cut 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<META.yml> or F<META.json> files in CPAN distributions, #pod and as defined by L<CPAN::Meta::Spec>; #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<CPAN::Meta::Spec/Version Ranges>. 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<E<gt>=>). 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<exactly> 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</accepts_module> 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<CPAN::Meta::Spec>. 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</accepts> 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<META.yml> or F<META.json> files in CPAN distributions, and as defined by L<CPAN::Meta::Spec>; 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<CPAN::Meta::Spec/Version Ranges>. 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<E<gt>=>). 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<exactly> 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</accepts_module> instead). =head2 as_string $range->as_string; This returns a string containing the version requirements in the format described in L<CPAN::Meta::Spec>. This should only be used for informational purposes such as error messages and should not be interpreted or used for comparison (see L</accepts> 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 <dagolden@cpan.org> =item * Ricardo Signes <rjbs@cpan.org> =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�������!�somFU��FU����perl5/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<META.yml> or F<META.json> files in CPAN distributions, #pod and as defined by L<CPAN::Meta::Spec>. #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<bad_version_hook> -- 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<exactly> 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<CPAN::Meta::Spec> 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</accepts_module> 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</accepts_module> 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<finalize> 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<if> 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<CPAN::Meta::Spec> 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<CPAN::Meta::Spec/Version Ranges>. 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<E<gt>=>). 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</new> #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<META.yml> or F<META.json> files in CPAN distributions, and as defined by L<CPAN::Meta::Spec>. 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<bad_version_hook> -- 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<exactly> 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<CPAN::Meta::Spec> 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</accepts_module> 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</accepts_module> 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<finalize> method called on them. =head2 finalize This method marks the requirements finalized. Subsequent attempts to change the requirements will be fatal, I<if> 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<CPAN::Meta::Spec> 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<CPAN::Meta::Spec/Version Ranges>. 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<E<gt>=>). 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</new> 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<https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements/issues>. 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<https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements> git clone https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements.git =head1 AUTHORS =over 4 =item * David Golden <dagolden@cpan.org> =item * Ricardo Signes <rjbs@cpan.org> =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 <mohawk2@users.noreply.github.com> =item * Graham Knop <haarg@haarg.org> =item * Karen Etheridge <ether@cpan.org> =item * Leon Timmermans <fawaka@gmail.com> =item * Paul Howarth <paul@city-fan.org> =item * Ricardo Signes <rjbs@semiotic.systems> =item * robario <webmaster@robario.com> =item * Tatsuhiko Miyagawa <miyagawa@bulknews.net> =item * Tatsuhiko Miyagawa <miyagawa@gmail.com> =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�A�A� ��perl5/CPAN.pmnu�6$��������# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*- # vim: ts=4 sts=4 sw=4: use strict; package CPAN; $CPAN::VERSION = '2.36'; $CPAN::VERSION =~ s/_//; # we need to run chdir all over and we would get at wrong libraries # there use File::Spec (); BEGIN { if (File::Spec->can("rel2abs")) { for my $inc (@INC) { $inc = File::Spec->rel2abs($inc) unless ref $inc; } } $SIG{WINCH} = 'IGNORE' if exists $SIG{WINCH}; } use CPAN::Author; use CPAN::HandleConfig; use CPAN::Version; use CPAN::Bundle; use CPAN::CacheMgr; use CPAN::Complete; use CPAN::Debug; use CPAN::Distribution; use CPAN::Distrostatus; use CPAN::FTP; use CPAN::Index 1.93; # https://rt.cpan.org/Ticket/Display.html?id=43349 use CPAN::InfoObj; use CPAN::Module; use CPAN::Prompt; use CPAN::URL; use CPAN::Queue; use CPAN::Tarzip; use CPAN::DeferredCode; use CPAN::Shell; use CPAN::LWP::UserAgent; use CPAN::Exception::RecursiveDependency; use CPAN::Exception::yaml_not_installed; use CPAN::Exception::yaml_process_error; use Carp (); use Config (); use Cwd qw(chdir); use DirHandle (); use Exporter (); use ExtUtils::MakeMaker qw(prompt); # for some unknown reason, # 5.005_04 does not work without # this use File::Basename (); use File::Copy (); use File::Find; use File::Path (); use FileHandle (); use Fcntl qw(:flock); use Safe (); use Sys::Hostname qw(hostname); use Text::ParseWords (); use Text::Wrap (); # protect against "called too early" sub find_perl (); sub anycwd (); sub _uniq; no lib "."; require Mac::BuildTools if $^O eq 'MacOS'; if ($ENV{PERL5_CPAN_IS_RUNNING} && $$ != $ENV{PERL5_CPAN_IS_RUNNING}) { $ENV{PERL5_CPAN_IS_RUNNING_IN_RECURSION} ||= $ENV{PERL5_CPAN_IS_RUNNING}; my @rec = _uniq split(/,/, $ENV{PERL5_CPAN_IS_RUNNING_IN_RECURSION}), $$; $ENV{PERL5_CPAN_IS_RUNNING_IN_RECURSION} = join ",", @rec; # warn "# Note: Recursive call of CPAN.pm detected\n"; my $w = sprintf "# Note: CPAN.pm is running in process %d now", pop @rec; my %sleep = ( 5 => 30, 6 => 60, 7 => 120, ); my $sleep = @rec > 7 ? 300 : ($sleep{scalar @rec}||0); my $verbose = @rec >= 4; while (@rec) { $w .= sprintf " which has been called by process %d", pop @rec; } if ($sleep) { $w .= ".\n\n# Sleeping $sleep seconds to protect other processes\n"; } if ($verbose) { warn $w; } local $| = 1; my $have_been_sleeping = 0; while ($sleep > 0) { printf "\r#%5d", --$sleep; sleep 1; ++$have_been_sleeping; } print "\n" if $have_been_sleeping; } $ENV{PERL5_CPAN_IS_RUNNING}=$$; $ENV{PERL5_CPANPLUS_IS_RUNNING}=$$; # https://rt.cpan.org/Ticket/Display.html?id=23735 END { $CPAN::End++; &cleanup; } $CPAN::Signal ||= 0; $CPAN::Frontend ||= "CPAN::Shell"; unless (@CPAN::Defaultsites) { @CPAN::Defaultsites = map { CPAN::URL->new(TEXT => $_, FROM => "DEF") } "http://www.perl.org/CPAN/", "ftp://ftp.perl.org/pub/CPAN/"; } # $CPAN::iCwd (i for initial) $CPAN::iCwd ||= CPAN::anycwd(); $CPAN::Perl ||= CPAN::find_perl(); $CPAN::Defaultdocs ||= "http://search.cpan.org/perldoc?"; $CPAN::Defaultrecent ||= "http://search.cpan.org/uploads.rdf"; $CPAN::Defaultrecent ||= "http://cpan.uwinnipeg.ca/htdocs/cpan.xml"; # our globals are getting a mess use vars qw( $AUTOLOAD $Be_Silent $CONFIG_DIRTY $Defaultdocs $Echo_readline $Frontend $GOTOSHELL $HAS_USABLE $Have_warned $MAX_RECURSION $META $RUN_DEGRADED $Signal $SQLite $Suppress_readline $VERSION $autoload_recursion $term @Defaultsites @EXPORT ); $MAX_RECURSION = 32; @CPAN::ISA = qw(CPAN::Debug Exporter); # note that these functions live in CPAN::Shell and get executed via # AUTOLOAD when called directly @EXPORT = qw( autobundle bundle clean cvs_import expand force fforce get install install_tested is_tested make mkmyconfig notest perldoc readme recent recompile report shell smoke test upgrade ); sub soft_chdir_with_alternatives ($); { $autoload_recursion ||= 0; #-> sub CPAN::AUTOLOAD ; sub AUTOLOAD { ## no critic $autoload_recursion++; my($l) = $AUTOLOAD; $l =~ s/.*:://; if ($CPAN::Signal) { warn "Refusing to autoload '$l' while signal pending"; $autoload_recursion--; return; } if ($autoload_recursion > 1) { my $fullcommand = join " ", map { "'$_'" } $l, @_; warn "Refusing to autoload $fullcommand in recursion\n"; $autoload_recursion--; return; } my(%export); @export{@EXPORT} = ''; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; if (exists $export{$l}) { CPAN::Shell->$l(@_); } else { die(qq{Unknown CPAN command "$AUTOLOAD". }. qq{Type ? for help.\n}); } $autoload_recursion--; } } { my $x = *SAVEOUT; # avoid warning open($x,">&STDOUT") or die "dup failed"; my $redir = 0; sub _redirect(@) { #die if $redir; local $_; push(@_,undef); while(defined($_=shift)) { if (s/^\s*>//){ my ($m) = s/^>// ? ">" : ""; s/\s+//; $_=shift unless length; die "no dest" unless defined; open(STDOUT,">$m$_") or die "open:$_:$!\n"; $redir=1; } elsif ( s/^\s*\|\s*// ) { my $pipe="| $_"; while(defined($_[0])){ $pipe .= ' ' . shift; } open(STDOUT,$pipe) or die "open:$pipe:$!\n"; $redir=1; } else { push(@_,$_); } } return @_; } sub _unredirect { return unless $redir; $redir = 0; ## redirect: unredirect and propagate errors. explicit close to wait for pipe. close(STDOUT); open(STDOUT,">&SAVEOUT"); die "$@" if "$@"; ## redirect: done } } sub _uniq { my(@list) = @_; my %seen; return grep { !$seen{$_}++ } @list; } #-> sub CPAN::shell ; sub shell { my($self) = @_; $Suppress_readline = ! -t STDIN unless defined $Suppress_readline; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; my $oprompt = shift || CPAN::Prompt->new; my $prompt = $oprompt; my $commandline = shift || ""; $CPAN::CurrentCommandId ||= 1; local($^W) = 1; unless ($Suppress_readline) { require Term::ReadLine; if (! $term or $term->ReadLine eq "Term::ReadLine::Stub" ) { $term = Term::ReadLine->new('CPAN Monitor'); } if ($term->ReadLine eq "Term::ReadLine::Gnu") { my $attribs = $term->Attribs; $attribs->{attempted_completion_function} = sub { &CPAN::Complete::gnu_cpl; } } else { $readline::rl_completion_function = $readline::rl_completion_function = 'CPAN::Complete::cpl'; } if (my $histfile = $CPAN::Config->{'histfile'}) {{ unless ($term->can("AddHistory")) { $CPAN::Frontend->mywarn("Terminal does not support AddHistory.\n"); unless ($CPAN::META->has_inst('Term::ReadLine::Perl')) { $CPAN::Frontend->mywarn("\nTo fix that, maybe try> install Term::ReadLine::Perl\n\n"); } last; } $META->readhist($term,$histfile); }} for ($CPAN::Config->{term_ornaments}) { # alias local $Term::ReadLine::termcap_nowarn = 1; $term->ornaments($_) if defined; } # $term->OUT is autoflushed anyway my $odef = select STDERR; $| = 1; select STDOUT; $| = 1; select $odef; } $META->checklock(); my @cwd = grep { defined $_ and length $_ } CPAN::anycwd(), File::Spec->can("tmpdir") ? File::Spec->tmpdir() : (), File::Spec->rootdir(); my $try_detect_readline; $try_detect_readline = $term->ReadLine eq "Term::ReadLine::Stub" if $term; unless ($CPAN::Config->{inhibit_startup_message}) { my $rl_avail = $Suppress_readline ? "suppressed" : ($term->ReadLine ne "Term::ReadLine::Stub") ? "enabled" : "available (maybe install Bundle::CPAN or Bundle::CPANxxl?)"; $CPAN::Frontend->myprint( sprintf qq{ cpan shell -- CPAN exploration and modules installation (v%s) Enter 'h' for help. }, $CPAN::VERSION, ) } my($continuation) = ""; my $last_term_ornaments; SHELLCOMMAND: while () { if ($Suppress_readline) { if ($Echo_readline) { $|=1; } print $prompt; last SHELLCOMMAND unless defined ($_ = <> ); if ($Echo_readline) { # backdoor: I could not find a way to record sessions print $_; } chomp; } else { last SHELLCOMMAND unless defined ($_ = $term->readline($prompt, $commandline)); } $_ = "$continuation$_" if $continuation; s/^\s+//; next SHELLCOMMAND if /^$/; s/^\s*\?\s*/help /; if (/^(?:q(?:uit)?|bye|exit)\s*$/i) { last SHELLCOMMAND; } elsif (s/\\$//s) { chomp; $continuation = $_; $prompt = " > "; } elsif (/^\!/) { s/^\!//; my($eval) = $_; package CPAN::Eval; # hide from the indexer use strict; use vars qw($import_done); CPAN->import(':DEFAULT') unless $import_done++; CPAN->debug("eval[$eval]") if $CPAN::DEBUG; eval($eval); warn $@ if $@; $continuation = ""; $prompt = $oprompt; } elsif (/./) { my(@line); eval { @line = Text::ParseWords::shellwords($_) }; warn($@), next SHELLCOMMAND if $@; warn("Text::Parsewords could not parse the line [$_]"), next SHELLCOMMAND unless @line; $CPAN::META->debug("line[".join("|",@line)."]") if $CPAN::DEBUG; my $command = shift @line; eval { local (*STDOUT)=*STDOUT; @line = _redirect(@line); CPAN::Shell->$command(@line) }; my $command_error = $@; _unredirect; my $reported_error; if ($command_error) { my $err = $command_error; if (ref $err and $err->isa('CPAN::Exception::blocked_urllist')) { $CPAN::Frontend->mywarn("Client not fully configured, please proceed with configuring.$err"); $reported_error = ref $err; } else { # I'd prefer never to arrive here and make all errors exception objects if ($err =~ /\S/) { require Carp; require Dumpvalue; my $dv = Dumpvalue->new(tick => '"'); Carp::cluck(sprintf "Catching error: %s", $dv->stringify($err)); } } } if ($command =~ /^( # classic commands make |test |install |clean # pragmas for classic commands |ff?orce |notest # compounds |report |smoke |upgrade )$/x) { # only commands that tell us something about failed distros # eval necessary for people without an urllist eval {CPAN::Shell->failed($CPAN::CurrentCommandId,1);}; if (my $err = $@) { unless (ref $err and $reported_error eq ref $err) { die $@; } } } soft_chdir_with_alternatives(\@cwd); $CPAN::Frontend->myprint("\n"); $continuation = ""; $CPAN::CurrentCommandId++; $prompt = $oprompt; } } continue { $commandline = ""; # I do want to be able to pass a default to # shell, but on the second command I see no # use in that $Signal=0; CPAN::Queue->nullify_queue; if ($try_detect_readline) { if ($CPAN::META->has_inst("Term::ReadLine::Gnu") || $CPAN::META->has_inst("Term::ReadLine::Perl") ) { delete $INC{"Term/ReadLine.pm"}; my $redef = 0; local($SIG{__WARN__}) = CPAN::Shell::paintdots_onreload(\$redef); require Term::ReadLine; $CPAN::Frontend->myprint("\n$redef subroutines in ". "Term::ReadLine redefined\n"); $GOTOSHELL = 1; } } if ($term and $term->can("ornaments")) { for ($CPAN::Config->{term_ornaments}) { # alias if (defined $_) { if (not defined $last_term_ornaments or $_ != $last_term_ornaments ) { local $Term::ReadLine::termcap_nowarn = 1; $term->ornaments($_); $last_term_ornaments = $_; } } else { undef $last_term_ornaments; } } } for my $class (qw(Module Distribution)) { # again unsafe meta access? for my $dm (sort keys %{$CPAN::META->{readwrite}{"CPAN::$class"}}) { next unless $CPAN::META->{readwrite}{"CPAN::$class"}{$dm}{incommandcolor}; CPAN->debug("BUG: $class '$dm' was in command state, resetting"); delete $CPAN::META->{readwrite}{"CPAN::$class"}{$dm}{incommandcolor}; } } if ($GOTOSHELL) { $GOTOSHELL = 0; # not too often $META->savehist if $CPAN::term && $CPAN::term->can("GetHistory"); @_ = ($oprompt,""); goto &shell; } } soft_chdir_with_alternatives(\@cwd); } #-> CPAN::soft_chdir_with_alternatives ; sub soft_chdir_with_alternatives ($) { my($cwd) = @_; unless (@$cwd) { my $root = File::Spec->rootdir(); $CPAN::Frontend->mywarn(qq{Warning: no good directory to chdir to! Trying '$root' as temporary haven. }); push @$cwd, $root; } while () { if (chdir "$cwd->[0]") { return; } else { if (@$cwd>1) { $CPAN::Frontend->mywarn(qq{Could not chdir to "$cwd->[0]": $! Trying to chdir to "$cwd->[1]" instead. }); shift @$cwd; } else { $CPAN::Frontend->mydie(qq{Could not chdir to "$cwd->[0]": $!}); } } } } sub _flock { my($fh,$mode) = @_; if ( $Config::Config{d_flock} || $Config::Config{d_fcntl_can_lock} ) { return flock $fh, $mode; } elsif (!$Have_warned->{"d_flock"}++) { $CPAN::Frontend->mywarn("Your OS does not seem to support locking; continuing and ignoring all locking issues\n"); $CPAN::Frontend->mysleep(5); return 1; } else { return 1; } } sub _yaml_module () { my $yaml_module = $CPAN::Config->{yaml_module} || "YAML"; if ( $yaml_module ne "YAML" && !$CPAN::META->has_inst($yaml_module) ) { # $CPAN::Frontend->mywarn("'$yaml_module' not installed, falling back to 'YAML'\n"); $yaml_module = "YAML"; } if ($yaml_module eq "YAML" && $CPAN::META->has_inst($yaml_module) && $YAML::VERSION < 0.60 && !$Have_warned->{"YAML"}++ ) { $CPAN::Frontend->mywarn("Warning: YAML version '$YAML::VERSION' is too low, please upgrade!\n". "I'll continue but problems are *very* likely to happen.\n" ); $CPAN::Frontend->mysleep(5); } return $yaml_module; } # CPAN::_yaml_loadfile sub _yaml_loadfile { my($self,$local_file,$opt) = @_; return +[] unless -s $local_file; my $opt_loadblessed = $opt->{loadblessed} || $CPAN::Config->{yaml_load_code} || 0; my $yaml_module = _yaml_module; if ($CPAN::META->has_inst($yaml_module)) { # temporarily enable yaml code deserialisation no strict 'refs'; # 5.6.2 could not do the local() with the reference # so we do it manually instead my $old_loadcode = ${"$yaml_module\::LoadCode"}; my $old_loadblessed = ${"$yaml_module\::LoadBlessed"}; ${ "$yaml_module\::LoadCode" } = $CPAN::Config->{yaml_load_code} || 0; ${ "$yaml_module\::LoadBlessed" } = $opt_loadblessed ? 1 : 0; my ($code, @yaml); if ($code = UNIVERSAL::can($yaml_module, "LoadFile")) { eval { @yaml = $code->($local_file); }; if ($@) { # this shall not be done by the frontend die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"parse",$@); } } elsif ($code = UNIVERSAL::can($yaml_module, "Load")) { local *FH; if (open FH, $local_file) { local $/; my $ystream = <FH>; eval { @yaml = $code->($ystream); }; if ($@) { # this shall not be done by the frontend die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"parse",$@); } } else { $CPAN::Frontend->mywarn("Could not open '$local_file': $!"); } } ${"$yaml_module\::LoadCode"} = $old_loadcode; ${"$yaml_module\::LoadBlessed"} = $old_loadblessed; return \@yaml; } else { # this shall not be done by the frontend die CPAN::Exception::yaml_not_installed->new($yaml_module, $local_file, "parse"); } return +[]; } # CPAN::_yaml_dumpfile sub _yaml_dumpfile { my($self,$local_file,@what) = @_; my $yaml_module = _yaml_module; if ($CPAN::META->has_inst($yaml_module)) { my $code; if (UNIVERSAL::isa($local_file, "FileHandle")) { $code = UNIVERSAL::can($yaml_module, "Dump"); eval { print $local_file $code->(@what) }; } elsif ($code = UNIVERSAL::can($yaml_module, "DumpFile")) { eval { $code->($local_file,@what); }; } elsif ($code = UNIVERSAL::can($yaml_module, "Dump")) { local *FH; open FH, ">$local_file" or die "Could not open '$local_file': $!"; print FH $code->(@what); } if ($@) { die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"dump",$@); } } else { if (UNIVERSAL::isa($local_file, "FileHandle")) { # I think this case does not justify a warning at all } else { die CPAN::Exception::yaml_not_installed->new($yaml_module, $local_file, "dump"); } } } sub _init_sqlite () { unless ($CPAN::META->has_inst("CPAN::SQLite")) { $CPAN::Frontend->mywarn(qq{CPAN::SQLite not installed, trying to work without\n}) unless $Have_warned->{"CPAN::SQLite"}++; return; } require CPAN::SQLite::META; # not needed since CVS version of 2006-12-17 $CPAN::SQLite ||= CPAN::SQLite::META->new($CPAN::META); } { my $negative_cache = {}; sub _sqlite_running { if ($negative_cache->{time} && time < $negative_cache->{time} + 60) { # need to cache the result, otherwise too slow return $negative_cache->{fact}; } else { $negative_cache = {}; # reset } my $ret = $CPAN::Config->{use_sqlite} && ($CPAN::SQLite || _init_sqlite()); return $ret if $ret; # fast anyway $negative_cache->{time} = time; return $negative_cache->{fact} = $ret; } } $META ||= CPAN->new; # In case we re-eval ourselves we need the || # from here on only subs. ################################################################################ sub _perl_fingerprint { my($self,$other_fingerprint) = @_; my $dll = eval {OS2::DLLname()}; my $mtime_dll = 0; if (defined $dll) { $mtime_dll = (-f $dll ? (stat(_))[9] : '-1'); } my $mtime_perl = (-f CPAN::find_perl ? (stat(_))[9] : '-1'); my $this_fingerprint = { '$^X' => CPAN::find_perl, sitearchexp => $Config::Config{sitearchexp}, 'mtime_$^X' => $mtime_perl, 'mtime_dll' => $mtime_dll, }; if ($other_fingerprint) { if (exists $other_fingerprint->{'stat($^X)'}) { # repair fp from rev. 1.88_57 $other_fingerprint->{'mtime_$^X'} = $other_fingerprint->{'stat($^X)'}[9]; } # mandatory keys since 1.88_57 for my $key (qw($^X sitearchexp mtime_dll mtime_$^X)) { return unless $other_fingerprint->{$key} eq $this_fingerprint->{$key}; } return 1; } else { return $this_fingerprint; } } sub suggest_myconfig () { SUGGEST_MYCONFIG: if(!$INC{'CPAN/MyConfig.pm'}) { $CPAN::Frontend->myprint("You don't seem to have a user ". "configuration (MyConfig.pm) yet.\n"); my $new = CPAN::Shell::colorable_makemaker_prompt("Do you want to create a ". "user configuration now? (Y/n)", "yes"); if($new =~ m{^y}i) { CPAN::Shell->mkmyconfig(); return &checklock; } else { $CPAN::Frontend->mydie("OK, giving up."); } } } #-> sub CPAN::all_objects ; sub all_objects { my($mgr,$class) = @_; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; CPAN->debug("mgr[$mgr] class[$class]") if $CPAN::DEBUG; CPAN::Index->reload; values %{ $META->{readwrite}{$class} }; # unsafe meta access, ok } # Called by shell, not in batch mode. In batch mode I see no risk in # having many processes updating something as installations are # continually checked at runtime. In shell mode I suspect it is # unintentional to open more than one shell at a time #-> sub CPAN::checklock ; sub checklock { my($self) = @_; my $lockfile = File::Spec->catfile($CPAN::Config->{cpan_home},".lock"); if (-f $lockfile && -M _ > 0) { my $fh = FileHandle->new($lockfile) or $CPAN::Frontend->mydie("Could not open lockfile '$lockfile': $!"); my $otherpid = <$fh>; my $otherhost = <$fh>; $fh->close; if (defined $otherpid && length $otherpid) { chomp $otherpid; } if (defined $otherhost && length $otherhost) { chomp $otherhost; } my $thishost = hostname(); my $ask_if_degraded_wanted = 0; if (defined $otherhost && defined $thishost && $otherhost ne '' && $thishost ne '' && $otherhost ne $thishost) { $CPAN::Frontend->mydie(sprintf("CPAN.pm panic: Lockfile '$lockfile'\n". "reports other host $otherhost and other ". "process $otherpid.\n". "Cannot proceed.\n")); } elsif ($RUN_DEGRADED) { $CPAN::Frontend->mywarn("Running in downgraded mode (experimental)\n"); } elsif (defined $otherpid && $otherpid) { return if $$ == $otherpid; # should never happen $CPAN::Frontend->mywarn( qq{ There seems to be running another CPAN process (pid $otherpid). Contacting... }); if (kill 0, $otherpid or $!{EPERM}) { $CPAN::Frontend->mywarn(qq{Other job is running.\n}); $ask_if_degraded_wanted = 1; } elsif (-w $lockfile) { my($ans) = CPAN::Shell::colorable_makemaker_prompt (qq{Other job not responding. Shall I overwrite }. qq{the lockfile '$lockfile'? (Y/n)},"y"); $CPAN::Frontend->myexit("Ok, bye\n") unless $ans =~ /^y/i; } else { Carp::croak( qq{Lockfile '$lockfile' not writable by you. }. qq{Cannot proceed.\n}. qq{ On UNIX try:\n}. qq{ rm '$lockfile'\n}. qq{ and then rerun us.\n} ); } } elsif ($^O eq "MSWin32") { $CPAN::Frontend->mywarn( qq{ There seems to be running another CPAN process according to '$lockfile'. }); $ask_if_degraded_wanted = 1; } else { $CPAN::Frontend->mydie(sprintf("CPAN.pm panic: Found invalid lockfile ". "'$lockfile', please remove. Cannot proceed.\n")); } if ($ask_if_degraded_wanted) { my($ans) = CPAN::Shell::colorable_makemaker_prompt (qq{Shall I try to run in downgraded }. qq{mode? (Y/n)},"y"); if ($ans =~ /^y/i) { $CPAN::Frontend->mywarn("Running in downgraded mode (experimental). Please report if something unexpected happens\n"); $RUN_DEGRADED = 1; for ($CPAN::Config) { # XXX # $_->{build_dir_reuse} = 0; # 2006-11-17 akoenig Why was that? $_->{commandnumber_in_prompt} = 0; # visibility $_->{histfile} = ""; # who should win otherwise? $_->{cache_metadata} = 0; # better would be a lock? $_->{use_sqlite} = 0; # better would be a write lock! $_->{auto_commit} = 0; # we are violent, do not persist $_->{test_report} = 0; # Oliver Paukstadt had sent wrong reports in degraded mode } } else { my $msg = "You may want to kill the other job and delete the lockfile."; if (defined $otherpid) { $msg .= " Something like: kill $otherpid rm $lockfile "; } $CPAN::Frontend->mydie("\n$msg"); } } } my $dotcpan = $CPAN::Config->{cpan_home}; eval { File::Path::mkpath($dotcpan);}; if ($@) { # A special case at least for Jarkko. my $firsterror = $@; my $seconderror; my $symlinkcpan; if (-l $dotcpan) { $symlinkcpan = readlink $dotcpan; die "readlink $dotcpan failed: $!" unless defined $symlinkcpan; eval { File::Path::mkpath($symlinkcpan); }; if ($@) { $seconderror = $@; } else { $CPAN::Frontend->mywarn(qq{ Working directory $symlinkcpan created. }); } } unless (-d $dotcpan) { my $mess = qq{ Your configuration suggests "$dotcpan" as your CPAN.pm working directory. I could not create this directory due to this error: $firsterror\n}; $mess .= qq{ As "$dotcpan" is a symlink to "$symlinkcpan", I tried to create that, but I failed with this error: $seconderror } if $seconderror; $mess .= qq{ Please make sure the directory exists and is writable. }; $CPAN::Frontend->mywarn($mess); return suggest_myconfig; } } # $@ after eval mkpath $dotcpan if (0) { # to test what happens when a race condition occurs for (reverse 1..10) { print $_, "\n"; sleep 1; } } # locking if (!$RUN_DEGRADED && !$self->{LOCKFH}) { my $fh; unless ($fh = FileHandle->new("+>>$lockfile")) { $CPAN::Frontend->mywarn(qq{ Your configuration suggests that CPAN.pm should use a working directory of $CPAN::Config->{cpan_home} Unfortunately we could not create the lock file $lockfile due to '$!'. Please make sure that the configuration variable \$CPAN::Config->{cpan_home} points to a directory where you can write a .lock file. You can set this variable in either a CPAN/MyConfig.pm or a CPAN/Config.pm in your \@INC path; }); return suggest_myconfig; } my $sleep = 1; while (!CPAN::_flock($fh, LOCK_EX|LOCK_NB)) { my $err = $! || "unknown error"; if ($sleep>3) { $CPAN::Frontend->mydie("Could not lock '$lockfile' with flock: $err; giving up\n"); } $CPAN::Frontend->mysleep($sleep+=0.1); $CPAN::Frontend->mywarn("Could not lock '$lockfile' with flock: $err; retrying\n"); } seek $fh, 0, 0; truncate $fh, 0; $fh->autoflush(1); $fh->print($$, "\n"); $fh->print(hostname(), "\n"); $self->{LOCK} = $lockfile; $self->{LOCKFH} = $fh; } $SIG{TERM} = sub { my $sig = shift; &cleanup; $CPAN::Frontend->mydie("Got SIG$sig, leaving"); }; $SIG{INT} = sub { # no blocks!!! my $sig = shift; &cleanup if $Signal; die "Got yet another signal" if $Signal > 1; $CPAN::Frontend->mydie("Got another SIG$sig") if $Signal; $CPAN::Frontend->mywarn("Caught SIG$sig, trying to continue\n"); $Signal++; }; # From: Larry Wall <larry@wall.org> # Subject: Re: deprecating SIGDIE # To: perl5-porters@perl.org # Date: Thu, 30 Sep 1999 14:58:40 -0700 (PDT) # # The original intent of __DIE__ was only to allow you to substitute one # kind of death for another on an application-wide basis without respect # to whether you were in an eval or not. As a global backstop, it should # not be used any more lightly (or any more heavily :-) than class # UNIVERSAL. Any attempt to build a general exception model on it should # be politely squashed. Any bug that causes every eval {} to have to be # modified should be not so politely squashed. # # Those are my current opinions. It is also my opinion that polite # arguments degenerate to personal arguments far too frequently, and that # when they do, it's because both people wanted it to, or at least didn't # sufficiently want it not to. # # Larry # global backstop to cleanup if we should really die $SIG{__DIE__} = \&cleanup; $self->debug("Signal handler set.") if $CPAN::DEBUG; } #-> sub CPAN::DESTROY ; sub DESTROY { &cleanup; # need an eval? } #-> sub CPAN::anycwd ; sub anycwd () { my $getcwd; $getcwd = $CPAN::Config->{'getcwd'} || 'cwd'; CPAN->$getcwd(); } #-> sub CPAN::cwd ; sub cwd {Cwd::cwd();} #-> sub CPAN::getcwd ; sub getcwd {Cwd::getcwd();} #-> sub CPAN::fastcwd ; sub fastcwd {Cwd::fastcwd();} #-> sub CPAN::getdcwd ; sub getdcwd {Cwd::getdcwd();} #-> sub CPAN::backtickcwd ; sub backtickcwd {my $cwd = `cwd`; chomp $cwd; $cwd} # Adapted from Probe::Perl #-> sub CPAN::_perl_is_same sub _perl_is_same { my ($perl) = @_; return MM->maybe_command($perl) && `$perl -MConfig=myconfig -e print -e myconfig` eq Config->myconfig; } # Adapted in part from Probe::Perl #-> sub CPAN::find_perl ; sub find_perl () { if ( File::Spec->file_name_is_absolute($^X) ) { return $^X; } else { my $exe = $Config::Config{exe_ext}; my @candidates = ( File::Spec->catfile($CPAN::iCwd,$^X), $Config::Config{'perlpath'}, ); for my $perl_name ($^X, 'perl', 'perl5', "perl$]") { for my $path (File::Spec->path(), $Config::Config{'binexp'}) { if ( defined($path) && length $path && -d $path ) { my $perl = File::Spec->catfile($path,$perl_name); push @candidates, $perl; # try with extension if not provided already if ($^O eq 'VMS') { # VMS might have a file version at the end push @candidates, $perl . $exe unless $perl =~ m/$exe(;\d+)?$/i; } elsif (defined $exe && length $exe) { push @candidates, $perl . $exe unless $perl =~ m/$exe$/i; } } } } for my $perl ( @candidates ) { if (MM->maybe_command($perl) && _perl_is_same($perl)) { $^X = $perl; return $perl; } } } return $^X; # default fall back } #-> sub CPAN::exists ; sub exists { my($mgr,$class,$id) = @_; CPAN::HandleConfig->load unless $CPAN::Config_loaded++; CPAN::Index->reload; ### Carp::croak "exists called without class argument" unless $class; $id ||= ""; $id =~ s/:+/::/g if $class eq "CPAN::Module"; my $exists; if (CPAN::_sqlite_running) { $exists = (exists $META->{readonly}{$class}{$id} or $CPAN::SQLite->set($class, $id)); } else { $exists = exists $META->{readonly}{$class}{$id}; } $exists ||= exists $META->{readwrite}{$class}{$id}; # unsafe meta access, ok } #-> sub CPAN::delete ; sub delete { my($mgr,$class,$id) = @_; delete $META->{readonly}{$class}{$id}; # unsafe meta access, ok delete $META->{readwrite}{$class}{$id}; # unsafe meta access, ok } #-> sub CPAN::has_usable # has_inst is sometimes too optimistic, we should replace it with this # has_usable whenever a case is given sub has_usable { my($self,$mod,$message) = @_; return 1 if $HAS_USABLE->{$mod}; my $has_inst = $self->has_inst($mod,$message); return unless $has_inst; my $usable; $usable = { # # most of these subroutines warn on the frontend, then # die if the installed version is unusable for some # reason; has_usable() then returns false when it caught # an exception, otherwise returns true and caches that; # 'CPAN::Meta' => [ sub { require CPAN::Meta; unless (CPAN::Version->vge(CPAN::Meta->VERSION, 2.110350)) { for ("Will not use CPAN::Meta, need version 2.110350\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'CPAN::Meta::Requirements' => [ sub { if (defined $CPAN::Meta::Requirements::VERSION && CPAN::Version->vlt($CPAN::Meta::Requirements::VERSION, "2.120920") ) { delete $INC{"CPAN/Meta/Requirements.pm"}; } require CPAN::Meta::Requirements; unless (CPAN::Version->vge(CPAN::Meta::Requirements->VERSION, 2.120920)) { for ("Will not use CPAN::Meta::Requirements, need version 2.120920\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'CPAN::Reporter' => [ sub { if (defined $CPAN::Reporter::VERSION && CPAN::Version->vlt($CPAN::Reporter::VERSION, "1.2011") ) { delete $INC{"CPAN/Reporter.pm"}; } require CPAN::Reporter; unless (CPAN::Version->vge(CPAN::Reporter->VERSION, "1.2011")) { for ("Will not use CPAN::Reporter, need version 1.2011\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], LWP => [ # we frequently had "Can't locate object # method "new" via package "LWP::UserAgent" at # (eval 69) line 2006 sub {require LWP}, sub {require LWP::UserAgent}, sub {require HTTP::Request}, sub {require URI::URL; unless (CPAN::Version->vge(URI::URL::->VERSION,0.08)) { for ("Will not use URI::URL, need 0.08\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'Net::FTP' => [ sub { my $var = $CPAN::Config->{ftp_proxy} || $ENV{ftp_proxy}; if ($var and $var =~ /^http:/i) { # rt #110833 for ("Net::FTP cannot handle http proxy") { $CPAN::Frontend->mywarn($_); die $_; } } }, sub {require Net::FTP}, sub {require Net::Config}, ], 'IO::Socket::SSL' => [ sub { require IO::Socket::SSL; unless (CPAN::Version->vge(IO::Socket::SSL::->VERSION,1.56)) { for ("Will not use IO::Socket::SSL, need 1.56\n") { $CPAN::Frontend->mywarn($_); die $_; } } } ], 'Net::SSLeay' => [ sub { require Net::SSLeay; unless (CPAN::Version->vge(Net::SSLeay::->VERSION,1.49)) { for ("Will not use Net::SSLeay, need 1.49\n") { $CPAN::Frontend->mywarn($_); die $_; } } } ], 'HTTP::Tiny' => [ sub { require HTTP::Tiny; unless (CPAN::Version->vge(HTTP::Tiny->VERSION, 0.005)) { for ("Will not use HTTP::Tiny, need version 0.005\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'File::HomeDir' => [ sub {require File::HomeDir; unless (CPAN::Version->vge(File::HomeDir::->VERSION, 0.52)) { for ("Will not use File::HomeDir, need 0.52\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ], 'Archive::Tar' => [ sub {require Archive::Tar; my $demand = "1.50"; unless (CPAN::Version->vge(Archive::Tar::->VERSION, $demand)) { my $atv = Archive::Tar->VERSION; for ("You have Archive::Tar $atv, but $demand or later is recommended. Please upgrade.\n") { $CPAN::Frontend->mywarn($_); # don't die, because we may need # Archive::Tar to upgrade } } }, ], 'File::Temp' => [ # XXX we should probably delete from # %INC too so we can load after we # installed a new enough version -- # I'm not sure. sub {require File::Temp; unless (CPAN::Version->vge(File::Temp::->VERSION,0.16)) { for ("Will not use File::Temp, need 0.16\n") { $CPAN::Frontend->mywarn($_); die $_; } } }, ] }; if ($usable->{$mod}) { local @INC = @INC; pop @INC if $INC[-1] eq '.'; for my $c (0..$#{$usable->{$mod}}) { my $code = $usable->{$mod}[$c]; my $ret = eval { &$code() }; $ret = "" unless defined $ret; if ($@) { # warn "DEBUG: c[$c]\$\@[$@]ret[$ret]"; return; } } } return $HAS_USABLE->{$mod} = 1; } sub frontend { shift; $CPAN::Frontend = shift if @_; $CPAN::Frontend; } sub use_inst { my ($self, $module) = @_; unless ($self->has_inst($module)) { $self->frontend->mydie("$module not installed, cannot continue"); } } #-> sub CPAN::has_inst sub has_inst { my($self,$mod,$message) = @_; Carp::croak("CPAN->has_inst() called without an argument") unless defined $mod; my %dont = map { $_ => 1 } keys %{$CPAN::META->{dontload_hash}||{}}, keys %{$CPAN::Config->{dontload_hash}||{}}, @{$CPAN::Config->{dontload_list}||[]}; if (defined $message && $message eq "no" # as far as I remember only used by Nox || $dont{$mod} ) { $CPAN::META->{dontload_hash}{$mod}||=1; # unsafe meta access, ok return 0; } local @INC = @INC; pop @INC if $INC[-1] eq '.'; my $file = $mod; my $obj; $file =~ s|::|/|g; $file .= ".pm"; if ($INC{$file}) { # checking %INC is wrong, because $INC{LWP} may be true # although $INC{"URI/URL.pm"} may have failed. But as # I really want to say "blah loaded OK", I have to somehow # cache results. ### warn "$file in %INC"; #debug return 1; } elsif (eval { require $file }) { # eval is good: if we haven't yet read the database it's # perfect and if we have installed the module in the meantime, # it tries again. The second require is only a NOOP returning # 1 if we had success, otherwise it's retrying my $mtime = (stat $INC{$file})[9]; # privileged files loaded by has_inst; Note: we use $mtime # as a proxy for a checksum. $CPAN::Shell::reload->{$file} = $mtime; my $v = eval "\$$mod\::VERSION"; $v = $v ? " (v$v)" : ""; CPAN::Shell->optprint("load_module","CPAN: $mod loaded ok$v\n"); if ($mod eq "CPAN::WAIT") { push @CPAN::Shell::ISA, 'CPAN::WAIT'; } return 1; } elsif ($mod eq "Net::FTP") { $CPAN::Frontend->mywarn(qq{ Please, install Net::FTP as soon as possible. CPAN.pm installs it for you if you just type install Bundle::libnet }) unless $Have_warned->{"Net::FTP"}++; $CPAN::Frontend->mysleep(3); } elsif ($mod eq "Digest::SHA") { if ($Have_warned->{"Digest::SHA"}++) { $CPAN::Frontend->mywarn(qq{CPAN: checksum security checks disabled }. qq{because Digest::SHA not installed.\n}); } else { $CPAN::Frontend->mywarn(qq{ CPAN: checksum security checks disabled because Digest::SHA not installed. Please consider installing the Digest::SHA module. }); $CPAN::Frontend->mysleep(2); } } elsif ($mod eq "Module::Signature") { # NOT prefs_lookup, we are not a distro my $check_sigs = $CPAN::Config->{check_sigs}; if (not $check_sigs) { # they do not want us:-( } elsif (not $Have_warned->{"Module::Signature"}++) { # No point in complaining unless the user can # reasonably install and use it. if (eval { require Crypt::OpenPGP; 1 } || ( defined $CPAN::Config->{'gpg'} && $CPAN::Config->{'gpg'} =~ /\S/ ) ) { $CPAN::Frontend->mywarn(qq{ CPAN: Module::Signature security checks disabled because Module::Signature not installed. Please consider installing the Module::Signature module. You may also need to be able to connect over the Internet to the public key servers like pool.sks-keyservers.net or pgp.mit.edu. }); $CPAN::Frontend->mysleep(2); } } } else { delete $INC{$file}; # if it inc'd LWP but failed during, say, URI } return 0; } #-> sub CPAN::instance ; sub instance { my($mgr,$class,$id) = @_; CPAN::Index->reload; $id ||= ""; # unsafe meta access, ok? return $META->{readwrite}{$class}{$id} if exists $META->{readwrite}{$class}{$id}; $META->{readwrite}{$class}{$id} ||= $class->new(ID => $id); } #-> sub CPAN::new ; sub new { bless {}, shift; } #-> sub CPAN::_exit_messages ; sub _exit_messages { my ($self) = @_; $self->{exit_messages} ||= []; } #-> sub CPAN::cleanup ; sub cleanup { # warn "cleanup called with arg[@_] End[$CPAN::End] Signal[$Signal]"; local $SIG{__DIE__} = ''; my($message) = @_; my $i = 0; my $ineval = 0; my($subroutine); while ((undef,undef,undef,$subroutine) = caller(++$i)) { $ineval = 1, last if $subroutine eq '(eval)'; } return if $ineval && !$CPAN::End; return unless defined $META->{LOCK}; return unless -f $META->{LOCK}; $META->savehist; $META->{cachemgr} ||= CPAN::CacheMgr->new('atexit'); close $META->{LOCKFH}; unlink $META->{LOCK}; # require Carp; # Carp::cluck("DEBUGGING"); if ( $CPAN::CONFIG_DIRTY ) { $CPAN::Frontend->mywarn("Warning: Configuration not saved.\n"); } $CPAN::Frontend->myprint("Lockfile removed.\n"); for my $msg ( @{ $META->_exit_messages } ) { $CPAN::Frontend->myprint($msg); } } #-> sub CPAN::readhist sub readhist { my($self,$term,$histfile) = @_; my $histsize = $CPAN::Config->{'histsize'} || 100; $term->Attribs->{'MaxHistorySize'} = $histsize if (defined($term->Attribs->{'MaxHistorySize'})); my($fh) = FileHandle->new; open $fh, "<$histfile" or return; local $/ = "\n"; while (<$fh>) { chomp; $term->AddHistory($_); } close $fh; } #-> sub CPAN::savehist sub savehist { my($self) = @_; my($histfile,$histsize); unless ($histfile = $CPAN::Config->{'histfile'}) { $CPAN::Frontend->mywarn("No history written (no histfile specified).\n"); return; } $histsize = $CPAN::Config->{'histsize'} || 100; if ($CPAN::term) { unless ($CPAN::term->can("GetHistory")) { $CPAN::Frontend->mywarn("Terminal does not support GetHistory.\n"); return; } } else { return; } my @h = $CPAN::term->GetHistory; splice @h, 0, @h-$histsize if @h>$histsize; my($fh) = FileHandle->new; open $fh, ">$histfile" or $CPAN::Frontend->mydie("Couldn't open >$histfile: $!"); local $\ = local $, = "\n"; print $fh @h; close $fh; } #-> sub CPAN::is_tested sub is_tested { my($self,$what,$when) = @_; unless ($what) { Carp::cluck("DEBUG: empty what"); return; } $self->{is_tested}{$what} = $when; } #-> sub CPAN::reset_tested # forget all distributions tested -- resets what gets included in PERL5LIB sub reset_tested { my ($self) = @_; $self->{is_tested} = {}; } #-> sub CPAN::is_installed # unsets the is_tested flag: as soon as the thing is installed, it is # not needed in set_perl5lib anymore sub is_installed { my($self,$what) = @_; delete $self->{is_tested}{$what}; } sub _list_sorted_descending_is_tested { my($self) = @_; my $foul = 0; my @sorted = sort { ($self->{is_tested}{$b}||0) <=> ($self->{is_tested}{$a}||0) } grep { if ($foul){ 0 } elsif (-e) { 1 } else { $foul = $_; 0 } } keys %{$self->{is_tested}}; if ($foul) { $CPAN::Frontend->mywarn("Lost build_dir detected ($foul), giving up all cached test results of currently running session.\n"); for my $dbd (sort keys %{$self->{is_tested}}) { # distro-build-dir SEARCH: for my $d (sort { $a->id cmp $b->id } $CPAN::META->all_objects("CPAN::Distribution")) { if ($d->{build_dir} && $d->{build_dir} eq $dbd) { $CPAN::Frontend->mywarn(sprintf "Flushing cache for %s\n", $d->pretty_id); $d->fforce(""); last SEARCH; } } delete $self->{is_tested}{$dbd}; } return (); } else { return @sorted; } } #-> sub CPAN::set_perl5lib # Notes on max environment variable length: # - Win32 : XP or later, 8191; Win2000 or NT4, 2047 { my $fh; sub set_perl5lib { my($self,$for) = @_; unless ($for) { (undef,undef,undef,$for) = caller(1); $for =~ s/.*://; } $self->{is_tested} ||= {}; return unless %{$self->{is_tested}}; my $env = $ENV{PERL5LIB}; $env = $ENV{PERLLIB} unless defined $env; my @env; push @env, split /\Q$Config::Config{path_sep}\E/, $env if defined $env and length $env; #my @dirs = map {("$_/blib/arch", "$_/blib/lib")} keys %{$self->{is_tested}}; #$CPAN::Frontend->myprint("Prepending @dirs to PERL5LIB.\n"); my @dirs = map {("$_/blib/arch", "$_/blib/lib")} $self->_list_sorted_descending_is_tested; return if !@dirs; if (@dirs < 12) { $CPAN::Frontend->optprint('perl5lib', "Prepending @dirs to PERL5LIB for '$for'\n"); $ENV{PERL5LIB} = join $Config::Config{path_sep}, @dirs, @env; } elsif (@dirs < 24 ) { my @d = map {my $cp = $_; $cp =~ s/^\Q$CPAN::Config->{build_dir}\E/%BUILDDIR%/; $cp } @dirs; $CPAN::Frontend->optprint('perl5lib', "Prepending @d to PERL5LIB; ". "%BUILDDIR%=$CPAN::Config->{build_dir} ". "for '$for'\n" ); $ENV{PERL5LIB} = join $Config::Config{path_sep}, @dirs, @env; } else { my $cnt = keys %{$self->{is_tested}}; my $newenv = join $Config::Config{path_sep}, @dirs, @env; $CPAN::Frontend->optprint('perl5lib', sprintf ("Prepending blib/arch and blib/lib of ". "%d build dirs to PERL5LIB, reaching size %d; ". "for '%s'\n", $cnt, length($newenv), $for) ); $ENV{PERL5LIB} = $newenv; } }} 1; __END__ =head1 NAME CPAN - query, download and build perl modules from CPAN sites =head1 SYNOPSIS Interactive mode: perl -MCPAN -e shell --or-- cpan Basic commands: # Modules: cpan> install Acme::Meta # in the shell CPAN::Shell->install("Acme::Meta"); # in perl # Distributions: cpan> install NWCLARK/Acme-Meta-0.02.tar.gz # in the shell CPAN::Shell-> install("NWCLARK/Acme-Meta-0.02.tar.gz"); # in perl # module objects: $mo = CPAN::Shell->expandany($mod); $mo = CPAN::Shell->expand("Module",$mod); # same thing # distribution objects: $do = CPAN::Shell->expand("Module",$mod)->distribution; $do = CPAN::Shell->expandany($distro); # same thing $do = CPAN::Shell->expand("Distribution", $distro); # same thing =head1 DESCRIPTION The CPAN module automates or at least simplifies the make and install of perl modules and extensions. It includes some primitive searching capabilities and knows how to use LWP, HTTP::Tiny, Net::FTP and certain external download clients to fetch distributions from the net. These are fetched from one or more mirrored CPAN (Comprehensive Perl Archive Network) sites and unpacked in a dedicated directory. The CPAN module also supports named and versioned I<bundles> of modules. Bundles simplify handling of sets of related modules. See Bundles below. The package contains a session manager and a cache manager. The session manager keeps track of what has been fetched, built, and installed in the current session. The cache manager keeps track of the disk space occupied by the make processes and deletes excess space using a simple FIFO mechanism. All methods provided are accessible in a programmer style and in an interactive shell style. =head2 CPAN::shell([$prompt, $command]) Starting Interactive Mode Enter interactive mode by running perl -MCPAN -e shell or cpan which puts you into a readline interface. If C<Term::ReadKey> and either of C<Term::ReadLine::Perl> or C<Term::ReadLine::Gnu> are installed, history and command completion are supported. Once at the command line, type C<h> for one-page help screen; the rest should be self-explanatory. The function call C<shell> takes two optional arguments: one the prompt, the second the default initial command line (the latter only works if a real ReadLine interface module is installed). The most common uses of the interactive modes are =over 2 =item Searching for authors, bundles, distribution files and modules There are corresponding one-letter commands C<a>, C<b>, C<d>, and C<m> for each of the four categories and another, C<i> for any of the mentioned four. Each of the four entities is implemented as a class with slightly differing methods for displaying an object. Arguments to these commands are either strings exactly matching the identification string of an object, or regular expressions matched case-insensitively against various attributes of the objects. The parser only recognizes a regular expression when you enclose it with slashes. The principle is that the number of objects found influences how an item is displayed. If the search finds one item, the result is displayed with the rather verbose method C<as_string>, but if more than one is found, each object is displayed with the terse method C<as_glimpse>. Examples: cpan> m Acme::MetaSyntactic Module id = Acme::MetaSyntactic CPAN_USERID BOOK (Philippe Bruhat (BooK) <[...]>) CPAN_VERSION 0.99 CPAN_FILE B/BO/BOOK/Acme-MetaSyntactic-0.99.tar.gz UPLOAD_DATE 2006-11-06 MANPAGE Acme::MetaSyntactic - Themed metasyntactic variables names INST_FILE /usr/local/lib/perl/5.10.0/Acme/MetaSyntactic.pm INST_VERSION 0.99 cpan> a BOOK Author id = BOOK EMAIL [...] FULLNAME Philippe Bruhat (BooK) cpan> d BOOK/Acme-MetaSyntactic-0.99.tar.gz Distribution id = B/BO/BOOK/Acme-MetaSyntactic-0.99.tar.gz CPAN_USERID BOOK (Philippe Bruhat (BooK) <[...]>) CONTAINSMODS Acme::MetaSyntactic Acme::MetaSyntactic::Alias [...] UPLOAD_DATE 2006-11-06 cpan> m /lorem/ Module = Acme::MetaSyntactic::loremipsum (BOOK/Acme-MetaSyntactic-0.99.tar.gz) Module Text::Lorem (ADEOLA/Text-Lorem-0.3.tar.gz) Module Text::Lorem::More (RKRIMEN/Text-Lorem-More-0.12.tar.gz) Module Text::Lorem::More::Source (RKRIMEN/Text-Lorem-More-0.12.tar.gz) cpan> i /berlin/ Distribution BEATNIK/Filter-NumberLines-0.02.tar.gz Module = DateTime::TimeZone::Europe::Berlin (DROLSKY/DateTime-TimeZone-0.7904.tar.gz) Module Filter::NumberLines (BEATNIK/Filter-NumberLines-0.02.tar.gz) Author [...] The examples illustrate several aspects: the first three queries target modules, authors, or distros directly and yield exactly one result. The last two use regular expressions and yield several results. The last one targets all of bundles, modules, authors, and distros simultaneously. When more than one result is available, they are printed in one-line format. =item C<get>, C<make>, C<test>, C<install>, C<clean> modules or distributions These commands take any number of arguments and investigate what is necessary to perform the action. Argument processing is as follows: known module name in format Foo/Bar.pm module other embedded slash distribution - with trailing slash dot directory enclosing slashes regexp known module name in format Foo::Bar module If the argument is a distribution file name (recognized by embedded slashes), it is processed. If it is a module, CPAN determines the distribution file in which this module is included and processes that, following any dependencies named in the module's META.yml or Makefile.PL (this behavior is controlled by the configuration parameter C<prerequisites_policy>). If an argument is enclosed in slashes it is treated as a regular expression: it is expanded and if the result is a single object (distribution, bundle or module), this object is processed. Example: install Dummy::Perl # installs the module install AUXXX/Dummy-Perl-3.14.tar.gz # installs that distribution install /Dummy-Perl-3.14/ # same if the regexp is unambiguous C<get> downloads a distribution file and untars or unzips it, C<make> builds it, C<test> runs the test suite, and C<install> installs it. Any C<make> or C<test> is run unconditionally. An install <distribution_file> is also run unconditionally. But for install <module> CPAN checks whether an install is needed and prints I<module up to date> if the distribution file containing the module doesn't need updating. CPAN also keeps track of what it has done within the current session and doesn't try to build a package a second time regardless of whether it succeeded or not. It does not repeat a test run if the test has been run successfully before. Same for install runs. The C<force> pragma may precede another command (currently: C<get>, C<make>, C<test>, or C<install>) to execute the command from scratch and attempt to continue past certain errors. See the section below on the C<force> and the C<fforce> pragma. The C<notest> pragma skips the test part in the build process. Example: cpan> notest install Tk A C<clean> command results in a make clean being executed within the distribution file's working directory. =item C<readme>, C<perldoc>, C<look> module or distribution C<readme> displays the README file of the associated distribution. C<Look> gets and untars (if not yet done) the distribution file, changes to the appropriate directory and opens a subshell process in that directory. C<perldoc> displays the module's pod documentation in html or plain text format. =item C<ls> author =item C<ls> globbing_expression The first form lists all distribution files in and below an author's CPAN directory as stored in the CHECKSUMS files distributed on CPAN. The listing recurses into subdirectories. The second form limits or expands the output with shell globbing as in the following examples: ls JV/make* ls GSAR/*make* ls */*make* The last example is very slow and outputs extra progress indicators that break the alignment of the result. Note that globbing only lists directories explicitly asked for, for example FOO/* will not list FOO/bar/Acme-Sthg-n.nn.tar.gz. This may be regarded as a bug that may be changed in some future version. =item C<failed> The C<failed> command reports all distributions that failed on one of C<make>, C<test> or C<install> for some reason in the currently running shell session. =item Persistence between sessions If the C<YAML> or the C<YAML::Syck> module is installed a record of the internal state of all modules is written to disk after each step. The files contain a signature of the currently running perl version for later perusal. If the configurations variable C<build_dir_reuse> is set to a true value, then CPAN.pm reads the collected YAML files. If the stored signature matches the currently running perl, the stored state is loaded into memory such that persistence between sessions is effectively established. =item The C<force> and the C<fforce> pragma To speed things up in complex installation scenarios, CPAN.pm keeps track of what it has already done and refuses to do some things a second time. A C<get>, a C<make>, and an C<install> are not repeated. A C<test> is repeated only if the previous test was unsuccessful. The diagnostic message when CPAN.pm refuses to do something a second time is one of I<Has already been >C<unwrapped|made|tested successfully> or something similar. Another situation where CPAN refuses to act is an C<install> if the corresponding C<test> was not successful. In all these cases, the user can override this stubborn behaviour by prepending the command with the word force, for example: cpan> force get Foo cpan> force make AUTHOR/Bar-3.14.tar.gz cpan> force test Baz cpan> force install Acme::Meta Each I<forced> command is executed with the corresponding part of its memory erased. The C<fforce> pragma is a variant that emulates a C<force get> which erases the entire memory followed by the action specified, effectively restarting the whole get/make/test/install procedure from scratch. =item Lockfile Interactive sessions maintain a lockfile, by default C<~/.cpan/.lock>. Batch jobs can run without a lockfile and not disturb each other. The shell offers to run in I<downgraded mode> when another process is holding the lockfile. This is an experimental feature that is not yet tested very well. This second shell then does not write the history file, does not use the metadata file, and has a different prompt. =item Signals CPAN.pm installs signal handlers for SIGINT and SIGTERM. While you are in the cpan-shell, it is intended that you can press C<^C> anytime and return to the cpan-shell prompt. A SIGTERM will cause the cpan-shell to clean up and leave the shell loop. You can emulate the effect of a SIGTERM by sending two consecutive SIGINTs, which usually means by pressing C<^C> twice. CPAN.pm ignores SIGPIPE. If the user sets C<inactivity_timeout>, a SIGALRM is used during the run of the C<perl Makefile.PL> or C<perl Build.PL> subprocess. A SIGALRM is also used during module version parsing, and is controlled by C<version_timeout>. =back =head2 CPAN::Shell The commands available in the shell interface are methods in the package CPAN::Shell. If you enter the shell command, your input is split by the Text::ParseWords::shellwords() routine, which acts like most shells do. The first word is interpreted as the method to be invoked, and the rest of the words are treated as the method's arguments. Continuation lines are supported by ending a line with a literal backslash. =head2 autobundle C<autobundle> writes a bundle file into the C<$CPAN::Config-E<gt>{cpan_home}/Bundle> directory. The file contains a list of all modules that are both available from CPAN and currently installed within @INC. Duplicates of each distribution are suppressed. The name of the bundle file is based on the current date and a counter, e.g. F<Bundle/Snapshot_2012_05_21_00.pm>. This is installed again by running C<cpan Bundle::Snapshot_2012_05_21_00>, or installing C<Bundle::Snapshot_2012_05_21_00> from the CPAN shell. Return value: path to the written file. =head2 hosts Note: this feature is still in alpha state and may change in future versions of CPAN.pm This commands provides a statistical overview over recent download activities. The data for this is collected in the YAML file C<FTPstats.yml> in your C<cpan_home> directory. If no YAML module is configured or YAML not installed, no stats are provided. =over =item install_tested Install all distributions that have been tested successfully but have not yet been installed. See also C<is_tested>. =item is_tested List all build directories of distributions that have been tested successfully but have not yet been installed. See also C<install_tested>. =back =head2 mkmyconfig mkmyconfig() writes your own CPAN::MyConfig file into your C<~/.cpan/> directory so that you can save your own preferences instead of the system-wide ones. =head2 r [Module|/Regexp/]... scans current perl installation for modules that have a newer version available on CPAN and provides a list of them. If called without argument, all potential upgrades are listed; if called with arguments the list is filtered to the modules and regexps given as arguments. The listing looks something like this: Package namespace installed latest in CPAN file CPAN 1.94_64 1.9600 ANDK/CPAN-1.9600.tar.gz CPAN::Reporter 1.1801 1.1902 DAGOLDEN/CPAN-Reporter-1.1902.tar.gz YAML 0.70 0.73 INGY/YAML-0.73.tar.gz YAML::Syck 1.14 1.17 AVAR/YAML-Syck-1.17.tar.gz YAML::Tiny 1.44 1.50 ADAMK/YAML-Tiny-1.50.tar.gz CGI 3.43 3.55 MARKSTOS/CGI.pm-3.55.tar.gz Module::Build::YAML 1.40 1.41 DAGOLDEN/Module-Build-0.3800.tar.gz TAP::Parser::Result::YAML 3.22 3.23 ANDYA/Test-Harness-3.23.tar.gz YAML::XS 0.34 0.35 INGY/YAML-LibYAML-0.35.tar.gz It suppresses duplicates in the column C<in CPAN file> such that distributions with many upgradeable modules are listed only once. Note that the list is not sorted. =head2 recent ***EXPERIMENTAL COMMAND*** The C<recent> command downloads a list of recent uploads to CPAN and displays them I<slowly>. While the command is running, a $SIG{INT} exits the loop after displaying the current item. B<Note>: This command requires XML::LibXML installed. B<Note>: This whole command currently is just a hack and will probably change in future versions of CPAN.pm, but the general approach will likely remain. B<Note>: See also L<smoke> =head2 recompile recompile() is a special command that takes no argument and runs the make/test/install cycle with brute force over all installed dynamically loadable extensions (a.k.a. XS modules) with 'force' in effect. The primary purpose of this command is to finish a network installation. Imagine you have a common source tree for two different architectures. You decide to do a completely independent fresh installation. You start on one architecture with the help of a Bundle file produced earlier. CPAN installs the whole Bundle for you, but when you try to repeat the job on the second architecture, CPAN responds with a C<"Foo up to date"> message for all modules. So you invoke CPAN's recompile on the second architecture and you're done. Another popular use for C<recompile> is to act as a rescue in case your perl breaks binary compatibility. If one of the modules that CPAN uses is in turn depending on binary compatibility (so you cannot run CPAN commands), then you should try the CPAN::Nox module for recovery. =head2 report Bundle|Distribution|Module The C<report> command temporarily turns on the C<test_report> config variable, then runs the C<force test> command with the given arguments. The C<force> pragma reruns the tests and repeats every step that might have failed before. =head2 smoke ***EXPERIMENTAL COMMAND*** B<*** WARNING: this command downloads and executes software from CPAN to your computer of completely unknown status. You should never do this with your normal account and better have a dedicated well separated and secured machine to do this. ***> The C<smoke> command takes the list of recent uploads to CPAN as provided by the C<recent> command and tests them all. While the command is running $SIG{INT} is defined to mean that the current item shall be skipped. B<Note>: This whole command currently is just a hack and will probably change in future versions of CPAN.pm, but the general approach will likely remain. B<Note>: See also L<recent> =head2 upgrade [Module|/Regexp/]... The C<upgrade> command first runs an C<r> command with the given arguments and then installs the newest versions of all modules that were listed by that. =head2 The four C<CPAN::*> Classes: Author, Bundle, Module, Distribution Although it may be considered internal, the class hierarchy does matter for both users and programmer. CPAN.pm deals with the four classes mentioned above, and those classes all share a set of methods. Classical single polymorphism is in effect. A metaclass object registers all objects of all kinds and indexes them with a string. The strings referencing objects have a separated namespace (well, not completely separated): Namespace Class words containing a "/" (slash) Distribution words starting with Bundle:: Bundle everything else Module or Author Modules know their associated Distribution objects. They always refer to the most recent official release. Developers may mark their releases as unstable development versions (by inserting an underscore into the module version number which will also be reflected in the distribution name when you run 'make dist'), so the really hottest and newest distribution is not always the default. If a module Foo circulates on CPAN in both version 1.23 and 1.23_90, CPAN.pm offers a convenient way to install version 1.23 by saying install Foo This would install the complete distribution file (say BAR/Foo-1.23.tar.gz) with all accompanying material. But if you would like to install version 1.23_90, you need to know where the distribution file resides on CPAN relative to the authors/id/ directory. If the author is BAR, this might be BAR/Foo-1.23_90.tar.gz; so you would have to say install BAR/Foo-1.23_90.tar.gz The first example will be driven by an object of the class CPAN::Module, the second by an object of class CPAN::Distribution. =head2 Integrating local directories Note: this feature is still in alpha state and may change in future versions of CPAN.pm Distribution objects are normally distributions from the CPAN, but there is a slightly degenerate case for Distribution objects, too, of projects held on the local disk. These distribution objects have the same name as the local directory and end with a dot. A dot by itself is also allowed for the current directory at the time CPAN.pm was used. All actions such as C<make>, C<test>, and C<install> are applied directly to that directory. This gives the command C<cpan .> an interesting touch: while the normal mantra of installing a CPAN module without CPAN.pm is one of perl Makefile.PL perl Build.PL ( go and get prerequisites ) make ./Build make test ./Build test make install ./Build install the command C<cpan .> does all of this at once. It figures out which of the two mantras is appropriate, fetches and installs all prerequisites, takes care of them recursively, and finally finishes the installation of the module in the current directory, be it a CPAN module or not. The typical usage case is for private modules or working copies of projects from remote repositories on the local disk. =head2 Redirection The usual shell redirection symbols C< | > and C<< > >> are recognized by the cpan shell B<only when surrounded by whitespace>. So piping to pager or redirecting output into a file works somewhat as in a normal shell, with the stipulation that you must type extra spaces. =head2 Plugin support ***EXPERIMENTAL*** Plugins are objects that implement any of currently eight methods: pre_get post_get pre_make post_make pre_test post_test pre_install post_install The C<plugin_list> configuration parameter holds a list of strings of the form Modulename=arg0,arg1,arg2,arg3,... eg: CPAN::Plugin::Flurb=dir,/opt/pkgs/flurb/raw,verbose,1 At run time, each listed plugin is instantiated as a singleton object by running the equivalent of this pseudo code: my $plugin = <string representation from config>; <generate Modulename and arguments from $plugin>; my $p = $instance{$plugin} ||= Modulename->new($arg0,$arg1,...); The generated singletons are kept around from instantiation until the end of the shell session. <plugin_list> can be reconfigured at any time at run time. While the cpan shell is running, it checks all activated plugins at each of the 8 reference points listed above and runs the respective method if it is implemented for that object. The method is called with the active CPAN::Distribution object passed in as an argument. =head1 CONFIGURATION When the CPAN module is used for the first time, a configuration dialogue tries to determine a couple of site specific options. The result of the dialog is stored in a hash reference C< $CPAN::Config > in a file CPAN/Config.pm. Default values defined in the CPAN/Config.pm file can be overridden in a user specific file: CPAN/MyConfig.pm. Such a file is best placed in C<$HOME/.cpan/CPAN/MyConfig.pm>, because C<$HOME/.cpan> is added to the search path of the CPAN module before the use() or require() statements. The mkmyconfig command writes this file for you. The C<o conf> command has various bells and whistles: =over =item completion support If you have a ReadLine module installed, you can hit TAB at any point of the commandline and C<o conf> will offer you completion for the built-in subcommands and/or config variable names. =item displaying some help: o conf help Displays a short help =item displaying current values: o conf [KEY] Displays the current value(s) for this config variable. Without KEY, displays all subcommands and config variables. Example: o conf shell If KEY starts and ends with a slash, the string in between is treated as a regular expression and only keys matching this regexp are displayed Example: o conf /color/ =item changing of scalar values: o conf KEY VALUE Sets the config variable KEY to VALUE. The empty string can be specified as usual in shells, with C<''> or C<""> Example: o conf wget /usr/bin/wget =item changing of list values: o conf KEY SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST If a config variable name ends with C<list>, it is a list. C<o conf KEY shift> removes the first element of the list, C<o conf KEY pop> removes the last element of the list. C<o conf KEYS unshift LIST> prepends a list of values to the list, C<o conf KEYS push LIST> appends a list of valued to the list. Likewise, C<o conf KEY splice LIST> passes the LIST to the corresponding splice command. Finally, any other list of arguments is taken as a new list value for the KEY variable discarding the previous value. Examples: o conf urllist unshift http://cpan.dev.local/CPAN o conf urllist splice 3 1 o conf urllist http://cpan1.local http://cpan2.local ftp://ftp.perl.org =item reverting to saved: o conf defaults Reverts all config variables to the state in the saved config file. =item saving the config: o conf commit Saves all config variables to the current config file (CPAN/Config.pm or CPAN/MyConfig.pm that was loaded at start). =back The configuration dialog can be started any time later again by issuing the command C< o conf init > in the CPAN shell. A subset of the configuration dialog can be run by issuing C<o conf init WORD> where WORD is any valid config variable or a regular expression. =head2 Config Variables The following keys in the hash reference $CPAN::Config are currently defined: allow_installing_module_downgrades allow or disallow installing module downgrades allow_installing_outdated_dists allow or disallow installing modules that are indexed in the cpan index pointing to a distro with a higher distro-version number applypatch path to external prg auto_commit commit all changes to config variables to disk build_cache size of cache for directories to build modules build_dir locally accessible directory to build modules build_dir_reuse boolean if distros in build_dir are persistent build_requires_install_policy to install or not to install when a module is only needed for building. yes|no|ask/yes|ask/no bzip2 path to external prg cache_metadata use serializer to cache metadata check_sigs if signatures should be verified cleanup_after_install remove build directory immediately after a successful install and remember that for the duration of the session colorize_debug Term::ANSIColor attributes for debugging output colorize_output boolean if Term::ANSIColor should colorize output colorize_print Term::ANSIColor attributes for normal output colorize_warn Term::ANSIColor attributes for warnings commandnumber_in_prompt boolean if you want to see current command number commands_quote preferred character to use for quoting external commands when running them. Defaults to double quote on Windows, single tick everywhere else; can be set to space to disable quoting connect_to_internet_ok whether to ask if opening a connection is ok before urllist is specified cpan_home local directory reserved for this package curl path to external prg dontload_hash DEPRECATED dontload_list arrayref: modules in the list will not be loaded by the CPAN::has_inst() routine ftp path to external prg ftp_passive if set, the environment variable FTP_PASSIVE is set for downloads ftp_proxy proxy host for ftp requests ftpstats_period max number of days to keep download statistics ftpstats_size max number of items to keep in the download statistics getcwd see below gpg path to external prg gzip location of external program gzip halt_on_failure stop processing after the first failure of queued items or dependencies histfile file to maintain history between sessions histsize maximum number of lines to keep in histfile http_proxy proxy host for http requests inactivity_timeout breaks interactive Makefile.PLs or Build.PLs after this many seconds inactivity. Set to 0 to disable timeouts. index_expire refetch index files after this many days inhibit_startup_message if true, suppress the startup message keep_source_where directory in which to keep the source (if we do) load_module_verbosity report loading of optional modules used by CPAN.pm lynx path to external prg make location of external make program make_arg arguments that should always be passed to 'make' make_install_make_command the make command for running 'make install', for example 'sudo make' make_install_arg same as make_arg for 'make install' makepl_arg arguments passed to 'perl Makefile.PL' mbuild_arg arguments passed to './Build' mbuild_install_arg arguments passed to './Build install' mbuild_install_build_command command to use instead of './Build' when we are in the install stage, for example 'sudo ./Build' mbuildpl_arg arguments passed to 'perl Build.PL' ncftp path to external prg ncftpget path to external prg no_proxy don't proxy to these hosts/domains (comma separated list) pager location of external program more (or any pager) password your password if you CPAN server wants one patch path to external prg patches_dir local directory containing patch files perl5lib_verbosity verbosity level for PERL5LIB additions plugin_list list of active hooks (see Plugin support above and the CPAN::Plugin module) prefer_external_tar per default all untar operations are done with Archive::Tar; by setting this variable to true the external tar command is used if available prefer_installer legal values are MB and EUMM: if a module comes with both a Makefile.PL and a Build.PL, use the former (EUMM) or the latter (MB); if the module comes with only one of the two, that one will be used no matter the setting prerequisites_policy what to do if you are missing module prerequisites ('follow' automatically, 'ask' me, or 'ignore') For 'follow', also sets PERL_AUTOINSTALL and PERL_EXTUTILS_AUTOINSTALL for "--defaultdeps" if not already set prefs_dir local directory to store per-distro build options proxy_user username for accessing an authenticating proxy proxy_pass password for accessing an authenticating proxy pushy_https use https to cpan.org when possible, otherwise use http to cpan.org and issue a warning randomize_urllist add some randomness to the sequence of the urllist recommends_policy whether recommended prerequisites should be included scan_cache controls scanning of cache ('atstart', 'atexit' or 'never') shell your favorite shell show_unparsable_versions boolean if r command tells which modules are versionless show_upload_date boolean if commands should try to determine upload date show_zero_versions boolean if r command tells for which modules $version==0 suggests_policy whether suggested prerequisites should be included tar location of external program tar tar_verbosity verbosity level for the tar command term_is_latin deprecated: if true Unicode is translated to ISO-8859-1 (and nonsense for characters outside latin range) term_ornaments boolean to turn ReadLine ornamenting on/off test_report email test reports (if CPAN::Reporter is installed) trust_test_report_history skip testing when previously tested ok (according to CPAN::Reporter history) unzip location of external program unzip urllist arrayref to nearby CPAN sites (or equivalent locations) urllist_ping_external use external ping command when autoselecting mirrors urllist_ping_verbose increase verbosity when autoselecting mirrors use_prompt_default set PERL_MM_USE_DEFAULT for configure/make/test/install use_sqlite use CPAN::SQLite for metadata storage (fast and lean) username your username if you CPAN server wants one version_timeout stops version parsing after this many seconds. Default is 15 secs. Set to 0 to disable. wait_list arrayref to a wait server to try (See CPAN::WAIT) wget path to external prg yaml_load_code enable YAML code deserialisation via CPAN::DeferredCode yaml_module which module to use to read/write YAML files You can set and query each of these options interactively in the cpan shell with the C<o conf> or the C<o conf init> command as specified below. =over 2 =item C<o conf E<lt>scalar optionE<gt>> prints the current value of the I<scalar option> =item C<o conf E<lt>scalar optionE<gt> E<lt>valueE<gt>> Sets the value of the I<scalar option> to I<value> =item C<o conf E<lt>list optionE<gt>> prints the current value of the I<list option> in MakeMaker's neatvalue format. =item C<o conf E<lt>list optionE<gt> [shift|pop]> shifts or pops the array in the I<list option> variable =item C<o conf E<lt>list optionE<gt> [unshift|push|splice] E<lt>listE<gt>> works like the corresponding perl commands. =item interactive editing: o conf init [MATCH|LIST] Runs an interactive configuration dialog for matching variables. Without argument runs the dialog over all supported config variables. To specify a MATCH the argument must be enclosed by slashes. Examples: o conf init ftp_passive ftp_proxy o conf init /color/ Note: this method of setting config variables often provides more explanation about the functioning of a variable than the manpage. =back =head2 CPAN::anycwd($path): Note on config variable getcwd CPAN.pm changes the current working directory often and needs to determine its own current working directory. By default it uses Cwd::cwd, but if for some reason this doesn't work on your system, configure alternatives according to the following table: =over 4 =item cwd Calls Cwd::cwd =item getcwd Calls Cwd::getcwd =item fastcwd Calls Cwd::fastcwd =item getdcwd Calls Cwd::getdcwd =item backtickcwd Calls the external command cwd. =back =head2 Note on the format of the urllist parameter urllist parameters are URLs according to RFC 1738. We do a little guessing if your URL is not compliant, but if you have problems with C<file> URLs, please try the correct format. Either: file://localhost/whatever/ftp/pub/CPAN/ or file:///home/ftp/pub/CPAN/ =head2 The urllist parameter has CD-ROM support The C<urllist> parameter of the configuration table contains a list of URLs used for downloading. If the list contains any C<file> URLs, CPAN always tries there first. This feature is disabled for index files. So the recommendation for the owner of a CD-ROM with CPAN contents is: include your local, possibly outdated CD-ROM as a C<file> URL at the end of urllist, e.g. o conf urllist push file://localhost/CDROM/CPAN CPAN.pm will then fetch the index files from one of the CPAN sites that come at the beginning of urllist. It will later check for each module to see whether there is a local copy of the most recent version. Another peculiarity of urllist is that the site that we could successfully fetch the last file from automatically gets a preference token and is tried as the first site for the next request. So if you add a new site at runtime it may happen that the previously preferred site will be tried another time. This means that if you want to disallow a site for the next transfer, it must be explicitly removed from urllist. =head2 Maintaining the urllist parameter If you have YAML.pm (or some other YAML module configured in C<yaml_module>) installed, CPAN.pm collects a few statistical data about recent downloads. You can view the statistics with the C<hosts> command or inspect them directly by looking into the C<FTPstats.yml> file in your C<cpan_home> directory. To get some interesting statistics, it is recommended that C<randomize_urllist> be set; this introduces some amount of randomness into the URL selection. =head2 The C<requires> and C<build_requires> dependency declarations Since CPAN.pm version 1.88_51 modules declared as C<build_requires> by a distribution are treated differently depending on the config variable C<build_requires_install_policy>. By setting C<build_requires_install_policy> to C<no>, such a module is not installed. It is only built and tested, and then kept in the list of tested but uninstalled modules. As such, it is available during the build of the dependent module by integrating the path to the C<blib/arch> and C<blib/lib> directories in the environment variable PERL5LIB. If C<build_requires_install_policy> is set to C<yes>, then both modules declared as C<requires> and those declared as C<build_requires> are treated alike. By setting to C<ask/yes> or C<ask/no>, CPAN.pm asks the user and sets the default accordingly. =head2 Configuration of the allow_installing_* parameters The C<allow_installing_*> parameters are evaluated during the C<make> phase. If set to C<yes>, they allow the testing and the installation of the current distro and otherwise have no effect. If set to C<no>, they may abort the build (preventing testing and installing), depending on the contents of the C<blib/> directory. The C<blib/> directory is the directory that holds all the files that would usually be installed in the C<install> phase. C<allow_installing_outdated_dists> compares the C<blib/> directory with the CPAN index. If it finds something there that belongs, according to the index, to a different dist, it aborts the current build. C<allow_installing_module_downgrades> compares the C<blib/> directory with already installed modules, actually their version numbers, as determined by ExtUtils::MakeMaker or equivalent. If a to-be-installed module would downgrade an already installed module, the current build is aborted. An interesting twist occurs when a distroprefs document demands the installation of an outdated dist via goto while C<allow_installing_outdated_dists> forbids it. Without additional provisions, this would let the C<allow_installing_outdated_dists> win and the distroprefs lose. So the proper arrangement in such a case is to write a second distroprefs document for the distro that C<goto> points to and overrule the C<cpanconfig> there. E.g.: --- match: distribution: "^MAUKE/Keyword-Simple-0.04.tar.gz" goto: "MAUKE/Keyword-Simple-0.03.tar.gz" --- match: distribution: "^MAUKE/Keyword-Simple-0.03.tar.gz" cpanconfig: allow_installing_outdated_dists: yes =head2 Configuration for individual distributions (I<Distroprefs>) (B<Note:> This feature has been introduced in CPAN.pm 1.8854) Distributions on CPAN usually behave according to what we call the CPAN mantra. Or since the advent of Module::Build we should talk about two mantras: perl Makefile.PL perl Build.PL make ./Build make test ./Build test make install ./Build install But some modules cannot be built with this mantra. They try to get some extra data from the user via the environment, extra arguments, or interactively--thus disturbing the installation of large bundles like Phalanx100 or modules with many dependencies like Plagger. The distroprefs system of C<CPAN.pm> addresses this problem by allowing the user to specify extra informations and recipes in YAML files to either =over =item pass additional arguments to one of the four commands, =item set environment variables =item instantiate an Expect object that reads from the console, waits for some regular expressions and enters some answers =item temporarily override assorted C<CPAN.pm> configuration variables =item specify dependencies the original maintainer forgot =item disable the installation of an object altogether =back See the YAML and Data::Dumper files that come with the C<CPAN.pm> distribution in the C<distroprefs/> directory for examples. =head2 Filenames The YAML files themselves must have the C<.yml> extension; all other files are ignored (for two exceptions see I<Fallback Data::Dumper and Storable> below). The containing directory can be specified in C<CPAN.pm> in the C<prefs_dir> config variable. Try C<o conf init prefs_dir> in the CPAN shell to set and activate the distroprefs system. Every YAML file may contain arbitrary documents according to the YAML specification, and every document is treated as an entity that can specify the treatment of a single distribution. Filenames can be picked arbitrarily; C<CPAN.pm> always reads all files (in alphabetical order) and takes the key C<match> (see below in I<Language Specs>) as a hashref containing match criteria that determine if the current distribution matches the YAML document or not. =head2 Fallback Data::Dumper and Storable If neither your configured C<yaml_module> nor YAML.pm is installed, CPAN.pm falls back to using Data::Dumper and Storable and looks for files with the extensions C<.dd> or C<.st> in the C<prefs_dir> directory. These files are expected to contain one or more hashrefs. For Data::Dumper generated files, this is expected to be done with by defining C<$VAR1>, C<$VAR2>, etc. The YAML shell would produce these with the command ysh < somefile.yml > somefile.dd For Storable files the rule is that they must be constructed such that C<Storable::retrieve(file)> returns an array reference and the array elements represent one distropref object each. The conversion from YAML would look like so: perl -MYAML=LoadFile -MStorable=nstore -e ' @y=LoadFile(shift); nstore(\@y, shift)' somefile.yml somefile.st In bootstrapping situations it is usually sufficient to translate only a few YAML files to Data::Dumper for crucial modules like C<YAML::Syck>, C<YAML.pm> and C<Expect.pm>. If you prefer Storable over Data::Dumper, remember to pull out a Storable version that writes an older format than all the other Storable versions that will need to read them. =head2 Blueprint The following example contains all supported keywords and structures with the exception of C<eexpect> which can be used instead of C<expect>. --- comment: "Demo" match: module: "Dancing::Queen" distribution: "^CHACHACHA/Dancing-" not_distribution: "\.zip$" perl: "/usr/local/cariba-perl/bin/perl" perlconfig: archname: "freebsd" not_cc: "gcc" env: DANCING_FLOOR: "Shubiduh" disabled: 1 cpanconfig: make: gmake pl: args: - "--somearg=specialcase" env: {} expect: - "Which is your favorite fruit" - "apple\n" make: args: - all - extra-all env: {} expect: [] commandline: "echo SKIPPING make" test: args: [] env: {} expect: [] install: args: [] env: WANT_TO_INSTALL: YES expect: - "Do you really want to install" - "y\n" patches: - "ABCDE/Fedcba-3.14-ABCDE-01.patch" depends: configure_requires: LWP: 5.8 build_requires: Test::Exception: 0.25 requires: Spiffy: 0.30 =head2 Language Specs Every YAML document represents a single hash reference. The valid keys in this hash are as follows: =over =item comment [scalar] A comment =item cpanconfig [hash] Temporarily override assorted C<CPAN.pm> configuration variables. Supported are: C<build_requires_install_policy>, C<check_sigs>, C<make>, C<make_install_make_command>, C<prefer_installer>, C<test_report>. Please report as a bug when you need another one supported. =item depends [hash] *** EXPERIMENTAL FEATURE *** All three types, namely C<configure_requires>, C<build_requires>, and C<requires> are supported in the way specified in the META.yml specification. The current implementation I<merges> the specified dependencies with those declared by the package maintainer. In a future implementation this may be changed to override the original declaration. =item disabled [boolean] Specifies that this distribution shall not be processed at all. =item features [array] *** EXPERIMENTAL FEATURE *** Experimental implementation to deal with optional_features from META.yml. Still needs coordination with installer software and currently works only for META.yml declaring C<dynamic_config=0>. Use with caution. =item goto [string] The canonical name of a delegate distribution to install instead. Useful when a new version, although it tests OK itself, breaks something else or a developer release or a fork is already uploaded that is better than the last released version. =item install [hash] Processing instructions for the C<make install> or C<./Build install> phase of the CPAN mantra. See below under I<Processing Instructions>. =item make [hash] Processing instructions for the C<make> or C<./Build> phase of the CPAN mantra. See below under I<Processing Instructions>. =item match [hash] A hashref with one or more of the keys C<distribution>, C<module>, C<perl>, C<perlconfig>, and C<env> that specify whether a document is targeted at a specific CPAN distribution or installation. Keys prefixed with C<not_> negates the corresponding match. The corresponding values are interpreted as regular expressions. The C<distribution> related one will be matched against the canonical distribution name, e.g. "AUTHOR/Foo-Bar-3.14.tar.gz". The C<module> related one will be matched against I<all> modules contained in the distribution until one module matches. The C<perl> related one will be matched against C<$^X> (but with the absolute path). The value associated with C<perlconfig> is itself a hashref that is matched against corresponding values in the C<%Config::Config> hash living in the C<Config.pm> module. Keys prefixed with C<not_> negates the corresponding match. The value associated with C<env> is itself a hashref that is matched against corresponding values in the C<%ENV> hash. Keys prefixed with C<not_> negates the corresponding match. If more than one restriction of C<module>, C<distribution>, etc. is specified, the results of the separately computed match values must all match. If so, the hashref represented by the YAML document is returned as the preference structure for the current distribution. =item patches [array] An array of patches on CPAN or on the local disk to be applied in order via an external patch program. If the value for the C<-p> parameter is C<0> or C<1> is determined by reading the patch beforehand. The path to each patch is either an absolute path on the local filesystem or relative to a patch directory specified in the C<patches_dir> configuration variable or in the format of a canonical distro name. For examples please consult the distroprefs/ directory in the CPAN.pm distribution (these examples are not installed by default). Note: if the C<applypatch> program is installed and C<CPAN::Config> knows about it B<and> a patch is written by the C<makepatch> program, then C<CPAN.pm> lets C<applypatch> apply the patch. Both C<makepatch> and C<applypatch> are available from CPAN in the C<JV/makepatch-*> distribution. =item pl [hash] Processing instructions for the C<perl Makefile.PL> or C<perl Build.PL> phase of the CPAN mantra. See below under I<Processing Instructions>. =item test [hash] Processing instructions for the C<make test> or C<./Build test> phase of the CPAN mantra. See below under I<Processing Instructions>. =back =head2 Processing Instructions =over =item args [array] Arguments to be added to the command line =item commandline A full commandline to run via C<system()>. During execution, the environment variable PERL is set to $^X (but with an absolute path). If C<commandline> is specified, C<args> is not used. =item eexpect [hash] Extended C<expect>. This is a hash reference with four allowed keys, C<mode>, C<timeout>, C<reuse>, and C<talk>. You must install the C<Expect> module to use C<eexpect>. CPAN.pm does not install it for you. C<mode> may have the values C<deterministic> for the case where all questions come in the order written down and C<anyorder> for the case where the questions may come in any order. The default mode is C<deterministic>. C<timeout> denotes a timeout in seconds. Floating-point timeouts are OK. With C<mode=deterministic>, the timeout denotes the timeout per question; with C<mode=anyorder> it denotes the timeout per byte received from the stream or questions. C<talk> is a reference to an array that contains alternating questions and answers. Questions are regular expressions and answers are literal strings. The Expect module watches the stream from the execution of the external program (C<perl Makefile.PL>, C<perl Build.PL>, C<make>, etc.). For C<mode=deterministic>, the CPAN.pm injects the corresponding answer as soon as the stream matches the regular expression. For C<mode=anyorder> CPAN.pm answers a question as soon as the timeout is reached for the next byte in the input stream. In this mode you can use the C<reuse> parameter to decide what will happen with a question-answer pair after it has been used. In the default case (reuse=0) it is removed from the array, avoiding being used again accidentally. If you want to answer the question C<Do you really want to do that> several times, then it must be included in the array at least as often as you want this answer to be given. Setting the parameter C<reuse> to 1 makes this repetition unnecessary. =item env [hash] Environment variables to be set during the command =item expect [array] You must install the C<Expect> module to use C<expect>. CPAN.pm does not install it for you. C<< expect: <array> >> is a short notation for this C<eexpect>: eexpect: mode: deterministic timeout: 15 talk: <array> =back =head2 Schema verification with C<Kwalify> If you have the C<Kwalify> module installed (which is part of the Bundle::CPANxxl), then all your distroprefs files are checked for syntactic correctness. =head2 Example Distroprefs Files C<CPAN.pm> comes with a collection of example YAML files. Note that these are really just examples and should not be used without care because they cannot fit everybody's purpose. After all, the authors of the packages that ask questions had a need to ask, so you should watch their questions and adjust the examples to your environment and your needs. You have been warned:-) =head1 PROGRAMMER'S INTERFACE If you do not enter the shell, shell commands are available both as methods (C<CPAN::Shell-E<gt>install(...)>) and as functions in the calling package (C<install(...)>). Before calling low-level commands, it makes sense to initialize components of CPAN you need, e.g.: CPAN::HandleConfig->load; CPAN::Shell::setup_output; CPAN::Index->reload; High-level commands do such initializations automatically. There's currently only one class that has a stable interface - CPAN::Shell. All commands that are available in the CPAN shell are methods of the class CPAN::Shell. The arguments on the commandline are passed as arguments to the method. So if you take for example the shell command notest install A B C the actually executed command is CPAN::Shell->notest("install","A","B","C"); Each of the commands that produce listings of modules (C<r>, C<autobundle>, C<u>) also return a list of the IDs of all modules within the list. =over 2 =item expand($type,@things) The IDs of all objects available within a program are strings that can be expanded to the corresponding real objects with the C<CPAN::Shell-E<gt>expand("Module",@things)> method. Expand returns a list of CPAN::Module objects according to the C<@things> arguments given. In scalar context, it returns only the first element of the list. =item expandany(@things) Like expand, but returns objects of the appropriate type, i.e. CPAN::Bundle objects for bundles, CPAN::Module objects for modules, and CPAN::Distribution objects for distributions. Note: it does not expand to CPAN::Author objects. =item Programming Examples This enables the programmer to do operations that combine functionalities that are available in the shell. # install everything that is outdated on my disk: perl -MCPAN -e 'CPAN::Shell->install(CPAN::Shell->r)' # install my favorite programs if necessary: for $mod (qw(Net::FTP Digest::SHA Data::Dumper)) { CPAN::Shell->install($mod); } # list all modules on my disk that have no VERSION number for $mod (CPAN::Shell->expand("Module","/./")) { next unless $mod->inst_file; # MakeMaker convention for undefined $VERSION: next unless $mod->inst_version eq "undef"; print "No VERSION in ", $mod->id, "\n"; } # find out which distribution on CPAN contains a module: print CPAN::Shell->expand("Module","Apache::Constants")->cpan_file Or if you want to schedule a I<cron> job to watch CPAN, you could list all modules that need updating. First a quick and dirty way: perl -e 'use CPAN; CPAN::Shell->r;' If you don't want any output should all modules be up to date, parse the output of above command for the regular expression C</modules are up to date/> and decide to mail the output only if it doesn't match. If you prefer to do it more in a programmerish style in one single process, something like this may better suit you: # list all modules on my disk that have newer versions on CPAN for $mod (CPAN::Shell->expand("Module","/./")) { next unless $mod->inst_file; next if $mod->uptodate; printf "Module %s is installed as %s, could be updated to %s from CPAN\n", $mod->id, $mod->inst_version, $mod->cpan_version; } If that gives too much output every day, you may want to watch only for three modules. You can write for $mod (CPAN::Shell->expand("Module","/Apache|LWP|CGI/")) { as the first line instead. Or you can combine some of the above tricks: # watch only for a new mod_perl module $mod = CPAN::Shell->expand("Module","mod_perl"); exit if $mod->uptodate; # new mod_perl arrived, let me know all update recommendations CPAN::Shell->r; =back =head2 Methods in the other Classes =over 4 =item CPAN::Author::as_glimpse() Returns a one-line description of the author =item CPAN::Author::as_string() Returns a multi-line description of the author =item CPAN::Author::email() Returns the author's email address =item CPAN::Author::fullname() Returns the author's name =item CPAN::Author::name() An alias for fullname =item CPAN::Bundle::as_glimpse() Returns a one-line description of the bundle =item CPAN::Bundle::as_string() Returns a multi-line description of the bundle =item CPAN::Bundle::clean() Recursively runs the C<clean> method on all items contained in the bundle. =item CPAN::Bundle::contains() Returns a list of objects' IDs contained in a bundle. The associated objects may be bundles, modules or distributions. =item CPAN::Bundle::force($method,@args) Forces CPAN to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that CPAN.pm does not refuse to take the action. The C<force> is passed recursively to all contained objects. See also the section above on the C<force> and the C<fforce> pragma. =item CPAN::Bundle::get() Recursively runs the C<get> method on all items contained in the bundle =item CPAN::Bundle::inst_file() Returns the highest installed version of the bundle in either @INC or C<< $CPAN::Config->{cpan_home} >>. Note that this is different from CPAN::Module::inst_file. =item CPAN::Bundle::inst_version() Like CPAN::Bundle::inst_file, but returns the $VERSION =item CPAN::Bundle::uptodate() Returns 1 if the bundle itself and all its members are up-to-date. =item CPAN::Bundle::install() Recursively runs the C<install> method on all items contained in the bundle =item CPAN::Bundle::make() Recursively runs the C<make> method on all items contained in the bundle =item CPAN::Bundle::readme() Recursively runs the C<readme> method on all items contained in the bundle =item CPAN::Bundle::test() Recursively runs the C<test> method on all items contained in the bundle =item CPAN::Distribution::as_glimpse() Returns a one-line description of the distribution =item CPAN::Distribution::as_string() Returns a multi-line description of the distribution =item CPAN::Distribution::author Returns the CPAN::Author object of the maintainer who uploaded this distribution =item CPAN::Distribution::pretty_id() Returns a string of the form "AUTHORID/TARBALL", where AUTHORID is the author's PAUSE ID and TARBALL is the distribution filename. =item CPAN::Distribution::base_id() Returns the distribution filename without any archive suffix. E.g "Foo-Bar-0.01" =item CPAN::Distribution::clean() Changes to the directory where the distribution has been unpacked and runs C<make clean> there. =item CPAN::Distribution::containsmods() Returns a list of IDs of modules contained in a distribution file. Works only for distributions listed in the 02packages.details.txt.gz file. This typically means that just most recent version of a distribution is covered. =item CPAN::Distribution::cvs_import() Changes to the directory where the distribution has been unpacked and runs something like cvs -d $cvs_root import -m $cvs_log $cvs_dir $userid v$version there. =item CPAN::Distribution::dir() Returns the directory into which this distribution has been unpacked. =item CPAN::Distribution::force($method,@args) Forces CPAN to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that CPAN.pm does not refuse to take the action. See also the section above on the C<force> and the C<fforce> pragma. =item CPAN::Distribution::get() Downloads the distribution from CPAN and unpacks it. Does nothing if the distribution has already been downloaded and unpacked within the current session. =item CPAN::Distribution::install() Changes to the directory where the distribution has been unpacked and runs the external command C<make install> there. If C<make> has not yet been run, it will be run first. A C<make test> is issued in any case and if this fails, the install is cancelled. The cancellation can be avoided by letting C<force> run the C<install> for you. This install method only has the power to install the distribution if there are no dependencies in the way. To install an object along with all its dependencies, use CPAN::Shell->install. Note that install() gives no meaningful return value. See uptodate(). =item CPAN::Distribution::isa_perl() Returns 1 if this distribution file seems to be a perl distribution. Normally this is derived from the file name only, but the index from CPAN can contain a hint to achieve a return value of true for other filenames too. =item CPAN::Distribution::look() Changes to the directory where the distribution has been unpacked and opens a subshell there. Exiting the subshell returns. =item CPAN::Distribution::make() First runs the C<get> method to make sure the distribution is downloaded and unpacked. Changes to the directory where the distribution has been unpacked and runs the external commands C<perl Makefile.PL> or C<perl Build.PL> and C<make> there. =item CPAN::Distribution::perldoc() Downloads the pod documentation of the file associated with a distribution (in HTML format) and runs it through the external command I<lynx> specified in C<< $CPAN::Config->{lynx} >>. If I<lynx> isn't available, it converts it to plain text with the external command I<html2text> and runs it through the pager specified in C<< $CPAN::Config->{pager} >>. =item CPAN::Distribution::prefs() Returns the hash reference from the first matching YAML file that the user has deposited in the C<prefs_dir/> directory. The first succeeding match wins. The files in the C<prefs_dir/> are processed alphabetically, and the canonical distro name (e.g. AUTHOR/Foo-Bar-3.14.tar.gz) is matched against the regular expressions stored in the $root->{match}{distribution} attribute value. Additionally all module names contained in a distribution are matched against the regular expressions in the $root->{match}{module} attribute value. The two match values are ANDed together. Each of the two attributes are optional. =item CPAN::Distribution::prereq_pm() Returns the hash reference that has been announced by a distribution as the C<requires> and C<build_requires> elements. These can be declared either by the C<META.yml> (if authoritative) or can be deposited after the run of C<Build.PL> in the file C<./_build/prereqs> or after the run of C<Makfile.PL> written as the C<PREREQ_PM> hash in a comment in the produced C<Makefile>. I<Note>: this method only works after an attempt has been made to C<make> the distribution. Returns undef otherwise. =item CPAN::Distribution::readme() Downloads the README file associated with a distribution and runs it through the pager specified in C<< $CPAN::Config->{pager} >>. =item CPAN::Distribution::reports() Downloads report data for this distribution from www.cpantesters.org and displays a subset of them. =item CPAN::Distribution::read_yaml() Returns the content of the META.yml of this distro as a hashref. Note: works only after an attempt has been made to C<make> the distribution. Returns undef otherwise. Also returns undef if the content of META.yml is not authoritative. (The rules about what exactly makes the content authoritative are still in flux.) =item CPAN::Distribution::test() Changes to the directory where the distribution has been unpacked and runs C<make test> there. =item CPAN::Distribution::uptodate() Returns 1 if all the modules contained in the distribution are up-to-date. Relies on containsmods. =item CPAN::Index::force_reload() Forces a reload of all indices. =item CPAN::Index::reload() Reloads all indices if they have not been read for more than C<< $CPAN::Config->{index_expire} >> days. =item CPAN::InfoObj::dump() CPAN::Author, CPAN::Bundle, CPAN::Module, and CPAN::Distribution inherit this method. It prints the data structure associated with an object. Useful for debugging. Note: the data structure is considered internal and thus subject to change without notice. =item CPAN::Module::as_glimpse() Returns a one-line description of the module in four columns: The first column contains the word C<Module>, the second column consists of one character: an equals sign if this module is already installed and up-to-date, a less-than sign if this module is installed but can be upgraded, and a space if the module is not installed. The third column is the name of the module and the fourth column gives maintainer or distribution information. =item CPAN::Module::as_string() Returns a multi-line description of the module =item CPAN::Module::clean() Runs a clean on the distribution associated with this module. =item CPAN::Module::cpan_file() Returns the filename on CPAN that is associated with the module. =item CPAN::Module::cpan_version() Returns the latest version of this module available on CPAN. =item CPAN::Module::cvs_import() Runs a cvs_import on the distribution associated with this module. =item CPAN::Module::description() Returns a 44 character description of this module. Only available for modules listed in The Module List (CPAN/modules/00modlist.long.html or 00modlist.long.txt.gz) =item CPAN::Module::distribution() Returns the CPAN::Distribution object that contains the current version of this module. =item CPAN::Module::dslip_status() Returns a hash reference. The keys of the hash are the letters C<D>, C<S>, C<L>, C<I>, and <P>, for development status, support level, language, interface and public licence respectively. The data for the DSLIP status are collected by pause.perl.org when authors register their namespaces. The values of the 5 hash elements are one-character words whose meaning is described in the table below. There are also 5 hash elements C<DV>, C<SV>, C<LV>, C<IV>, and <PV> that carry a more verbose value of the 5 status variables. Where the 'DSLIP' characters have the following meanings: D - Development Stage (Note: *NO IMPLIED TIMESCALES*): i - Idea, listed to gain consensus or as a placeholder c - under construction but pre-alpha (not yet released) a/b - Alpha/Beta testing R - Released M - Mature (no rigorous definition) S - Standard, supplied with Perl 5 S - Support Level: m - Mailing-list d - Developer u - Usenet newsgroup comp.lang.perl.modules n - None known, try comp.lang.perl.modules a - abandoned; volunteers welcome to take over maintenance L - Language Used: p - Perl-only, no compiler needed, should be platform independent c - C and perl, a C compiler will be needed h - Hybrid, written in perl with optional C code, no compiler needed + - C++ and perl, a C++ compiler will be needed o - perl and another language other than C or C++ I - Interface Style f - plain Functions, no references used h - hybrid, object and function interfaces available n - no interface at all (huh?) r - some use of unblessed References or ties O - Object oriented using blessed references and/or inheritance P - Public License p - Standard-Perl: user may choose between GPL and Artistic g - GPL: GNU General Public License l - LGPL: "GNU Lesser General Public License" (previously known as "GNU Library General Public License") b - BSD: The BSD License a - Artistic license alone 2 - Artistic license 2.0 or later o - open source: approved by www.opensource.org d - allows distribution without restrictions r - restricted distribution n - no license at all =item CPAN::Module::force($method,@args) Forces CPAN to perform a task it would normally refuse to do. Force takes as arguments a method name to be invoked and any number of additional arguments to pass that method. The internals of the object get the needed changes so that CPAN.pm does not refuse to take the action. See also the section above on the C<force> and the C<fforce> pragma. =item CPAN::Module::get() Runs a get on the distribution associated with this module. =item CPAN::Module::inst_file() Returns the filename of the module found in @INC. The first file found is reported, just as perl itself stops searching @INC once it finds a module. =item CPAN::Module::available_file() Returns the filename of the module found in PERL5LIB or @INC. The first file found is reported. The advantage of this method over C<inst_file> is that modules that have been tested but not yet installed are included because PERL5LIB keeps track of tested modules. =item CPAN::Module::inst_version() Returns the version number of the installed module in readable format. =item CPAN::Module::available_version() Returns the version number of the available module in readable format. =item CPAN::Module::install() Runs an C<install> on the distribution associated with this module. =item CPAN::Module::look() Changes to the directory where the distribution associated with this module has been unpacked and opens a subshell there. Exiting the subshell returns. =item CPAN::Module::make() Runs a C<make> on the distribution associated with this module. =item CPAN::Module::manpage_headline() If module is installed, peeks into the module's manpage, reads the headline, and returns it. Moreover, if the module has been downloaded within this session, does the equivalent on the downloaded module even if it hasn't been installed yet. =item CPAN::Module::perldoc() Runs a C<perldoc> on this module. =item CPAN::Module::readme() Runs a C<readme> on the distribution associated with this module. =item CPAN::Module::reports() Calls the reports() method on the associated distribution object. =item CPAN::Module::test() Runs a C<test> on the distribution associated with this module. =item CPAN::Module::uptodate() Returns 1 if the module is installed and up-to-date. =item CPAN::Module::userid() Returns the author's ID of the module. =back =head2 Cache Manager Currently the cache manager only keeps track of the build directory ($CPAN::Config->{build_dir}). It is a simple FIFO mechanism that deletes complete directories below C<build_dir> as soon as the size of all directories there gets bigger than $CPAN::Config->{build_cache} (in MB). The contents of this cache may be used for later re-installations that you intend to do manually, but will never be trusted by CPAN itself. This is due to the fact that the user might use these directories for building modules on different architectures. There is another directory ($CPAN::Config->{keep_source_where}) where the original distribution files are kept. This directory is not covered by the cache manager and must be controlled by the user. If you choose to have the same directory as build_dir and as keep_source_where directory, then your sources will be deleted with the same fifo mechanism. =head2 Bundles A bundle is just a perl module in the namespace Bundle:: that does not define any functions or methods. It usually only contains documentation. It starts like a perl module with a package declaration and a $VERSION variable. After that the pod section looks like any other pod with the only difference being that I<one special pod section> exists starting with (verbatim): =head1 CONTENTS In this pod section each line obeys the format Module_Name [Version_String] [- optional text] The only required part is the first field, the name of a module (e.g. Foo::Bar, i.e. I<not> the name of the distribution file). The rest of the line is optional. The comment part is delimited by a dash just as in the man page header. The distribution of a bundle should follow the same convention as other distributions. Bundles are treated specially in the CPAN package. If you say 'install Bundle::Tkkit' (assuming such a bundle exists), CPAN will install all the modules in the CONTENTS section of the pod. You can install your own Bundles locally by placing a conformant Bundle file somewhere into your @INC path. The autobundle() command which is available in the shell interface does that for you by including all currently installed modules in a snapshot bundle file. =head1 PREREQUISITES The CPAN program is trying to depend on as little as possible so the user can use it in hostile environment. It works better the more goodies the environment provides. For example if you try in the CPAN shell install Bundle::CPAN or install Bundle::CPANxxl you will find the shell more convenient than the bare shell before. If you have a local mirror of CPAN and can access all files with "file:" URLs, then you only need a perl later than perl5.003 to run this module. Otherwise Net::FTP is strongly recommended. LWP may be required for non-UNIX systems, or if your nearest CPAN site is associated with a URL that is not C<ftp:>. If you have neither Net::FTP nor LWP, there is a fallback mechanism implemented for an external ftp command or for an external lynx command. =head1 UTILITIES =head2 Finding packages and VERSION This module presumes that all packages on CPAN =over 2 =item * declare their $VERSION variable in an easy to parse manner. This prerequisite can hardly be relaxed because it consumes far too much memory to load all packages into the running program just to determine the $VERSION variable. Currently all programs that are dealing with version use something like this perl -MExtUtils::MakeMaker -le \ 'print MM->parse_version(shift)' filename If you are author of a package and wonder if your $VERSION can be parsed, please try the above method. =item * come as compressed or gzipped tarfiles or as zip files and contain a C<Makefile.PL> or C<Build.PL> (well, we try to handle a bit more, but with little enthusiasm). =back =head2 Debugging Debugging this module is more than a bit complex due to interference from the software producing the indices on CPAN, the mirroring process on CPAN, packaging, configuration, synchronicity, and even (gasp!) due to bugs within the CPAN.pm module itself. For debugging the code of CPAN.pm itself in interactive mode, some debugging aid can be turned on for most packages within CPAN.pm with one of =over 2 =item o debug package... sets debug mode for packages. =item o debug -package... unsets debug mode for packages. =item o debug all turns debugging on for all packages. =item o debug number =back which sets the debugging packages directly. Note that C<o debug 0> turns debugging off. What seems a successful strategy is the combination of C<reload cpan> and the debugging switches. Add a new debug statement while running in the shell and then issue a C<reload cpan> and see the new debugging messages immediately without losing the current context. C<o debug> without an argument lists the valid package names and the current set of packages in debugging mode. C<o debug> has built-in completion support. For debugging of CPAN data there is the C<dump> command which takes the same arguments as make/test/install and outputs each object's Data::Dumper dump. If an argument looks like a perl variable and contains one of C<$>, C<@> or C<%>, it is eval()ed and fed to Data::Dumper directly. =head2 Floppy, Zip, Offline Mode CPAN.pm works nicely without network access, too. If you maintain machines that are not networked at all, you should consider working with C<file:> URLs. You'll have to collect your modules somewhere first. So you might use CPAN.pm to put together all you need on a networked machine. Then copy the $CPAN::Config->{keep_source_where} (but not $CPAN::Config->{build_dir}) directory on a floppy. This floppy is kind of a personal CPAN. CPAN.pm on the non-networked machines works nicely with this floppy. See also below the paragraph about CD-ROM support. =head2 Basic Utilities for Programmers =over 2 =item has_inst($module) Returns true if the module is installed. Used to load all modules into the running CPAN.pm that are considered optional. The config variable C<dontload_list> intercepts the C<has_inst()> call such that an optional module is not loaded despite being available. For example, the following command will prevent C<YAML.pm> from being loaded: cpan> o conf dontload_list push YAML See the source for details. =item use_inst($module) Similary to L<has_inst()> tries to load optional library but also dies if library is not available =item has_usable($module) Returns true if the module is installed and in a usable state. Only useful for a handful of modules that are used internally. See the source for details. =item instance($module) The constructor for all the singletons used to represent modules, distributions, authors, and bundles. If the object already exists, this method returns the object; otherwise, it calls the constructor. =item frontend() =item frontend($new_frontend) Getter/setter for frontend object. Method just allows to subclass CPAN.pm. =back =head1 SECURITY There's no strong security layer in CPAN.pm. CPAN.pm helps you to install foreign, unmasked, unsigned code on your machine. We compare to a checksum that comes from the net just as the distribution file itself. But we try to make it easy to add security on demand: =head2 Cryptographically signed modules Since release 1.77, CPAN.pm has been able to verify cryptographically signed module distributions using Module::Signature. The CPAN modules can be signed by their authors, thus giving more security. The simple unsigned MD5 checksums that were used before by CPAN protect mainly against accidental file corruption. You will need to have Module::Signature installed, which in turn requires that you have at least one of Crypt::OpenPGP module or the command-line F<gpg> tool installed. You will also need to be able to connect over the Internet to the public key servers, like pgp.mit.edu, and their port 11731 (the HKP protocol). The configuration parameter check_sigs is there to turn signature checking on or off. =head1 EXPORT Most functions in package CPAN are exported by default. The reason for this is that the primary use is intended for the cpan shell or for one-liners. =head1 ENVIRONMENT When the CPAN shell enters a subshell via the look command, it sets the environment CPAN_SHELL_LEVEL to 1, or increments that variable if it is already set. When CPAN runs, it sets the environment variable PERL5_CPAN_IS_RUNNING to the ID of the running process. It also sets PERL5_CPANPLUS_IS_RUNNING to prevent runaway processes which could happen with older versions of Module::Install. When running C<perl Makefile.PL>, the environment variable C<PERL5_CPAN_IS_EXECUTING> is set to the full path of the C<Makefile.PL> that is being executed. This prevents runaway processes with newer versions of Module::Install. When the config variable ftp_passive is set, all downloads will be run with the environment variable FTP_PASSIVE set to this value. This is in general a good idea as it influences both Net::FTP and LWP based connections. The same effect can be achieved by starting the cpan shell with this environment variable set. For Net::FTP alone, one can also always set passive mode by running libnetcfg. =head1 POPULATE AN INSTALLATION WITH LOTS OF MODULES Populating a freshly installed perl with one's favorite modules is pretty easy if you maintain a private bundle definition file. To get a useful blueprint of a bundle definition file, the command autobundle can be used on the CPAN shell command line. This command writes a bundle definition file for all modules installed for the current perl interpreter. It's recommended to run this command once only, and from then on maintain the file manually under a private name, say Bundle/my_bundle.pm. With a clever bundle file you can then simply say cpan> install Bundle::my_bundle then answer a few questions and go out for coffee (possibly even in a different city). Maintaining a bundle definition file means keeping track of two things: dependencies and interactivity. CPAN.pm sometimes fails on calculating dependencies because not all modules define all MakeMaker attributes correctly, so a bundle definition file should specify prerequisites as early as possible. On the other hand, it's annoying that so many distributions need some interactive configuring. So what you can try to accomplish in your private bundle file is to have the packages that need to be configured early in the file and the gentle ones later, so you can go out for coffee after a few minutes and leave CPAN.pm to churn away unattended. =head1 WORKING WITH CPAN.pm BEHIND FIREWALLS Thanks to Graham Barr for contributing the following paragraphs about the interaction between perl, and various firewall configurations. For further information on firewalls, it is recommended to consult the documentation that comes with the I<ncftp> program. If you are unable to go through the firewall with a simple Perl setup, it is likely that you can configure I<ncftp> so that it works through your firewall. =head2 Three basic types of firewalls Firewalls can be categorized into three basic types. =over 4 =item http firewall This is when the firewall machine runs a web server, and to access the outside world, you must do so via that web server. If you set environment variables like http_proxy or ftp_proxy to values beginning with http://, or in your web browser you've proxy information set, then you know you are running behind an http firewall. To access servers outside these types of firewalls with perl (even for ftp), you need LWP or HTTP::Tiny. =item ftp firewall This where the firewall machine runs an ftp server. This kind of firewall will only let you access ftp servers outside the firewall. This is usually done by connecting to the firewall with ftp, then entering a username like "user@outside.host.com". To access servers outside these type of firewalls with perl, you need Net::FTP. =item One-way visibility One-way visibility means these firewalls try to make themselves invisible to users inside the firewall. An FTP data connection is normally created by sending your IP address to the remote server and then listening for the return connection. But the remote server will not be able to connect to you because of the firewall. For these types of firewall, FTP connections need to be done in a passive mode. There are two that I can think off. =over 4 =item SOCKS If you are using a SOCKS firewall, you will need to compile perl and link it with the SOCKS library. This is what is normally called a 'socksified' perl. With this executable you will be able to connect to servers outside the firewall as if it were not there. =item IP Masquerade This is when the firewall implemented in the kernel (via NAT, or networking address translation), it allows you to hide a complete network behind one IP address. With this firewall no special compiling is needed as you can access hosts directly. For accessing ftp servers behind such firewalls you usually need to set the environment variable C<FTP_PASSIVE> or the config variable ftp_passive to a true value. =back =back =head2 Configuring lynx or ncftp for going through a firewall If you can go through your firewall with e.g. lynx, presumably with a command such as /usr/local/bin/lynx -pscott:tiger then you would configure CPAN.pm with the command o conf lynx "/usr/local/bin/lynx -pscott:tiger" That's all. Similarly for ncftp or ftp, you would configure something like o conf ncftp "/usr/bin/ncftp -f /home/scott/ncftplogin.cfg" Your mileage may vary... =head1 FAQ =over 4 =item 1) I installed a new version of module X but CPAN keeps saying, I have the old version installed Probably you B<do> have the old version installed. This can happen if a module installs itself into a different directory in the @INC path than it was previously installed. This is not really a CPAN.pm problem, you would have the same problem when installing the module manually. The easiest way to prevent this behaviour is to add the argument C<UNINST=1> to the C<make install> call, and that is why many people add this argument permanently by configuring o conf make_install_arg UNINST=1 =item 2) So why is UNINST=1 not the default? Because there are people who have their precise expectations about who may install where in the @INC path and who uses which @INC array. In fine tuned environments C<UNINST=1> can cause damage. =item 3) I want to clean up my mess, and install a new perl along with all modules I have. How do I go about it? Run the autobundle command for your old perl and optionally rename the resulting bundle file (e.g. Bundle/mybundle.pm), install the new perl with the Configure option prefix, e.g. ./Configure -Dprefix=/usr/local/perl-5.6.78.9 Install the bundle file you produced in the first step with something like cpan> install Bundle::mybundle and you're done. =item 4) When I install bundles or multiple modules with one command there is too much output to keep track of. You may want to configure something like o conf make_arg "| tee -ai /root/.cpan/logs/make.out" o conf make_install_arg "| tee -ai /root/.cpan/logs/make_install.out" so that STDOUT is captured in a file for later inspection. =item 5) I am not root, how can I install a module in a personal directory? As of CPAN 1.9463, if you do not have permission to write the default perl library directories, CPAN's configuration process will ask you whether you want to bootstrap <local::lib>, which makes keeping a personal perl library directory easy. Another thing you should bear in mind is that the UNINST parameter can be dangerous when you are installing into a private area because you might accidentally remove modules that other people depend on that are not using the private area. =item 6) How to get a package, unwrap it, and make a change before building it? Have a look at the C<look> (!) command. =item 7) I installed a Bundle and had a couple of fails. When I retried, everything resolved nicely. Can this be fixed to work on first try? The reason for this is that CPAN does not know the dependencies of all modules when it starts out. To decide about the additional items to install, it just uses data found in the META.yml file or the generated Makefile. An undetected missing piece breaks the process. But it may well be that your Bundle installs some prerequisite later than some depending item and thus your second try is able to resolve everything. Please note, CPAN.pm does not know the dependency tree in advance and cannot sort the queue of things to install in a topologically correct order. It resolves perfectly well B<if> all modules declare the prerequisites correctly with the PREREQ_PM attribute to MakeMaker or the C<requires> stanza of Module::Build. For bundles which fail and you need to install often, it is recommended to sort the Bundle definition file manually. =item 8) In our intranet, we have many modules for internal use. How can I integrate these modules with CPAN.pm but without uploading the modules to CPAN? Have a look at the CPAN::Site module. =item 9) When I run CPAN's shell, I get an error message about things in my C</etc/inputrc> (or C<~/.inputrc>) file. These are readline issues and can only be fixed by studying readline configuration on your architecture and adjusting the referenced file accordingly. Please make a backup of the C</etc/inputrc> or C<~/.inputrc> and edit them. Quite often harmless changes like uppercasing or lowercasing some arguments solves the problem. =item 10) Some authors have strange characters in their names. Internally CPAN.pm uses the UTF-8 charset. If your terminal is expecting ISO-8859-1 charset, a converter can be activated by setting term_is_latin to a true value in your config file. One way of doing so would be cpan> o conf term_is_latin 1 If other charset support is needed, please file a bug report against CPAN.pm at rt.cpan.org and describe your needs. Maybe we can extend the support or maybe UTF-8 terminals become widely available. Note: this config variable is deprecated and will be removed in a future version of CPAN.pm. It will be replaced with the conventions around the family of $LANG and $LC_* environment variables. =item 11) When an install fails for some reason and then I correct the error condition and retry, CPAN.pm refuses to install the module, saying C<Already tried without success>. Use the force pragma like so force install Foo::Bar Or you can use look Foo::Bar and then C<make install> directly in the subshell. =item 12) How do I install a "DEVELOPER RELEASE" of a module? By default, CPAN will install the latest non-developer release of a module. If you want to install a dev release, you have to specify the partial path starting with the author id to the tarball you wish to install, like so: cpan> install KWILLIAMS/Module-Build-0.27_07.tar.gz Note that you can use the C<ls> command to get this path listed. =item 13) How do I install a module and all its dependencies from the commandline, without being prompted for anything, despite my CPAN configuration (or lack thereof)? CPAN uses ExtUtils::MakeMaker's prompt() function to ask its questions, so if you set the PERL_MM_USE_DEFAULT environment variable, you shouldn't be asked any questions at all (assuming the modules you are installing are nice about obeying that variable as well): % PERL_MM_USE_DEFAULT=1 perl -MCPAN -e 'install My::Module' =item 14) How do I create a Module::Build based Build.PL derived from an ExtUtils::MakeMaker focused Makefile.PL? http://search.cpan.org/dist/Module-Build-Convert/ =item 15) I'm frequently irritated with the CPAN shell's inability to help me select a good mirror. CPAN can now help you select a "good" mirror, based on which ones have the lowest 'ping' round-trip times. From the shell, use the command 'o conf init urllist' and allow CPAN to automatically select mirrors for you. Beyond that help, the urllist config parameter is yours. You can add and remove sites at will. You should find out which sites have the best up-to-dateness, bandwidth, reliability, etc. and are topologically close to you. Some people prefer fast downloads, others up-to-dateness, others reliability. You decide which to try in which order. Henk P. Penning maintains a site that collects data about CPAN sites: http://mirrors.cpan.org/ Also, feel free to play with experimental features. Run o conf init randomize_urllist ftpstats_period ftpstats_size and choose your favorite parameters. After a few downloads running the C<hosts> command will probably assist you in choosing the best mirror sites. =item 16) Why do I get asked the same questions every time I start the shell? You can make your configuration changes permanent by calling the command C<o conf commit>. Alternatively set the C<auto_commit> variable to true by running C<o conf init auto_commit> and answering the following question with yes. =item 17) Older versions of CPAN.pm had the original root directory of all tarballs in the build directory. Now there are always random characters appended to these directory names. Why was this done? The random characters are provided by File::Temp and ensure that each module's individual build directory is unique. This makes running CPAN.pm in concurrent processes simultaneously safe. =item 18) Speaking of the build directory. Do I have to clean it up myself? You have the choice to set the config variable C<scan_cache> to C<never>. Then you must clean it up yourself. The other possible values, C<atstart> and C<atexit> clean up the build directory when you start (or more precisely, after the first extraction into the build directory) or exit the CPAN shell, respectively. If you never start up the CPAN shell, you probably also have to clean up the build directory yourself. =item 19) How can I switch to sudo instead of local::lib? The following 5 environment veriables need to be reset to the previous values: PATH, PERL5LIB, PERL_LOCAL_LIB_ROOT, PERL_MB_OPT, PERL_MM_OPT; and these two CPAN.pm config variables must be reconfigured: make_install_make_command and mbuild_install_build_command. The five env variables have probably been overwritten in your $HOME/.bashrc or some equivalent. You either find them there and delete their traces and logout/login or you override them temporarily, depending on your exact desire. The two cpanpm config variables can be set with: o conf init /install_.*_command/ probably followed by o conf commit =back =head1 COMPATIBILITY =head2 OLD PERL VERSIONS CPAN.pm is regularly tested to run under 5.005 and assorted newer versions. It is getting more and more difficult to get the minimal prerequisites working on older perls. It is close to impossible to get the whole Bundle::CPAN working there. If you're in the position to have only these old versions, be advised that CPAN is designed to work fine without the Bundle::CPAN installed. To get things going, note that GBARR/Scalar-List-Utils-1.18.tar.gz is compatible with ancient perls and that File::Temp is listed as a prerequisite but CPAN has reasonable workarounds if it is missing. =head2 CPANPLUS This module and its competitor, the CPANPLUS module, are both much cooler than the other. CPAN.pm is older. CPANPLUS was designed to be more modular, but it was never intended to be compatible with CPAN.pm. =head2 CPANMINUS In the year 2010 App::cpanminus was launched as a new approach to a cpan shell with a considerably smaller footprint. Very cool stuff. =head1 SECURITY ADVICE This software enables you to upgrade software on your computer and so is inherently dangerous because the newly installed software may contain bugs and may alter the way your computer works or even make it unusable. Please consider backing up your data before every upgrade. =head1 BUGS Please report bugs via L<http://rt.cpan.org/> Before submitting a bug, please make sure that the traditional method of building a Perl module package from a shell by following the installation instructions of that package still works in your environment. =head1 AUTHOR Andreas Koenig C<< <andk@cpan.org> >> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<http://www.perl.com/perl/misc/Artistic.html> =head1 TRANSLATIONS Kawai,Takanori provides a Japanese translation of a very old version of this manpage at L<http://homepage3.nifty.com/hippo2000/perltips/CPAN.htm> =head1 SEE ALSO Many people enter the CPAN shell by running the L<cpan> utility program which is installed in the same directory as perl itself. So if you have this directory in your PATH variable (or some equivalent in your operating system) then typing C<cpan> in a console window will work for you as well. Above that the utility provides several commandline shortcuts. melezhik (Alexey) sent me a link where he published a chef recipe to work with CPAN.pm: http://community.opscode.com/cookbooks/cpan. =cut PK�������!�g, �� ��<��perl5/x86_64-linux-thread-multi/.meta/CPAN-2.36/install.jsonnu�6$��������{"name":"CPAN","target":"CPAN","provides":{"CPAN::Plugin::Specfile":{"version":0.02,"file":"lib/CPAN/Plugin/Specfile.pm"},"CPAN::LWP::UserAgent":{"file":"lib/CPAN/LWP/UserAgent.pm","version":1.9601},"CPAN::Index":{"version":2.29,"file":"lib/CPAN/Index.pm"},"CPAN::Distroprefs":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::Mirrored::By":{"version":2.27,"file":"lib/CPAN/Mirrors.pm"},"CPAN::Kwalify":{"version":"5.50","file":"lib/CPAN/Kwalify.pm"},"CPAN::Mirrors":{"file":"lib/CPAN/Mirrors.pm","version":2.27},"CPAN::CacheMgr":{"version":5.5002,"file":"lib/CPAN/CacheMgr.pm"},"CPAN::Distroprefs::Result::Error":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::Prompt":{"file":"lib/CPAN/Prompt.pm","version":5.5},"CPAN::Distroprefs::Result::Fatal":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::HandleConfig":{"file":"lib/CPAN/HandleConfig.pm","version":5.5012},"CPAN::Tarzip":{"version":5.5013,"file":"lib/CPAN/Tarzip.pm"},"CPAN::HTTP::Client":{"version":1.9602,"file":"lib/CPAN/HTTP/Client.pm"},"CPAN::Complete":{"file":"lib/CPAN/Complete.pm","version":5.5001},"CPAN::DeferredCode":{"file":"lib/CPAN/DeferredCode.pm","version":"5.50"},"CPAN::InfoObj":{"file":"lib/CPAN/InfoObj.pm","version":5.5},"App::Cpan":{"file":"lib/App/Cpan.pm","version":1.678},"CPAN::HTTP::Credentials":{"version":1.9601,"file":"lib/CPAN/HTTP/Credentials.pm"},"CPAN::Exception::blocked_urllist":{"version":1.001,"file":"lib/CPAN/Exception/blocked_urllist.pm"},"CPAN::Distroprefs::Pref":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::Shell":{"file":"lib/CPAN/Shell.pm","version":5.5009},"CPAN::Nox":{"version":5.5001,"file":"lib/CPAN/Nox.pm"},"CPAN::Author":{"version":5.5002,"file":"lib/CPAN/Author.pm"},"CPAN::Module":{"version":5.5003,"file":"lib/CPAN/Module.pm"},"CPAN":{"file":"lib/CPAN.pm","version":2.36},"CPAN::FirstTime":{"version":5.5317,"file":"lib/CPAN/FirstTime.pm"},"CPAN::Distroprefs::Result":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::Distroprefs::Iterator":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::Exception::RecursiveDependency":{"file":"lib/CPAN/Exception/RecursiveDependency.pm","version":5.5001},"CPAN::Version":{"file":"lib/CPAN/Version.pm","version":5.5003},"CPAN::Exception::yaml_not_installed":{"version":5.5,"file":"lib/CPAN/Exception/yaml_not_installed.pm"},"CPAN::FTP":{"file":"lib/CPAN/FTP.pm","version":5.5016},"CPAN::Exception::RecursiveDependency::na":{"version":5.5001,"file":"lib/CPAN/Exception/RecursiveDependency.pm"},"CPAN::FTP::netrc":{"version":1.01,"file":"lib/CPAN/FTP/netrc.pm"},"CPAN::Debug":{"file":"lib/CPAN/Debug.pm","version":5.5001},"CPAN::Bundle":{"version":5.5005,"file":"lib/CPAN/Bundle.pm"},"CPAN::URL":{"version":5.5,"file":"lib/CPAN/URL.pm"},"CPAN::Distribution":{"file":"lib/CPAN/Distribution.pm","version":2.34},"CPAN::Exception::yaml_process_error":{"version":5.5,"file":"lib/CPAN/Exception/yaml_process_error.pm"},"CPAN::Distroprefs::Result::Success":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Distrostatus":{"version":5.5,"file":"lib/CPAN/Distrostatus.pm"},"CPAN::Eval":{"file":"lib/CPAN/Distroprefs.pm","version":6.0001},"CPAN::Admin":{"version":5.501,"file":"lib/CPAN/Admin.pm"},"CPAN::Queue":{"file":"lib/CPAN/Queue.pm","version":5.5003},"CPAN::Plugin":{"file":"lib/CPAN/Plugin.pm","version":0.97},"CPAN::Distroprefs::Result::Warning":{"version":6.0001,"file":"lib/CPAN/Distroprefs.pm"},"CPAN::Queue::Item":{"file":"lib/CPAN/Queue.pm","version":5.5003}},"version":2.36,"dist":"CPAN-2.36","pathname":"A/AN/ANDK/CPAN-2.36.tar.gz"}PK�������!�qA �� ��;��perl5/x86_64-linux-thread-multi/.meta/CPAN-2.36/MYMETA.jsonnu�6$��������{ "abstract" : "query, download and build perl modules from CPAN sites", "author" : [ "Andreas Koenig <andreas.koenig.gmwojprw@franz.ak.mind.de>" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010", "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", "Archive::Zip" : "0", "CPAN::Meta" : "0", "CPAN::Meta::Requirements" : "2.121", "CPAN::Meta::YAML" : "0", "Compress::Bzip2" : "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::HomeDir" : "0", "File::Spec" : "0", "File::Temp" : "0", "File::Which" : "0", "HTTP::Tiny" : "0.005", "IO::Compress::Base" : "0", "IO::Zlib" : "0", "JSON::PP" : "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::Glob" : "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.36", "x_serialization_backend" : "JSON::PP version 2.97001" } PK�������!�n}����O��perl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.143/install.jsonnu�6$��������{"pathname":"R/RJ/RJBS/CPAN-Meta-Requirements-2.143.tar.gz","version":"2.143","provides":{"CPAN::Meta::Requirements::Range":{"file":"lib/CPAN/Meta/Requirements/Range.pm","version":"2.143"},"CPAN::Meta::Requirements":{"file":"lib/CPAN/Meta/Requirements.pm","version":"2.143"}},"target":"CPAN::Meta::Requirements","dist":"CPAN-Meta-Requirements-2.143","name":"CPAN::Meta::Requirements"}PK�������!�&9~��~��N��perl5/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 <dagolden@cpan.org>", "Ricardo Signes <rjbs@cpan.org>" ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.030, CPAN::Meta::Converter version 2.150010", "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 <mohawk2@users.noreply.github.com>", "Graham Knop <haarg@haarg.org>", "Karen Etheridge <ether@cpan.org>", "Leon Timmermans <fawaka@gmail.com>", "Paul Howarth <paul@city-fan.org>", "Ricardo Signes <rjbs@semiotic.systems>", "robario <webmaster@robario.com>", "Tatsuhiko Miyagawa <miyagawa@bulknews.net>", "Tatsuhiko Miyagawa <miyagawa@gmail.com>" ], "x_generated_by_perl" : "v5.37.10", "x_serialization_backend" : "JSON::PP version 2.97001", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } PK�������!� ����>��perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.20/install.jsonnu�6$��������{"name":"IO::Tty","dist":"IO-Tty-1.20","provides":{"IO::Tty":{"version":"1.20","file":"Tty.pm"},"IO::Pty":{"version":"1.20","file":"Pty.pm"},"IO::Tty::Constant":{"version":"1.20","file":"Tty/Constant.pm"}},"version":"1.20","target":"IO::Pty","pathname":"T/TO/TODDR/IO-Tty-1.20.tar.gz"}PK�������!�ǽA��A��=��perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.20/MYMETA.jsonnu�6$��������{ "abstract" : "Pseudo ttys and constants", "author" : [ "Roland Giersig <RGiersig@cpan.org>" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010", "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 2.97001" } PK�������!�������>��perl5/x86_64-linux-thread-multi/.meta/Expect-1.38/install.jsonnu�6$��������{"name":"Expect","provides":{"Expect":{"version":1.38,"file":"lib/Expect.pm"}},"version":1.38,"target":"Expect","dist":"Expect-1.38","pathname":"J/JA/JACOBY/Expect-1.38.tar.gz"}PK�������!�!6��6��=��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 <ASchutz@users.sourceforge.net>", "Roland Giersig <RGiersig@cpan.org>", "Dave Jacoby <jacoby@cpan.org>" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.62, CPAN::Meta::Converter version 2.150010", "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 2.97001" } PK�������!�s������B��perl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.088/install.jsonnu�6$��������{"pathname":"D/DA/DAGOLDEN/HTTP-Tiny-0.088.tar.gz","name":"HTTP::Tiny","version":"0.088","provides":{"HTTP::Tiny":{"version":"0.088","file":"lib/HTTP/Tiny.pm"}},"target":"HTTP::Tiny","dist":"HTTP-Tiny-0.088"}PK�������!��1����A��perl5/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 <chansen@cpan.org>", "David Golden <dagolden@cpan.org>" ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.030, CPAN::Meta::Converter version 2.150010", "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 <gardner@pythian.com>", "Alessandro Ghedini <al3xbio@gmail.com>", "A. Sinan Unur <nanis@cpan.org>", "Brad Gilbert <bgills@cpan.org>", "brian m. carlson <sandals@crustytoothpaste.net>", "Chris Nehren <apeiron@cpan.org>", "Chris Weyl <cweyl@alumni.drew.edu>", "Claes Jakobsson <claes@surfar.nu>", "Clinton Gormley <clint@traveljury.com>", "Craig A. Berry <craigberry@mac.com>", "Craig Berry <cberry@cpan.org>", "David Golden <xdg@xdg.me>", "David Mitchell <davem@iabyn.com>", "Dean Pearce <pearce@pythian.com>", "Edward Zborowski <ed@rubensteintech.com>", "Felipe Gasper <felipe@felipegasper.com>", "Graham Knop <haarg@haarg.org>", "Greg Kennedy <kennedy.greg@gmail.com>", "James E Keenan <jkeenan@cpan.org>", "James Raspass <jraspass@gmail.com>", "Jeremy Mates <jmates@cpan.org>", "Jess Robinson <castaway@desert-island.me.uk>", "Karen Etheridge <ether@cpan.org>", "Lukas Eklund <leklund@gmail.com>", "Martin J. Evans <mjegh@ntlworld.com>", "Martin-Louis Bright <mlbright@gmail.com>", "Matthew Horsfall <wolfsage@gmail.com>", "Michael R. Davis <mrdvt92@users.noreply.github.com>", "Mike Doherty <doherty@cpan.org>", "Nicolas Rochelemagne <rochelemagne@cpanel.net>", "Olaf Alders <olaf@wundersolutions.com>", "Olivier Mengué <dolmen@cpan.org>", "Petr Písař <ppisar@redhat.com>", "sanjay-cpu <snjkmr32@gmail.com>", "Serguei Trouchelle <stro@cpan.org>", "Shoichi Kaji <skaji@cpan.org>", "SkyMarshal <skymarshal1729@gmail.com>", "Sören Kornetzki <soeren.kornetzki@delti.com>", "Steve Grazzini <steve.grazzini@grantstreet.com>", "Stig Palmquist <git@stig.io>", "Syohei YOSHIDA <syohex@gmail.com>", "Tatsuhiko Miyagawa <miyagawa@bulknews.net>", "Tom Hukins <tom@eborcom.com>", "Tony Cook <tony@develop-help.com>", "Xavier Guimard <yadd@debian.org>" ], "x_generated_by_perl" : "v5.36.0", "x_serialization_backend" : "JSON::PP version 2.97001", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } PK�������!�MH������H��perl5/x86_64-linux-thread-multi/.meta/Canary-Stability-2013/install.jsonnu�6$��������{"pathname":"M/ML/MLEHMANN/Canary-Stability-2013.tar.gz","name":"Canary::Stability","dist":"Canary-Stability-2013","target":"Canary::Stability","provides":{"Canary::Stability":{"file":"Stability.pm","version":2013}},"version":2013}PK�������!�QE����G��perl5/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", "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.97001" } PK�������!� k������D��perl5/x86_64-linux-thread-multi/.meta/common-sense-3.75/install.jsonnu�6$��������{"name":"common::sense","dist":"common-sense-3.75","provides":{"common::sense":{"version":3.75,"file":"sense.pm.PL"}},"target":"common::sense","version":3.75,"pathname":"M/ML/MLEHMANN/common-sense-3.75.tar.gz"}PK�������!�PU?��?��C��perl5/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.150010", "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, "x_serialization_backend" : "JSON::PP version 2.97001" } PK�������!�:D����H��perl5/x86_64-linux-thread-multi/.meta/Types-Serialiser-1.01/install.jsonnu�6$��������{"pathname":"M/ML/MLEHMANN/Types-Serialiser-1.01.tar.gz","dist":"Types-Serialiser-1.01","provides":{"Types::Serialiser::Error":{"file":"Serialiser.pm","version":1.01},"Types::Serialiser":{"file":"Serialiser.pm","version":1.01},"Types::Serialiser::BooleanBase":{"file":"Serialiser.pm","version":1.01},"JSON::PP::Boolean":{"file":"Serialiser.pm","version":1.01}},"target":"Types::Serialiser","version":1.01,"name":"Types::Serialiser"}PK�������!�V����G��perl5/x86_64-linux-thread-multi/.meta/Types-Serialiser-1.01/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.150010", "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.01", "x_serialization_backend" : "JSON::PP version 2.97001" } PK�������!�G������?��perl5/x86_64-linux-thread-multi/.meta/JSON-XS-4.03/install.jsonnu�6$��������{"dist":"JSON-XS-4.03","provides":{"JSON::XS":{"version":4.03,"file":"XS.pm"}},"target":"JSON::XS","version":4.03,"name":"JSON::XS","pathname":"M/ML/MLEHMANN/JSON-XS-4.03.tar.gz"}PK�������!�| ����>��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.150010", "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", "x_serialization_backend" : "JSON::PP version 2.97001" } PK�������!�?����E��perl5/x86_64-linux-thread-multi/.meta/local-lib-2.000029/install.jsonnu�6$��������{"pathname":"H/HA/HAARG/local-lib-2.000029.tar.gz","dist":"local-lib-2.000029","target":"local::lib","provides":{"lib::core::only":{"file":"lib/lib/core/only.pm"},"local::lib":{"version":2.000029,"file":"lib/local/lib.pm"}},"version":2.000029,"name":"local::lib"}PK�������!��VJ����D��perl5/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) <mst@shadowcat.co.uk>" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010", "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 2.97001" } PK�������!�[& ������@��perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.31/install.jsonnu�6$��������{"name":"Try::Tiny","target":"Try::Tiny","provides":{"Try::Tiny":{"version":"0.31","file":"lib/Try/Tiny.pm"}},"version":"0.31","dist":"Try-Tiny-0.31","pathname":"E/ET/ETHER/Try-Tiny-0.31.tar.gz"}PK�������!�}t����?��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) <nothingmuch@woobling.org>", "Jesse Luehrs <doy@tozt.net>" ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.024, CPAN::Meta::Converter version 2.150010", "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 <ether@cpan.org>", "Peter Rabbitson <ribasushi@cpan.org>", "Ricardo Signes <rjbs@cpan.org>", "Mark Fowler <mark@twoshortplanks.com>", "Graham Knop <haarg@haarg.org>", "Aristotle Pagaltzis <pagaltzis@gmx.de>", "Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>", "Lukas Mai <l.mai@web.de>", "Alex <alex@koban.(none)>", "anaxagoras <walkeraj@gmail.com>", "Andrew Yates <ayates@haddock.local>", "awalker <awalker@sourcefire.com>", "chromatic <chromatic@wgz.org>", "cm-perl <cm-perl@users.noreply.github.com>", "David Lowe <davidl@lokku.com>", "Glenn Fowler <cebjyre@cpan.org>", "Hans Dieter Pearcey <hdp@weftsoar.net>", "Jens Berthold <jens@jebecs.de>", "Jonathan Yu <JAWNSY@cpan.org>", "Marc Mims <marc@questright.com>", "Mark Stosberg <mark@stosberg.com>", "Pali <pali@cpan.org>", "Paul Howarth <paul@city-fan.org>", "Rudolf Leermakers <rudolf@hatsuseno.org>" ], "x_generated_by_perl" : "v5.35.6", "x_serialization_backend" : "JSON::PP version 2.97001", "x_spdx_expression" : "MIT", "x_use_unsafe_inc" : 0 } PK�������!�K |��|��A��perl5/x86_64-linux-thread-multi/.meta/version-0.9932/install.jsonnu�6$��������{"pathname":"L/LE/LEONT/version-0.9932.tar.gz","name":"version","dist":"version-0.9932","version":0.9932,"provides":{"version::vpp":{"file":"vperl/vpp.pm","version":0.9932},"version":{"version":0.9932,"file":"lib/version.pm"},"version::vxs":{"file":"vutil/lib/version/vxs.pm","version":0.9932},"version::regex":{"version":0.9932,"file":"lib/version/regex.pm"}},"target":"version"}PK�������!�(����@��perl5/x86_64-linux-thread-multi/.meta/version-0.9932/MYMETA.jsonnu�6$��������{ "abstract" : "Structured version objects", "author" : [ "John Peacock <jpeacock@cpan.org>" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.70, CPAN::Meta::Converter version 2.150010", "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 2.97001" } PK�������!�\m��m��A��perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.34/install.jsonnu�6$��������{"dist":"YAML-Syck-1.34","provides":{"YAML::Syck":{"file":"lib/YAML/Syck.pm","version":1.34},"JSON::Syck":{"file":"lib/JSON/Syck.pm","version":1.34},"YAML::Dumper::Syck":{"file":"lib/YAML/Dumper/Syck.pm"},"YAML::Loader::Syck":{"file":"lib/YAML/Loader/Syck.pm"}},"version":1.34,"target":"YAML::Syck","name":"YAML::Syck","pathname":"T/TO/TODDR/YAML-Syck-1.34.tar.gz"}PK�������!�Q^����@��perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.34/MYMETA.jsonnu�6$��������{ "abstract" : "Fast, lightweight YAML loader and dumper", "author" : [ "Todd Rinaldo <toddr@cpan.org>" ], "dynamic_config" : 0, "generated_by" : "ExtUtils::MakeMaker version 7.44, CPAN::Meta::Converter version 2.150010", "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 2.97001" } PK�������!� ����perl5/Expect.pmnu�7m��������# -*-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 <ASchutz@users.sourceforge.net> # # This module now is maintained by # Dave Jacoby <jacoby@cpan.org> # 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 <blank><backspace> # 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<What is Expect|http://code-maven.com/expect> 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</"I want to automate password entry for su/ssh/scp/rsh/..."> and L</"I want to use Expect to automate [anything with a buzzword]..."> =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<or> =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<or> =item $object->spawn($command, @parameters) I<or> =item Expect->new($command, @parameters) Forks and execs $command. Returns an Expect object upon success or C<undef> 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 <space><backspace> 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<before> 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<or> =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<qr//>) 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<expect>, you can set it via the C<timeout> method . If the first argument of C<expect> 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<or> =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<or> =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<or> =item $object->match() returns the string matched by the last expect() call, undef if no string was matched. =item $object->exp_match_number() I<or> =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<or> =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<or> =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<or> =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<or> =item $object->exitstatus() Returns the exit status of $object (if it already exited). =item $object->exp_pty_handle() I<or> =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<IPC::Run>. =item Expect::test_handles(@objects) Given a set of objects determines which objects' handles have data ready to be read. B<Returns an array> 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<FILEHANDLE>, 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<Expect::interconnect($object , ...)>. 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<or> =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<or> =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<or> =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 <leakin@japh.itg.ti.com> has ported the kibitz script from Tcl/Expect to Perl/Expect. Jeff Carr <jcarr@linuxmachines.com> 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 <Eric.Arnold@Sun.com> and Randal 'Nuke your NT box with one line of perl code' Schwartz<merlyn@stonehenge.com> 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 <rogaski@att.com> 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<IO::Tty> 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-E<gt>raw_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<Net::FTP> or C<ncftp> (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<perlthrtut>: "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<ssh-keygen>). =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<http://sourceforge.net/projects/expectperl/> though the source code is now in GitHub: L<https://github.com/jacoby/expect.pm> =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 E<lt>F<ASchutz@users.sourceforge.net>E<gt> (retired) expect() interface & functionality enhancements (c) 1999-2006 Roland Giersig. This module is now maintained by Dave Jacoby E<lt>F<jacoby@cpan.org>E<gt> =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�������!�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<agent> — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If #pod C<agent> — ends in a space character, the default user-agent string is #pod appended. #pod * C<cookie_jar> — An instance of L<HTTP::CookieJar> — or equivalent class #pod that supports the C<add> and C<cookie_header> methods #pod * C<default_headers> — A hashref of default headers to apply to requests #pod * C<local_address> — The local IP address to bind to #pod * C<keep_alive> — Whether to reuse the last connection (if for the same #pod scheme, host and port) (defaults to 1) #pod * C<max_redirect> — Maximum number of redirects allowed (defaults to 5) #pod * C<max_size> — 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<http_proxy> — URL of a proxy server to use for HTTP connections #pod (default is C<$ENV{http_proxy}> — if set) #pod * C<https_proxy> — URL of a proxy server to use for HTTPS connections #pod (default is C<$ENV{https_proxy}> — if set) #pod * C<proxy> — URL of a generic proxy server for both HTTP and HTTPS #pod connections (default is C<$ENV{all_proxy}> — if set) #pod * C<no_proxy> — 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<timeout> — 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<verify_SSL> — A boolean that indicates whether to validate the TLS/SSL #pod certificate of an C<https> — connection (default is true). Changed from false #pod to true in version 0.083. #pod * C<SSL_options> — A hashref of C<SSL_*> — options to pass through to #pod L<IO::Socket::SSL> #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<verify_SSL> 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<undef> for C<proxy>, C<http_proxy> or C<https_proxy> 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<keep_alive> 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</SSL SUPPORT> for more on the C<verify_SSL> and C<SSL_options> 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<request()> for the given method. The #pod URL must have unsafe characters escaped and international domain names encoded. #pod See C<request()> for valid options and a description of the response. #pod #pod The C<success> 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<POST> request and sends the key/value pairs from a #pod form data hash or array reference to the given URL with a C<content-type> of #pod C<application/x-www-form-urlencoded>. 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<www_form_urlencode> method for details on the encoding. #pod #pod The URL must have unsafe characters escaped and international domain names #pod encoded. See C<request()> for valid options and a description of the response. #pod Any C<content-type> header or content in the options hashref will be ignored. #pod #pod The C<success> 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<GET> 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<If-Modified-Since> header with the modification timestamp of the file. You #pod may specify a different C<If-Modified-Since> header yourself in the C<< #pod $options->{headers} >> hash. #pod #pod The C<success> 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<Last-Modified> 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<NOTE>: Method names are B<case-sensitive> per the HTTP/1.1 specification. #pod Don't use C<get> when you really want C<GET>. See L<LIMITATIONS> 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<headers> — #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<content> — #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<trailer_callback> — #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<data_callback> — #pod A code reference that will be called for each chunks of the response #pod body received. #pod * C<peer> — #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<Host> header is generated from the URL in accordance with RFC 2616. It #pod is a fatal error to specify C<Host> in the C<headers> option. Other headers #pod may be ignored or overwritten if necessary for transport compliance. #pod #pod If the C<content> 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<content> option is the empty string, no C<content-type> or #pod C<content-length> headers will be generated. #pod #pod If the C<data_callback> 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<status> or C<headers> #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<request> method returns a hashref containing the response. The hashref #pod will have the following keys: #pod #pod =for :list #pod * C<success> — #pod Boolean indicating whether the operation returned a 2XX status code #pod * C<url> — #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<status> — #pod The HTTP status code of the response #pod * C<reason> — #pod The response phrase returned by the server #pod * C<content> — #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<headers> — #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<protocol> - #pod If this field exists, it is the protocol of the response #pod such as HTTP/1.0 or HTTP/1.1 #pod * C<redirects> #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<status> field will #pod contain 599, and the C<content> 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<x-www-form-urlencoded> 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<Net::SSLeay> and L<IO::Socket::SSL>. #pod When called as an object methods, if C<SSL_verify> is true or if C<SSL_verify_mode> #pod is set in C<SSL_options>, 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<keep_alive> #pod option. #pod #pod In scalar context, returns the peer host and port, joined with a colon, or #pod C<undef> (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<Note>: 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@]<host>:<port>/\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<LWP::UserAgent>. It is more correct and more complete than L<HTTP::Lite>. It supports proxies and redirection. It also correctly resumes after EINTR. If L<IO::Socket::IP> 0.25 or later is installed, HTTP::Tiny will use it instead of L<IO::Socket::INET> for transparent support for both IPv4 and IPv6. Cookie support requires L<HTTP::CookieJar> 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<agent> — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If C<agent> — ends in a space character, the default user-agent string is appended. =item * C<cookie_jar> — An instance of L<HTTP::CookieJar> — or equivalent class that supports the C<add> and C<cookie_header> methods =item * C<default_headers> — A hashref of default headers to apply to requests =item * C<local_address> — The local IP address to bind to =item * C<keep_alive> — Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1) =item * C<max_redirect> — Maximum number of redirects allowed (defaults to 5) =item * C<max_size> — 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<http_proxy> — URL of a proxy server to use for HTTP connections (default is C<$ENV{http_proxy}> — if set) =item * C<https_proxy> — URL of a proxy server to use for HTTPS connections (default is C<$ENV{https_proxy}> — if set) =item * C<proxy> — URL of a generic proxy server for both HTTP and HTTPS connections (default is C<$ENV{all_proxy}> — if set) =item * C<no_proxy> — 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<timeout> — 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<verify_SSL> — A boolean that indicates whether to validate the TLS/SSL certificate of an C<https> — connection (default is true). Changed from false to true in version 0.083. =item * C<SSL_options> — A hashref of C<SSL_*> — options to pass through to L<IO::Socket::SSL> =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<verify_SSL> is not set. Added in version 0.083. =back An accessor/mutator method exists for each attribute. Passing an explicit C<undef> for C<proxy>, C<http_proxy> or C<https_proxy> 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<keep_alive> 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</SSL SUPPORT> for more on the C<verify_SSL> and C<SSL_options> 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<request()> for the given method. The URL must have unsafe characters escaped and international domain names encoded. See C<request()> for valid options and a description of the response. The C<success> 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<POST> request and sends the key/value pairs from a form data hash or array reference to the given URL with a C<content-type> of C<application/x-www-form-urlencoded>. 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<www_form_urlencode> method for details on the encoding. The URL must have unsafe characters escaped and international domain names encoded. See C<request()> for valid options and a description of the response. Any C<content-type> header or content in the options hashref will be ignored. The C<success> 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<GET> 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<If-Modified-Since> header with the modification timestamp of the file. You may specify a different C<If-Modified-Since> header yourself in the C<< $options->{headers} >> hash. The C<success> 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<Last-Modified> 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<NOTE>: Method names are B<case-sensitive> per the HTTP/1.1 specification. Don't use C<get> when you really want C<GET>. See L<LIMITATIONS> 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<headers> — 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<content> — 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<trailer_callback> — 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<data_callback> — A code reference that will be called for each chunks of the response body received. =item * C<peer> — 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<Host> header is generated from the URL in accordance with RFC 2616. It is a fatal error to specify C<Host> in the C<headers> option. Other headers may be ignored or overwritten if necessary for transport compliance. If the C<content> 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<content> option is the empty string, no C<content-type> or C<content-length> headers will be generated. If the C<data_callback> 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<status> or C<headers> 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<request> method returns a hashref containing the response. The hashref will have the following keys: =over 4 =item * C<success> — Boolean indicating whether the operation returned a 2XX status code =item * C<url> — 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<status> — The HTTP status code of the response =item * C<reason> — The response phrase returned by the server =item * C<content> — 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<headers> — 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<protocol> - If this field exists, it is the protocol of the response such as HTTP/1.0 or HTTP/1.1 =item * C<redirects> 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<status> field will contain 599, and the C<content> 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<x-www-form-urlencoded> 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<Net::SSLeay> and L<IO::Socket::SSL>. When called as an object methods, if C<SSL_verify> is true or if C<SSL_verify_mode> is set in C<SSL_options>, 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<keep_alive> option. In scalar context, returns the peer host and port, joined with a colon, or C<undef> (if no peer is connected). In list context, returns the peer host and port or an empty list (if no peer is connected). B<Note>: 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<https> connections are supported only if L<IO::Socket::SSL> 1.56 or greater and L<Net::SSLeay> 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<HTTP::Tiny::can_ssl()> utility function that returns boolean to see if the required modules are installed. An C<https> connection may be made via an C<http> proxy that supports the CONNECT command (i.e. RFC 2817). You may not proxy C<https> via a proxy that itself requires C<https> to communicate. TLS/SSL provides two distinct capabilities: =over 4 =item * Encrypted communication channel =item * Verification of server identity =back B<By default, HTTP::Tiny verifies server identity>. 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<machine-in-the-middle attacks|http://en.wikipedia.org/wiki/Machine-in-the-middle_attack>. Certificate verification requires a file containing trusted CA certificates. If the environment variable C<SSL_CERT_FILE> is present, HTTP::Tiny will try to find a CA certificate file in that location. If the L<Mozilla::CA> 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<verify_SSL> is true and no CA certificate file is available. If you desire complete control over TLS/SSL connections, the C<SSL_options> attribute lets you provide a hash reference that will be passed through to C<IO::Socket::SSL::start_SSL()>, 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<SSL_options> 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<IO::Socket::SSL> documentation for details. =head1 PROXY SUPPORT HTTP::Tiny can proxy both C<http> and C<https> requests. Only Basic proxy authorization is supported and it must be provided as part of the proxy URL: C<http://user:pass@proxy.example.com/>. 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<REQUEST_METHOD> environment variable is set, then this might be a CGI process and C<HTTP_PROXY> would be set from the C<Proxy:> header, which is a security risk. If C<REQUEST_METHOD> is set, C<HTTP_PROXY> (the upper case variant only) is ignored, but C<CGI_HTTP_PROXY> is considered instead. Tunnelling C<https> over an C<http> proxy using the CONNECT method is supported. If your proxy uses C<https> itself, you can not tunnel C<https> over it. Be warned that proxying an C<https> connection opens you to the risk of a man-in-the-middle attack by the proxy server. The C<no_proxy> 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<new> will override their corresponding environment variables. =head1 LIMITATIONS HTTP::Tiny is I<conditionally compliant> with the L<HTTP/1.1 specifications|http://www.w3.org/Protocols/>: =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<PATCH> 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<URI::Escape>, L<URI::_punycode> and L<Net::IDN::Encode>. =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<Expect> header. Unexpected C<1XX> responses are silently ignored as per the specification. =item * Only 'chunked' C<Transfer-Encoding> 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<HTTP::Tiny::UA>. =head1 SEE ALSO =over 4 =item * L<HTTP::Tiny::UA> - Higher level UA features for HTTP::Tiny =item * L<HTTP::Thin> - HTTP::Tiny wrapper with L<HTTP::Request>/L<HTTP::Response> compatibility =item * L<HTTP::Tiny::Mech> - Wrap L<WWW::Mechanize> instance in HTTP::Tiny compatible interface =item * L<IO::Socket::IP> - Required for IPv6 support =item * L<IO::Socket::SSL> - Required for SSL support =item * L<LWP::UserAgent> - If HTTP::Tiny isn't enough for you, this is the "standard" way to do things =item * L<Mozilla::CA> - Required if you want to validate SSL certificates =item * L<Net::SSLeay> - 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<https://github.com/Perl-Toolchain-Gang/HTTP-Tiny/issues>. 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<https://github.com/Perl-Toolchain-Gang/HTTP-Tiny> git clone https://github.com/Perl-Toolchain-Gang/HTTP-Tiny.git =head1 AUTHORS =over 4 =item * Christian Hansen <chansen@cpan.org> =item * David Golden <dagolden@cpan.org> =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 <gardner@pythian.com> =item * Alessandro Ghedini <al3xbio@gmail.com> =item * A. Sinan Unur <nanis@cpan.org> =item * Brad Gilbert <bgills@cpan.org> =item * brian m. carlson <sandals@crustytoothpaste.net> =item * Chris Nehren <apeiron@cpan.org> =item * Chris Weyl <cweyl@alumni.drew.edu> =item * Claes Jakobsson <claes@surfar.nu> =item * Clinton Gormley <clint@traveljury.com> =item * Craig A. Berry <craigberry@mac.com> =item * Craig Berry <cberry@cpan.org> =item * David Golden <xdg@xdg.me> =item * David Mitchell <davem@iabyn.com> =item * Dean Pearce <pearce@pythian.com> =item * Edward Zborowski <ed@rubensteintech.com> =item * Felipe Gasper <felipe@felipegasper.com> =item * Graham Knop <haarg@haarg.org> =item * Greg Kennedy <kennedy.greg@gmail.com> =item * James E Keenan <jkeenan@cpan.org> =item * James Raspass <jraspass@gmail.com> =item * Jeremy Mates <jmates@cpan.org> =item * Jess Robinson <castaway@desert-island.me.uk> =item * Karen Etheridge <ether@cpan.org> =item * Lukas Eklund <leklund@gmail.com> =item * Martin J. Evans <mjegh@ntlworld.com> =item * Martin-Louis Bright <mlbright@gmail.com> =item * Matthew Horsfall <wolfsage@gmail.com> =item * Michael R. Davis <mrdvt92@users.noreply.github.com> =item * Mike Doherty <doherty@cpan.org> =item * Nicolas Rochelemagne <rochelemagne@cpanel.net> =item * Olaf Alders <olaf@wundersolutions.com> =item * Olivier Mengué <dolmen@cpan.org> =item * Petr Písař <ppisar@redhat.com> =item * sanjay-cpu <snjkmr32@gmail.com> =item * Serguei Trouchelle <stro@cpan.org> =item * Shoichi Kaji <skaji@cpan.org> =item * SkyMarshal <skymarshal1729@gmail.com> =item * Sören Kornetzki <soeren.kornetzki@delti.com> =item * Steve Grazzini <steve.grazzini@grantstreet.com> =item * Stig Palmquist <git@stig.io> =item * Syohei YOSHIDA <syohex@gmail.com> =item * Tatsuhiko Miyagawa <miyagawa@bulknews.net> =item * Tom Hukins <tom@eborcom.com> =item * Tony Cook <tony@develop-help.com> =item * Xavier Guimard <yadd@debian.org> =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�������!�-*��*����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<Makefile.PL> in L<Coro> or L<AnyEvent> 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 <<EOF; *** *** Canary::Stability COMPATIBILITY AND SUPPORT CHECK *** ================================================= *** *** Hi! *** *** I do my best to provide predictable and reliable software. *** *** However, in recent releases, P5P (who maintain perl) have been *** introducing regressions that are sometimes subtle and at other times *** catastrophic, often for personal preferences with little or no concern *** for existing code, most notably CPAN. *** *** For this reason, it has become very hard for me to maintain the level *** of reliability and support I have committed myself to in the past, at *** least with some perl versions: I simply can't keep up working around new *** bugs or gratituous incompatibilities, and in turn you might suffer from *** unanticipated problems. *** *** Therefore I have introduced a support and compatibility check, the results *** of which follow below, together with a FAQ and some recommendations. *** *** This check is just to let you know that there might be a risk, so you can *** make judgement calls on how to proceed - it will not keep the module from *** installing or working. *** EOF if ($minvers > $VERSION) { sgr 33; print <<EOF; *** The stability canary says: (nothing, it died of old age). *** *** Your Canary::Stability module (used by $distname) is too old. *** This is not a fatal problem - while you might want to upgrade to version *** $minvers (currently installed version: $VERSION) to get better support *** status testing, you might also not want to care at all, and all will *** be well as long $distname works well enough for you, as the stability *** canary is only used when installing the distribution. *** EOF } elsif ($] < $minperl) { sgr 33; print <<EOF; *** The stability canary says: chirp (it seems concerned about something). *** *** Your perl version ($]) is older than the $distname distribution *** likes ($minperl). This is not a fatal problem - the module might work *** well with your version of perl, but it does mean the author likely *** won't do anything to make it work if it breaks. *** EOF if ($ENV{AUTOMATED_TESTING}) { print <<EOF; *** Since this is an AUTOMATED_TESTING environment, the stability canary *** decided to fail cleanly here, rather than to generate a false test *** result. *** EOF exit 0; } } elsif (defined $Internals::StabilityBranchVersion) { # note to people studying this modules sources: # the above test is not considered a clean or stable way to # test for the stability branch. sgr 32; print <<EOF; *** The stability canary says: chirp! chirp! (it seems to be quite excited) *** *** It seems you are running schmorp's stability branch of perl. *** All should be well, and if it isn't, you should report this as a bug *** to the $distname author. *** EOF } elsif ($] < 5.021) { #sgr 32; print <<EOF; *** The stability canary says: chirp! chirp! (it seems to be quite happy) *** *** Your version of perl ($]) is quite supported by $distname, nothing *** else to be said, hope it comes in handy. *** EOF } else { sgr 31; print <<EOF; *** The stability canary says: (nothing, it was driven away by harsh weather) *** *** It seems you are running perl version $], likely the "official" or *** "standard" version. While there is nothing wrong with doing that, *** standard perl versions 5.022 and up are not supported by $distname. *** While this might be fatal, it might also be all right - if you run into *** problems, you might want to downgrade your perl or switch to the *** stability branch. *** *** If everything works fine, you can ignore this message. *** EOF sgr 0; print <<EOF; *** *** Stability canary mini-FAQ: *** *** Do I need to do anything? *** With luck, no. While some distributions are known to fail *** already, most should probably work. This message is here *** to alert you that your perl is not supported by $distname, *** and if things go wrong, you either need to downgrade, or *** sidegrade to the stability variant of your perl version, *** or simply live with the consequences. *** *** What is this canary thing? *** It's purpose is to check support status of $distname with *** respect to your perl version. *** *** What is this "stability branch"? *** It's a branch or fork of the official perl, by schmorp, to *** improve stability and compatibility with existing modules. *** *** How can I skip this prompt on automated installs? *** Set PERL_CANARY_STABILITY_NOPROMPT=1 in your environment. *** More info is in the Canary::Stability manpage. *** *** Long version of this FAQ: http://stableperl.schmorp.de/faq.html *** Stability Branch homepage: http://stableperl.schmorp.de/ *** EOF unless ($ENV{PERL_CANARY_STABILITY_NOPROMPT}) { require ExtUtils::MakeMaker; ExtUtils::MakeMaker::prompt ("Continue anyways? ", "y") =~ /^y/i or die "FATAL: User aborted configuration of $distname.\n"; } } sgr 0; } =head1 ENVIRONMENT VARIABLES =over 4 =item C<PERL_CANARY_STABILITY_NOPROMPT=1> Do not prompt the user on alert messages. =item C<PERL_CANARY_STABILITY_COLOUR=0> Disable use of colour. =item C<PERL_CANARY_STABILITY_COLOUR=1> Force use of colour. =item C<PERL_CANARY_STABILITY_DISABLE=1> Disable this modules functionality completely. =item C<AUTOMATED_TESTING=1> 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 <schmorp@schmorp.de> http://software.schmorp.de/pkg/Canary-Stability.html =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<Types::Serialiser> for more info about this class. =cut use Types::Serialiser (); =head1 AUTHOR Marc Lehmann <schmorp@schmorp.de> http://home.schmorp.de/ =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.01'; =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. In the following, functions with zero or one arguments have a prototype of C<()> and C<($)>, respectively, so act as constants and unary operators. =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<Types::Serialiser::true>). 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<Types::Serialiser::false>). The constant is represented as a reference to a scalar containing C<0> - implementations are allowed to directly test for this. =item Types::Serialiser::as_bool $value Converts a Perl scalar into a boolean, which is useful syntactic sugar. Strictly equivalent to: $value ? $Types::Serialiser::true : $Types::Serialiser::false =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<Types::Serialiser::true> 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<error>. 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<undef> - 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 as_bool($) { $_[0] ? $true : $false } 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<Types::Serialiser::Boolean> or C<Types::Serialiser::Error> stash, and then follow the scalar reference to see if it's C<1> (true), C<0> (false) or C<undef> (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<Types::Serialiser::Boolean> stash is just an alias for C<JSON::PP::Boolean>. When printed, the classname with usually be C<JSON::PP::Boolean>, 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<CBOR::XS>. 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<CBOR::XS> can encode a few special types itself, and will first attempt to use the special C<TO_CBOR> serialisation protocol), it will look up the C<FREEZE> method on the object. Note that the C<FREEZE> method will normally be called I<during> encoding, and I<MUST NOT> 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<CBOR::XS> uses C<CBOR>, and the L<JSON> and L<JSON::XS> modules (or any other JSON serialiser), would use C<JSON> as second argument. The C<FREEZE> 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<FREEZE> 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<FREEZE>. For example, in C<CBOR> it is permissible to return tagged CBOR values, while JSON does not support these at all, so C<JSON> would be a valid (but too limited) data model name for C<CBOR::XS>. similarly, a serialising format that supports more or less the same data model as JSON could use C<JSON> as data model without losing anything. =head2 DECODING When the decoder then encounters such an encoded perl object, it should look up the C<THAW> 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<FREEZE>. =head2 EXAMPLES See the C<OBJECT SERIALISATION> section in the L<CBOR::XS> manpage for more details, an example implementation, and code examples. Here is an example C<FREEZE>/C<THAW> 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<overload> makes this module much heavier than it should be (on my system, this module: 4kB RSS, overload: 260kB RSS). =head1 SEE ALSO Currently, L<JSON::XS> and L<CBOR::XS> use these types. =head1 AUTHOR Marc Lehmann <schmorp@schmorp.de> http://home.schmorp.de/ =cut 1 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</Unterschiede bei Benutzung dieses Module mit Win32>. 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<source ~/.cshrc> 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<CMD.EXE> 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<App::local::lib::Win32Helper> 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<SHELL> 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<lib::core::only> 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</build_environment_vars_for>. =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<lib> und C<perl5> 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</install_base_perl_path> 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</install_base_perl_path> Rückgabewert, hängt diese Methode noch C<bin> 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</resolve_empty_path>, L</resolve_home_path>, L</resolve_relative_path>. Der daraus resultierende Pfad wird zu L</resolve_empty_path> übergeben, dessen Resultat dann weitergegeben wird an L</resolve_home_path>, wessen Resultat dann weitergegeben wird an L</resolve_relative_path>. Dieses Resultat wird dann final an L</resolve_path> ü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<nach> 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<SHELL> 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<cpan -i Foo::Bar> ein Modul zu installieren, und dabei einen Fehler bekommst, wie: C<Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm> 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<rm -r ~/.cpan/build/Foo-Bar*> Abschliessend dann nochmal mit C<cpan -i Foo::Bar> installieren und die Probleme sollten verschwunden sein. =head1 UMGEBUNGSVARIABLEN =over 4 =item SHELL =item COMSPEC local::lib schaut in die C<SHELL> Umgebungsvariable um die korrekten Kommandos zu der Shell Konfiguration hinzuzufügen. Auf Win32 Systemen, C<COMSPEC> 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 <torsten@raudssus.de> http://www.raudssus.de/ =head1 URHEBERRECHT Copyright (c) 2007 - 2010 von den local::lib L<local::lib/"AUTHOR"> und L<local::lib/"CONTRIBUTORS"> aufgelistet in L<local::lib|local::lib>. =head1 LIZENZ Diese Sammlung ist freie Software und kann unter der selben Lizenz verbreitet werden wie Perl selber. =cut 1; 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</Diferenças ao usar esse módulo em Win32>. 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<source ~/.cshrc>. 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<CMD.exe>, 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<App::local::lib::Win32Helper>. 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<SHELL>), 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<import>, 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<import>. =head1 CRIANDO UM CONJUNTO AUTO-CONTIDO DE MÓDULOS Veja L<lib::core::only|lib::core::only> 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<build_environment_vars_for>. =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<lib> e C<perl5> 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</install_base_perl_path>, 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</install_base_perl_path>, adicionando o diretório C<bin>. =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</resolve_empty_path>, L</resolve_home_path>, L</resolve_relative_path>. Passa o caminho de diretório fornecido para L</resolve_empty_path> que retorna um resultado que é passado para L</resolve_home_path>, que então tem seu resultado passado para L</resolve_relative_path>. O resultado dessa chamada final é então retornado pelo L</resolve_path>. =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<após> 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<SHELL> 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<cpan -i Foo::Bar>, mas ele falhou com um erro como: C<Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm> 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<rm -r ~/.cpan/build/Foo-Bar*> Finalmente, execute novamente o C<cpan -i Foo::Bar> e ele deve instalar sem problemas. =head1 AMBIENTE =over 4 =item SHELL =item COMSPEC O local::lib procura pela variável de ambiente C<SHELL> do usuário ao processar e exibir os comandos a serem adicionados no arquivo de configuração da shell. Em sistemas Win32, C<COMSPEC> 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<< <garu at cpan.org> >>, após ter perdido uma aposta para o L<Getty|http://search.cpan.org/~getty/> durante a Copa de 2010. =head1 COPYRIGHT Copyright (c) 2007 - 2010 L<local::lib/"AUTHOR"> e L<local::lib/"CONTRIBUTORS"> do local::lib como listados em L<local::lib>. =head1 LICENÇA Esta biblioteca é software livre e pode ser distribuída sob os mesmo termos do perl. 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<local::lib> twice for this to work. First so that C<lib::core::only> doesn't prevent C<local::lib> from loading (it's not currently in core) and then again after C<lib::core::only> 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<App::FatPacker|App::FatPacker> 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</CAVEATS>). This module was extracted from L<local::lib|local::lib>'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<not> propagate properly across perl invocations like local::lib's stuff does. It can't. It's only a module import, so it B<only affects the specific perl VM instance in which you load and import() it>. 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<lib|lib> 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<http://www.shadowcat.co.uk/blog/matt-s-trout/tainted-love> - and for ways to achieve the old --self-contained feature's results, look at L<App::FatPacker|App::FatPacker>'s tree function, and at L<App::cpanminus|cpanm>'s --local-lib-contained feature. =head1 AUTHOR Matt S. Trout <mst@shadowcat.co.uk> =head1 LICENSE This library is free software under the same terms as perl itself. =head1 COPYRIGHT (c) 2010 the lib::core::only L</AUTHOR> as specified above. =cut 1; 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</Differences when using this module under Win32>. =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<source ~/.cshrc>. =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<local::lib> 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<activated most recently> 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<local::lib> 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<CMD.exe>, 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<App::local::lib::Win32Helper>. 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<Invoke-Expression> 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<SHELL> 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<lib::core::only> 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<local::lib> import besides the directory to use. They are specified as C<use local::lib '--option'[, path];> or C<perl -Mlocal::lib=--option[,path]>. =head2 --deactivate Remove the chosen path (or the default path) from the module search paths if it was added by C<local::lib>, instead of adding it. =head2 --deactivate-all Remove all directories that were added to search paths by C<local::lib> 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<bourne>, C<csh>, C<cmd>, or C<powershell>. =head2 --no-create Prevents C<local::lib> 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</build_environment_vars_for>. =head2 active_paths =over 4 =item Arguments: None =item Return value: @paths =back Returns a list of active C<local::lib> paths, according to the C<PERL_LOCAL_LIB_ROOT> 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<lib> and C<perl5> 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<bin> 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</resolve_empty_path>, L</resolve_home_path>, L</resolve_relative_path>. Passes the given path argument to L</resolve_empty_path> which then returns a result that is passed to L</resolve_home_path>, which then has its result passed to L</resolve_relative_path>. The result of this final call is returned from L</resolve_path>. =head1 OBJECT INTERFACE =head2 new =over 4 =item Arguments: %attributes =item Return value: $local_lib =back Constructs a new C<local::lib> object, representing the current state of C<@INC> and the relevant environment variables. =head1 ATTRIBUTES =head2 roots An arrayref representing active C<local::lib> 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<PERL_MM_OPT> and C<PERL_MB_OPT>) =head2 no_create If set, C<local::lib> 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<local::lib> 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<local::lib> 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<local::lib>, 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</build_environment_vars>. =head2 setup_local_lib Constructs the C<%ENV> hash using L</setup_env_hash>, 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<after> 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<SHELL> 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<File::Spec>. This means any L<File::Spec> version installed in the local::lib will be ignored by scripts using local::lib. A workaround for this is using C<use lib "$local_lib/lib/perl5";> instead of using C<local::lib> directly. =item * Conflicts with L<ExtUtils::MakeMaker>'s C<PREFIX> option. C<local::lib> uses the C<INSTALL_BASE> option, as it has more predictable and sane behavior. If something attempts to use the C<PREFIX> option when running a F<Makefile.PL>, L<ExtUtils::MakeMaker> will refuse to run, as the two options conflict. This can be worked around by temporarily unsetting the C<PERL_MM_OPT> environment variable. =item * Conflicts with L<Module::Build>'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<PERL_MB_OPT> 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<cpan -i Foo::Bar>, but it fails with an error like: C<Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm> 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<rm -r ~/.cpan/build/Foo-Bar*> Finally, re-run C<cpan -i Foo::Bar> and it should install without problems. =head1 ENVIRONMENT =over 4 =item SHELL =item COMSPEC local::lib looks at the user's C<SHELL> environment variable when printing out commands to add to the shell configuration file. On Win32 systems, C<COMSPEC> is also examined. =back =head1 SEE ALSO =over 4 =item * L<Perl Advent article, 2011|http://perladvent.org/2011/2011-12-01.html> =back =head1 SUPPORT IRC: Join #toolchain on irc.perl.org. =head1 AUTHOR Matt S Trout <mst@shadowcat.co.uk> 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 <apeiron@cpan.org>. Doc patches for a custom local::lib directory, more cleanups in the english documentation and a L<german documentation|POD2::DE::local::lib> contributed by Torsten Raudssus <torsten@raudssus.de>. Hans Dieter Pearcey <hdp@cpan.org> 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 <csjewell@cpan.org>. Warnings for missing PATH/PERL5LIB (as when not running interactively) silenced by a patch from Marco Emilio Poleggi. Mark Stosberg <mark@summersault.com> provided the code for the now deleted '--self-contained' option. Documentation patches to make win32 usage clearer by David Mertens <dcmertens.perl@gmail.com> (run4flat). Brazilian L<portuguese translation|POD2::PT_BR::local::lib> and minor doc patches contributed by Breno G. de Oliveira <garu@cpan.org>. Improvements to stacking multiple local::lib dirs and removing them from the environment later on contributed by Andrew Rodland <arodland@cpan.org>. Patch for Carp version mismatch contributed by Hakim Cassimally <osfameron@cpan.org>. Rewrite of internals and numerous bug fixes and added features contributed by Graham Knop <haarg@haarg.org>. =head1 COPYRIGHT Copyright (c) 2007 - 2013 the local::lib L</AUTHOR> and L</CONTRIBUTORS> 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�������!�X6qR��R����perl5/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<for> # 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<try> and C<catch> 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<eval> 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<try>/C<catch>/C<finally> statements that are designed to minimize common mistakes with eval blocks, and NOTHING else. This is unlike L<TryCatch> which provides a nice syntax and avoids adding another call stack layer, and supports calling C<return> from the C<try> block to return from the parent subroutine. These extra features come at a cost of a few dependencies, namely L<Devel::Declare> and L<Scope::Upper> which are occasionally problematic, and the additional catch filtering uses L<Moose> 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<TryCatch>, but who still want to write correct C<eval> 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</BACKGROUND>) and to be compatible with any style of error values (simple strings, references, objects, overloaded objects, etc). If the C<try> block dies, it returns the value of the last statement executed in the C<catch> block, if there is one. Otherwise, it returns C<undef> 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<finally> blocks, yielding the following: my $x; try { die 'foo' } finally { $x = 'bar' }; try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' }; C<finally> blocks are always executed making them suitable for cleanup code which cannot be handled using local. You can add as many C<finally> blocks to a given C<try> block as you like. Note that adding a C<finally> block without a preceding C<catch> block suppresses any errors. This behaviour is consistent with using a standalone C<eval>, but it is not consistent with C<try>/C<finally> patterns found in other programming languages, such as Java, Python, Javascript or C#. If you learned the C<try>/C<finally> pattern from one of these languages, watch out for this. =head1 EXPORTS All functions are exported by default using L<Exporter>. If you need to rename the C<try>, C<catch> or C<finally> keyword consider using L<Sub::Import> to get L<Sub::Exporter>'s flexibility. =over 4 =item try (&;@) Takes one mandatory C<try> subroutine, an optional C<catch> subroutine and C<finally> subroutine. The mandatory subroutine is evaluated in the context of an C<eval> 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<not> contain the error. Inside the C<catch> block it has the same value it had before the C<try> block was executed. Note that the error may be false, but if that happens the C<catch> block will still be invoked. Once all execution is finished then the C<finally> block, if given, will execute. =item catch (&;@) Intended to be used in the second argument position of C<try>. Returns a reference to the subroutine it was given but blessed as C<Try::Tiny::Catch> which allows try to decode correctly what to do with this code reference. catch { ... } Inside the C<catch> 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<try>, 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<Class::Throwable>), 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<try>. C<finally> blocks are always executed in the event of a successful C<try> or if C<catch> is run. This allows you to locate cleanup code which cannot be done via C<local()> e.g. closing a file handle. When invoked, the C<finally> block is passed the error that was caught. If no error was caught, it is passed nothing. (Note that the C<finally> block does not localize C<$_> with the error, since unlike in a C<catch> 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<You must always do your own error handling in the C<finally> block>. C<Try::Tiny> will not do anything about handling possible errors coming from code located in these blocks. Furthermore B<exceptions in C<finally> blocks are not trappable and are unable to influence the execution of your program>. This is due to limitation of C<DESTROY>-based scope guards, which C<finally> is implemented on top of. This may change in a future version of Try::Tiny. In the same way C<catch()> blesses the code reference this subroutine does the same except it bless them as C<Try::Tiny::Finally>. =back =head1 BACKGROUND There are a number of issues with C<eval>. =head2 Clobbering $@ When you run an C<eval> 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<eval> in order to avoid this issue. More specifically, L<before Perl version 5.14.0|perl5140delta/"Exception Handling"> C<$@> was clobbered at the beginning of the C<eval>, 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<try> will actually set C<$@> to its previous value (the one available before entering the C<try> block) in the beginning of the C<eval> block. =head2 Localizing $@ silently masks errors Inside an C<eval> block, C<die> 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<Perl 5.14.0|perl5140delta/"Exception Handling">) is: sub Object::DESTROY { eval { ... } } eval { my $obj = Object->new; die "foo"; }; if ( $@ ) { } In this case since C<Object::DESTROY> is not localizing C<$@> but still uses C<eval>, it will set C<$@> to C<"">. The destructor is called when the stack is unwound, after C<die> sets C<$@> to C<"foo at Foo.pm line 42\n">, so by the time C<if ( $@ )> is evaluated it has been cleared by C<eval> 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<eval> was aborted due to an error: my $failed = not eval { ... return 1; }; This is because an C<eval> that caught a C<die> will always return a false value. =head1 ALTERNATE SYNTAX Using Perl 5.10 you can use L<perlsyn/"Switch statements"> (but please don't, because that syntax has since been deprecated because there was too much unexpected magical behaviour). =for stopwords topicalizer The C<catch> block is invoked in a topicalizer context (like a C<given> block), but note that you can't return a useful value from C<catch> using the C<when> blocks without an explicit C<return>. This is somewhat similar to Perl 6's C<CATCH> 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<try> 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<return> returns from the C<try> block, not from the parent sub (note that this is also how C<eval> works, but not how L<TryCatch> 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<catch> block, it must return C<undef> for this to work, since if a C<catch> block exists, its return value is returned in place of C<undef> when an exception is thrown. =item * C<try> introduces another caller stack frame. L<Sub::Uplevel> is not used. L<Carp> 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<catch> block is not guaranteed to be the value of the exception thrown (C<$@>) in the C<try> block. There is no safe way to ensure this, since C<eval> may be used unhygienically in destructors. The only guarantee is that the C<catch> will be called if an exception is thrown. =item * The return value of the C<catch> 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<catch> 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<eval> blocks, since it isn't people have grown to rely on it. Therefore in the interests of compatibility, C<try> does not disable C<$SIG{__DIE__}> for the scope of the error throwing code. =item * Lexical C<$_> may override the one set by C<catch>. For example Perl 5.10's C<given> 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<Perl5 version 18|https://metacpan.org/module/perldelta#given-now-aliases-the-global-_>. However, since the entirety of lexical C<$_> is now L<considered experimental |https://metacpan.org/module/perldelta#Lexical-_-is-now-experimental>, it is unclear whether the new version 18 behavior is final. =back =head1 SEE ALSO =over 4 =item L<Syntax::Keyword::Try> 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<return> and C<next> within it). Use L<Feature::Compat::Try> to automatically switch to the native C<try> syntax in newer perls (when available). See also L<Try Catch Exception Handling|perlsyn/Try-Catch-Exception-Handling>. =item L<TryCatch> Much more feature complete, more convenient semantics, but at the cost of implementation complexity. =item L<autodie> Automatic error throwing for builtin functions and more. Also designed to work well with C<given>/C<when>. =item L<Throwable> A lightweight role for rolling your own exception classes. =item L<Error> Exception object implementation with a C<try> statement. Does not localize C<$@>. =item L<Exception::Class::TryCatch> Provides a C<catch> statement, but properly calling C<eval> is your responsibility. The C<try> 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<http://web.archive.org/web/20100628040134/http://nothingmuch.woobling.org/talks/takahashi.xul> Or read the source: L<http://web.archive.org/web/20100305133605/http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml> =head1 SUPPORT Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=Try-Tiny> (or L<bug-Try-Tiny@rt.cpan.org|mailto:bug-Try-Tiny@rt.cpan.org>). =head1 AUTHORS =over 4 =item * יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org> =item * Jesse Luehrs <doy@tozt.net> =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 <ether@cpan.org> =item * Peter Rabbitson <ribasushi@cpan.org> =item * Ricardo Signes <rjbs@cpan.org> =item * Mark Fowler <mark@twoshortplanks.com> =item * Graham Knop <haarg@haarg.org> =item * Aristotle Pagaltzis <pagaltzis@gmx.de> =item * Dagfinn Ilmari Mannsåker <ilmari@ilmari.org> =item * Lukas Mai <l.mai@web.de> =item * Alex <alex@koban.(none)> =item * anaxagoras <walkeraj@gmail.com> =item * Andrew Yates <ayates@haddock.local> =item * awalker <awalker@sourcefire.com> =item * chromatic <chromatic@wgz.org> =item * cm-perl <cm-perl@users.noreply.github.com> =item * David Lowe <davidl@lokku.com> =item * Glenn Fowler <cebjyre@cpan.org> =item * Hans Dieter Pearcey <hdp@weftsoar.net> =item * Jens Berthold <jens@jebecs.de> =item * Jonathan Yu <JAWNSY@cpan.org> =item * Marc Mims <marc@questright.com> =item * Mark Stosberg <mark@stosberg.com> =item * Pali <pali@cpan.org> =item * Paul Howarth <paul@city-fan.org> =item * Rudolf Leermakers <rudolf@hatsuseno.org> =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���������!�ɋ8/��8/������������������man/man1/cpan.1nu�6$��������PK���������!�y¬����������������w/��man/man1/cpan-mirrors.1nu�6$��������PK���������!�=؝!��!��������������I��man/man1/json_xs.1nu�6$��������PK���������!�EX:2��2��������������j��man/man3/App::Cpan.3pmnu�6$��������PK���������!�[/�/������������� ��man/man3/CPAN.3pmnu�6$��������PK���������!�< �� ��������������|_�man/man3/CPAN::API::HOWTO.3pmnu�6$��������PK���������!�?&��&��������������m�man/man3/CPAN::Admin.3pmnu�6$��������PK���������!�stb ��b ��������������5�man/man3/CPAN::Debug.3pmnu�6$��������PK���������!�a!����������������߈�man/man3/CPAN::Distroprefs.3pmnu�6$��������PK���������!� m�� m���������������man/man3/CPAN::FirstTime.3pmnu�6$��������PK���������!�j, �� ��������������N�man/man3/CPAN::HandleConfig.3pmnu�6$��������PK���������!�lg �� ���������������man/man3/CPAN::Kwalify.3pmnu�6$��������PK���������!�*'E"��"��������������)�man/man3/CPAN::Mirrors.3pmnu�6$��������PK���������!�އg! ��! ��������������L�man/man3/CPAN::Nox.3pmnu�6$��������PK���������!� �� ��������������-X�man/man3/CPAN::Plugin.3pmnu�6$��������PK���������!�&D����#������������]f�man/man3/CPAN::Plugin::Specfile.3pmnu�6$��������PK���������!�u�Tf ��f ��������������du�man/man3/CPAN::Queue.3pmnu�6$��������PK���������!�Jt ��t ���������������man/man3/CPAN::Tarzip.3pmnu�6$��������PK���������!�Hy �� ��������������ψ�man/man3/CPAN::Version.3pmnu�6$��������PK���������!�5ܚ1��1��%�������������man/man3/CPAN::Meta::Requirements.3pmnu�6$��������PK���������!�W]# %��%��,�������������man/man3/CPAN::Meta::Requirements::Range.3pmnu�6$��������PK���������!�z!��!��������������x�man/man3/IO::Pty.3pmnu�6$��������PK���������!� �� ��������������;�man/man3/IO::Tty.3pmnu�6$��������PK���������!�N)<w%��%��������������'�man/man3/IO::Tty::Constant.3pmnu�6$��������PK���������!�L��L��������������SM�man/man3/Expect.3pmnu�6$��������PK���������!�E4n��n��������������:�man/man3/HTTP::Tiny.3pmnu�6$��������PK���������!�/L��L���������������man/man3/Canary::Stability.3pmnu�6$��������PK���������!�������������������������T�man/man3/common::sense.3pmnu�6$��������PK���������!�O.��.���������������man/man3/Types::Serialiser.3pmnu�6$��������PK���������!�u{ �� ��%�������������man/man3/Types::Serialiser::Error.3pmnu�6$��������PK���������!�qo[�[��������������man/man3/JSON::XS.3pmnu�6$��������PK���������!�D% ��% ��������������P�man/man3/JSON::XS::Boolean.3pmnu�6$��������PK���������!� Y�� Y��!������������ \�man/man3/POD2::DE::local::lib.3pmnu�6$��������PK���������!�+YҚX��X��$������������f�man/man3/POD2::PT_BR::local::lib.3pmnu�6$��������PK���������!� , �� ��������������T�man/man3/lib::core::only.3pmnu�6$��������PK���������!�r4J|��|��������������$�man/man3/local::lib.3pmnu�6$��������PK���������!�+ihA@Q��@Q���������������man/man3/Try::Tiny.3pmnu�6$��������PK���������!�j:��j:���������������man/man3/version.3pmnu�6$��������PK���������!�F?sDo��Do��������������6- �man/man3/version::Internals.3pmnu�6$��������PK���������!�W����������������ɜ �man/man3/JSON::Syck.3pmnu�6$��������PK���������!��I*��I*�������������� �man/man3/YAML::Syck.3pmnu�6$��������PK���������!�q����������������: �perl5/cPanelUserConfig.pmnu�[��������PK���������!�Q���������������� �perl5/App/Cpan.pmnu�6$��������PK���������!�}l+��+�������������� �perl5/CPAN/API/HOWTO.podnu�6$��������PK���������!�ܑH����*������������ �perl5/CPAN/Exception/yaml_process_error.pmnu�6$��������PK���������!�1.��.��+������������ �perl5/CPAN/Exception/RecursiveDependency.pmnu�6$��������PK���������!�T����*������������ �perl5/CPAN/Exception/yaml_not_installed.pmnu�6$��������PK���������!�*^����'������������֥ �perl5/CPAN/Exception/blocked_urllist.pmnu�6$��������PK���������!�H����������������ũ �perl5/CPAN/FTP/netrc.pmnu�6$��������PK���������!�(��(��������������& �perl5/CPAN/HTTP/Client.pmnu�6$��������PK���������!�3yI ��I �������������� �perl5/CPAN/HTTP/Credentials.pmnu�6$��������PK���������!�w)#9��9��"������������. �perl5/CPAN/Kwalify/distroprefs.ymlnu�6$��������PK���������!�< �� ��!������������ �perl5/CPAN/Kwalify/distroprefs.ddnu�6$��������PK���������!�>+���������������� �perl5/CPAN/LWP/UserAgent.pmnu�6$��������PK���������!�z¤!��!�������������� �perl5/CPAN/Plugin/Specfile.pmnu�6$��������PK���������!�z6��6�������������� �perl5/CPAN/Debug.pmnu�6$��������PK���������!�Ʈޒw^��w^�������������� �perl5/CPAN/HandleConfig.pmnu�6$��������PK���������!�n3y.��.��������������R �perl5/CPAN/Version.pmnu�6$��������PK���������!�Bo��o��������������Ő �perl5/CPAN/Admin.pmnu�6$��������PK���������!�$d ��d ��������������w �perl5/CPAN/Kwalify.pmnu�6$��������PK���������!�ך9L��L�������������� �perl5/CPAN/URL.pmnu�6$��������PK���������!�Ч���������������� �perl5/CPAN/InfoObj.pmnu�6$��������PK���������!�7S���������������� �perl5/CPAN/Author.pmnu�6$��������PK���������!�2]���������������� �perl5/CPAN/Nox.pmnu�6$��������PK���������!�M :.��.�������������� �perl5/CPAN/Distroprefs.pmnu�6$��������PK���������!�UV��V��������������) �perl5/CPAN/Index.pmnu�6$��������PK���������!�4A'��'��������������% �perl5/CPAN/Bundle.pmnu�6$��������PK���������!�Y3�A���A�������������� �perl5/CPAN/Tarzip.pmnu�6$��������PK���������!�L��������������M �perl5/CPAN/Distribution.pmnu�6$��������PK���������!�:����������������r�perl5/CPAN/Complete.pmnu�6$��������PK���������!�hz.η����������������?�perl5/CPAN/FTP.pmnu�6$��������PK���������!�7=$�$�������������7�perl5/CPAN/FirstTime.pmnu�6$��������PK���������!�o�����������������perl5/CPAN/CacheMgr.pmnu�6$��������PK���������!�CvW��vW���������������perl5/CPAN/Module.pmnu�6$��������PK���������!�C �� ��������������*�perl5/CPAN/Plugin.pmnu�6$��������PK���������!�iۨD����������������Z7�perl5/CPAN/Distrostatus.pmnu�6$��������PK���������!�!+��������������p;�perl5/CPAN/Shell.pmnu�6$��������PK���������!�䍽������������������[�perl5/CPAN/DeferredCode.pmnu�6$��������PK���������!�B3����������������\�perl5/CPAN/Queue.pmnu�6$��������PK���������!�naX67��7��������������x�perl5/CPAN/Prompt.pmnu�6$��������PK���������!�bJG��JG�������������� {�perl5/CPAN/Mirrors.pmnu�6$��������PK���������!�< $l:M��:M��%�������������perl5/CPAN/Meta/Requirements/Range.pmnu�6$��������PK���������!�somFU��FU��������������>�perl5/CPAN/Meta/Requirements.pmnu�6$��������PK���������!�H�A�A� ������������e�perl5/CPAN.pmnu�6$��������PK���������!�g, �� ��<�������������perl5/x86_64-linux-thread-multi/.meta/CPAN-2.36/install.jsonnu�6$��������PK���������!�qA �� ��;�������������perl5/x86_64-linux-thread-multi/.meta/CPAN-2.36/MYMETA.jsonnu�6$��������PK���������!�n}����O������������ �perl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.143/install.jsonnu�6$��������PK���������!�&9~��~��N������������ �perl5/x86_64-linux-thread-multi/.meta/CPAN-Meta-Requirements-2.143/MYMETA.jsonnu�6$��������PK���������!� ����>�������������perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.20/install.jsonnu�6$��������PK���������!�ǽA��A��=�������������perl5/x86_64-linux-thread-multi/.meta/IO-Tty-1.20/MYMETA.jsonnu�6$��������PK���������!�������>������������@�perl5/x86_64-linux-thread-multi/.meta/Expect-1.38/install.jsonnu�6$��������PK���������!�!6��6��=������������_�perl5/x86_64-linux-thread-multi/.meta/Expect-1.38/MYMETA.jsonnu�6$��������PK���������!�s������B�������������perl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.088/install.jsonnu�6$��������PK���������!��1����A������������D�perl5/x86_64-linux-thread-multi/.meta/HTTP-Tiny-0.088/MYMETA.jsonnu�6$��������PK���������!�MH������H������������J�perl5/x86_64-linux-thread-multi/.meta/Canary-Stability-2013/install.jsonnu�6$��������PK���������!�QE����G�������������perl5/x86_64-linux-thread-multi/.meta/Canary-Stability-2013/MYMETA.jsonnu�6$��������PK���������!� k������D������������=�perl5/x86_64-linux-thread-multi/.meta/common-sense-3.75/install.jsonnu�6$��������PK���������!�PU?��?��C������������ �perl5/x86_64-linux-thread-multi/.meta/common-sense-3.75/MYMETA.jsonnu�6$��������PK���������!�:D����H������������5 �perl5/x86_64-linux-thread-multi/.meta/Types-Serialiser-1.01/install.jsonnu�6$��������PK���������!�V����G������������]�perl5/x86_64-linux-thread-multi/.meta/Types-Serialiser-1.01/MYMETA.jsonnu�6$��������PK���������!�G������?������������{�perl5/x86_64-linux-thread-multi/.meta/JSON-XS-4.03/install.jsonnu�6$��������PK���������!�| ����>�������������perl5/x86_64-linux-thread-multi/.meta/JSON-XS-4.03/MYMETA.jsonnu�6$��������PK���������!�?����E�������������perl5/x86_64-linux-thread-multi/.meta/local-lib-2.000029/install.jsonnu�6$��������PK���������!��VJ����D������������v�perl5/x86_64-linux-thread-multi/.meta/local-lib-2.000029/MYMETA.jsonnu�6$��������PK���������!�[& ������@������������!�perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.31/install.jsonnu�6$��������PK���������!�}t����?������������#�perl5/x86_64-linux-thread-multi/.meta/Try-Tiny-0.31/MYMETA.jsonnu�6$��������PK���������!�K |��|��A�������������perl5/x86_64-linux-thread-multi/.meta/version-0.9932/install.jsonnu�6$��������PK���������!�(����@�������������perl5/x86_64-linux-thread-multi/.meta/version-0.9932/MYMETA.jsonnu�6$��������PK���������!�\m��m��A�������������perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.34/install.jsonnu�6$��������PK���������!�Q^����@�������������perl5/x86_64-linux-thread-multi/.meta/YAML-Syck-1.34/MYMETA.jsonnu�6$��������PK���������!� ���������������perl5/Expect.pmnu�7m��������PK���������!�L=�=�������������{�perl5/HTTP/Tiny.pmnu�6$��������PK���������!�-*��*��������������%�perl5/Canary/Stability.pmnu�6$��������PK���������!�Wy�����������������perl5/Types/Serialiser/Error.pmnu�6$��������PK���������!�?#��#���������������perl5/Types/Serialiser.pmnu�6$��������PK���������!�( @��@���������������perl5/POD2/DE/local/lib.podnu�6$��������PK���������!�CP>��>��������������;�perl5/POD2/PT_BR/local/lib.podnu�6$��������PK���������!�4;{g �� ��������������z�perl5/lib/core/only.pmnu�6$��������PK���������!� O��O���������������perl5/local/lib.pmnu�6$��������PK���������!�X6qR��R��������������L*�perl5/Try/Tiny.pmnu�6$��������PK����x�x�-��$}���